Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- pllava/lib/python3.10/site-packages/sympy/codegen/__pycache__/__init__.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/__pycache__/approximations.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/__pycache__/cfunctions.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/__pycache__/cnodes.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/__pycache__/cutils.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/__pycache__/fnodes.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/__pycache__/numpy_nodes.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/__pycache__/rewriting.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/__pycache__/scipy_nodes.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/abstract_nodes.py +18 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/approximations.py +187 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/ast.py +1906 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/cnodes.py +156 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/cxxnodes.py +14 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/futils.py +40 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/matrix_nodes.py +71 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/numpy_nodes.py +110 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/pynodes.py +11 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/pyutils.py +24 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/rewriting.py +357 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/scipy_nodes.py +79 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/tests/__init__.py +0 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/tests/__pycache__/test_abstract_nodes.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/tests/__pycache__/test_approximations.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/tests/__pycache__/test_ast.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/tests/__pycache__/test_cxxnodes.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/tests/__pycache__/test_matrix_nodes.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/tests/__pycache__/test_numpy_nodes.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/tests/__pycache__/test_pyutils.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/tests/__pycache__/test_rewriting.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/tests/__pycache__/test_scipy_nodes.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/tests/test_abstract_nodes.py +14 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/tests/test_algorithms.py +179 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/tests/test_applications.py +57 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/tests/test_approximations.py +53 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/tests/test_ast.py +661 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/tests/test_cfunctions.py +165 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/tests/test_cnodes.py +112 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/tests/test_cxxnodes.py +14 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/tests/test_fnodes.py +213 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/tests/test_matrix_nodes.py +50 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/tests/test_numpy_nodes.py +50 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/tests/test_pynodes.py +13 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/tests/test_pyutils.py +7 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/tests/test_rewriting.py +479 -0
- pllava/lib/python3.10/site-packages/sympy/codegen/tests/test_scipy_nodes.py +44 -0
- pllava/lib/python3.10/site-packages/sympy/functions/combinatorial/__pycache__/__init__.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/functions/combinatorial/__pycache__/numbers.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/__pycache__/test_comb_factorials.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/functions/special/__pycache__/bessel.cpython-310.pyc +0 -0
pllava/lib/python3.10/site-packages/sympy/codegen/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (1.08 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/codegen/__pycache__/approximations.cpython-310.pyc
ADDED
|
Binary file (6.32 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/codegen/__pycache__/cfunctions.cpython-310.pyc
ADDED
|
Binary file (14.1 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/codegen/__pycache__/cnodes.cpython-310.pyc
ADDED
|
Binary file (4.88 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/codegen/__pycache__/cutils.cpython-310.pyc
ADDED
|
Binary file (704 Bytes). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/codegen/__pycache__/fnodes.cpython-310.pyc
ADDED
|
Binary file (21.2 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/codegen/__pycache__/numpy_nodes.cpython-310.pyc
ADDED
|
Binary file (3.83 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/codegen/__pycache__/rewriting.cpython-310.pyc
ADDED
|
Binary file (13.5 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/codegen/__pycache__/scipy_nodes.cpython-310.pyc
ADDED
|
Binary file (3.25 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/codegen/abstract_nodes.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""This module provides containers for python objects that are valid
|
| 2 |
+
printing targets but are not a subclass of SymPy's Printable.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
from sympy.core.containers import Tuple
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class List(Tuple):
|
| 10 |
+
"""Represents a (frozen) (Python) list (for code printing purposes)."""
|
| 11 |
+
def __eq__(self, other):
|
| 12 |
+
if isinstance(other, list):
|
| 13 |
+
return self == List(*other)
|
| 14 |
+
else:
|
| 15 |
+
return self.args == other
|
| 16 |
+
|
| 17 |
+
def __hash__(self):
|
| 18 |
+
return super().__hash__()
|
pllava/lib/python3.10/site-packages/sympy/codegen/approximations.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
from sympy.sets.sets import Interval
|
| 3 |
+
from sympy.calculus.singularities import is_increasing, is_decreasing
|
| 4 |
+
from sympy.codegen.rewriting import Optimization
|
| 5 |
+
from sympy.core.function import UndefinedFunction
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
This module collects classes useful for approimate rewriting of expressions.
|
| 9 |
+
This can be beneficial when generating numeric code for which performance is
|
| 10 |
+
of greater importance than precision (e.g. for preconditioners used in iterative
|
| 11 |
+
methods).
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
class SumApprox(Optimization):
|
| 15 |
+
"""
|
| 16 |
+
Approximates sum by neglecting small terms.
|
| 17 |
+
|
| 18 |
+
Explanation
|
| 19 |
+
===========
|
| 20 |
+
|
| 21 |
+
If terms are expressions which can be determined to be monotonic, then
|
| 22 |
+
bounds for those expressions are added.
|
| 23 |
+
|
| 24 |
+
Parameters
|
| 25 |
+
==========
|
| 26 |
+
|
| 27 |
+
bounds : dict
|
| 28 |
+
Mapping expressions to length 2 tuple of bounds (low, high).
|
| 29 |
+
reltol : number
|
| 30 |
+
Threshold for when to ignore a term. Taken relative to the largest
|
| 31 |
+
lower bound among bounds.
|
| 32 |
+
|
| 33 |
+
Examples
|
| 34 |
+
========
|
| 35 |
+
|
| 36 |
+
>>> from sympy import exp
|
| 37 |
+
>>> from sympy.abc import x, y, z
|
| 38 |
+
>>> from sympy.codegen.rewriting import optimize
|
| 39 |
+
>>> from sympy.codegen.approximations import SumApprox
|
| 40 |
+
>>> bounds = {x: (-1, 1), y: (1000, 2000), z: (-10, 3)}
|
| 41 |
+
>>> sum_approx3 = SumApprox(bounds, reltol=1e-3)
|
| 42 |
+
>>> sum_approx2 = SumApprox(bounds, reltol=1e-2)
|
| 43 |
+
>>> sum_approx1 = SumApprox(bounds, reltol=1e-1)
|
| 44 |
+
>>> expr = 3*(x + y + exp(z))
|
| 45 |
+
>>> optimize(expr, [sum_approx3])
|
| 46 |
+
3*(x + y + exp(z))
|
| 47 |
+
>>> optimize(expr, [sum_approx2])
|
| 48 |
+
3*y + 3*exp(z)
|
| 49 |
+
>>> optimize(expr, [sum_approx1])
|
| 50 |
+
3*y
|
| 51 |
+
|
| 52 |
+
"""
|
| 53 |
+
|
| 54 |
+
def __init__(self, bounds, reltol, **kwargs):
|
| 55 |
+
super().__init__(**kwargs)
|
| 56 |
+
self.bounds = bounds
|
| 57 |
+
self.reltol = reltol
|
| 58 |
+
|
| 59 |
+
def __call__(self, expr):
|
| 60 |
+
return expr.factor().replace(self.query, lambda arg: self.value(arg))
|
| 61 |
+
|
| 62 |
+
def query(self, expr):
|
| 63 |
+
return expr.is_Add
|
| 64 |
+
|
| 65 |
+
def value(self, add):
|
| 66 |
+
for term in add.args:
|
| 67 |
+
if term.is_number or term in self.bounds or len(term.free_symbols) != 1:
|
| 68 |
+
continue
|
| 69 |
+
fs, = term.free_symbols
|
| 70 |
+
if fs not in self.bounds:
|
| 71 |
+
continue
|
| 72 |
+
intrvl = Interval(*self.bounds[fs])
|
| 73 |
+
if is_increasing(term, intrvl, fs):
|
| 74 |
+
self.bounds[term] = (
|
| 75 |
+
term.subs({fs: self.bounds[fs][0]}),
|
| 76 |
+
term.subs({fs: self.bounds[fs][1]})
|
| 77 |
+
)
|
| 78 |
+
elif is_decreasing(term, intrvl, fs):
|
| 79 |
+
self.bounds[term] = (
|
| 80 |
+
term.subs({fs: self.bounds[fs][1]}),
|
| 81 |
+
term.subs({fs: self.bounds[fs][0]})
|
| 82 |
+
)
|
| 83 |
+
else:
|
| 84 |
+
return add
|
| 85 |
+
|
| 86 |
+
if all(term.is_number or term in self.bounds for term in add.args):
|
| 87 |
+
bounds = [(term, term) if term.is_number else self.bounds[term] for term in add.args]
|
| 88 |
+
largest_abs_guarantee = 0
|
| 89 |
+
for lo, hi in bounds:
|
| 90 |
+
if lo <= 0 <= hi:
|
| 91 |
+
continue
|
| 92 |
+
largest_abs_guarantee = max(largest_abs_guarantee,
|
| 93 |
+
min(abs(lo), abs(hi)))
|
| 94 |
+
new_terms = []
|
| 95 |
+
for term, (lo, hi) in zip(add.args, bounds):
|
| 96 |
+
if max(abs(lo), abs(hi)) >= largest_abs_guarantee*self.reltol:
|
| 97 |
+
new_terms.append(term)
|
| 98 |
+
return add.func(*new_terms)
|
| 99 |
+
else:
|
| 100 |
+
return add
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class SeriesApprox(Optimization):
|
| 104 |
+
""" Approximates functions by expanding them as a series.
|
| 105 |
+
|
| 106 |
+
Parameters
|
| 107 |
+
==========
|
| 108 |
+
|
| 109 |
+
bounds : dict
|
| 110 |
+
Mapping expressions to length 2 tuple of bounds (low, high).
|
| 111 |
+
reltol : number
|
| 112 |
+
Threshold for when to ignore a term. Taken relative to the largest
|
| 113 |
+
lower bound among bounds.
|
| 114 |
+
max_order : int
|
| 115 |
+
Largest order to include in series expansion
|
| 116 |
+
n_point_checks : int (even)
|
| 117 |
+
The validity of an expansion (with respect to reltol) is checked at
|
| 118 |
+
discrete points (linearly spaced over the bounds of the variable). The
|
| 119 |
+
number of points used in this numerical check is given by this number.
|
| 120 |
+
|
| 121 |
+
Examples
|
| 122 |
+
========
|
| 123 |
+
|
| 124 |
+
>>> from sympy import sin, pi
|
| 125 |
+
>>> from sympy.abc import x, y
|
| 126 |
+
>>> from sympy.codegen.rewriting import optimize
|
| 127 |
+
>>> from sympy.codegen.approximations import SeriesApprox
|
| 128 |
+
>>> bounds = {x: (-.1, .1), y: (pi-1, pi+1)}
|
| 129 |
+
>>> series_approx2 = SeriesApprox(bounds, reltol=1e-2)
|
| 130 |
+
>>> series_approx3 = SeriesApprox(bounds, reltol=1e-3)
|
| 131 |
+
>>> series_approx8 = SeriesApprox(bounds, reltol=1e-8)
|
| 132 |
+
>>> expr = sin(x)*sin(y)
|
| 133 |
+
>>> optimize(expr, [series_approx2])
|
| 134 |
+
x*(-y + (y - pi)**3/6 + pi)
|
| 135 |
+
>>> optimize(expr, [series_approx3])
|
| 136 |
+
(-x**3/6 + x)*sin(y)
|
| 137 |
+
>>> optimize(expr, [series_approx8])
|
| 138 |
+
sin(x)*sin(y)
|
| 139 |
+
|
| 140 |
+
"""
|
| 141 |
+
def __init__(self, bounds, reltol, max_order=4, n_point_checks=4, **kwargs):
|
| 142 |
+
super().__init__(**kwargs)
|
| 143 |
+
self.bounds = bounds
|
| 144 |
+
self.reltol = reltol
|
| 145 |
+
self.max_order = max_order
|
| 146 |
+
if n_point_checks % 2 == 1:
|
| 147 |
+
raise ValueError("Checking the solution at expansion point is not helpful")
|
| 148 |
+
self.n_point_checks = n_point_checks
|
| 149 |
+
self._prec = math.ceil(-math.log10(self.reltol))
|
| 150 |
+
|
| 151 |
+
def __call__(self, expr):
|
| 152 |
+
return expr.factor().replace(self.query, lambda arg: self.value(arg))
|
| 153 |
+
|
| 154 |
+
def query(self, expr):
|
| 155 |
+
return (expr.is_Function and not isinstance(expr, UndefinedFunction)
|
| 156 |
+
and len(expr.args) == 1)
|
| 157 |
+
|
| 158 |
+
def value(self, fexpr):
|
| 159 |
+
free_symbols = fexpr.free_symbols
|
| 160 |
+
if len(free_symbols) != 1:
|
| 161 |
+
return fexpr
|
| 162 |
+
symb, = free_symbols
|
| 163 |
+
if symb not in self.bounds:
|
| 164 |
+
return fexpr
|
| 165 |
+
lo, hi = self.bounds[symb]
|
| 166 |
+
x0 = (lo + hi)/2
|
| 167 |
+
cheapest = None
|
| 168 |
+
for n in range(self.max_order+1, 0, -1):
|
| 169 |
+
fseri = fexpr.series(symb, x0=x0, n=n).removeO()
|
| 170 |
+
n_ok = True
|
| 171 |
+
for idx in range(self.n_point_checks):
|
| 172 |
+
x = lo + idx*(hi - lo)/(self.n_point_checks - 1)
|
| 173 |
+
val = fseri.xreplace({symb: x})
|
| 174 |
+
ref = fexpr.xreplace({symb: x})
|
| 175 |
+
if abs((1 - val/ref).evalf(self._prec)) > self.reltol:
|
| 176 |
+
n_ok = False
|
| 177 |
+
break
|
| 178 |
+
|
| 179 |
+
if n_ok:
|
| 180 |
+
cheapest = fseri
|
| 181 |
+
else:
|
| 182 |
+
break
|
| 183 |
+
|
| 184 |
+
if cheapest is None:
|
| 185 |
+
return fexpr
|
| 186 |
+
else:
|
| 187 |
+
return cheapest
|
pllava/lib/python3.10/site-packages/sympy/codegen/ast.py
ADDED
|
@@ -0,0 +1,1906 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Types used to represent a full function/module as an Abstract Syntax Tree.
|
| 3 |
+
|
| 4 |
+
Most types are small, and are merely used as tokens in the AST. A tree diagram
|
| 5 |
+
has been included below to illustrate the relationships between the AST types.
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
AST Type Tree
|
| 9 |
+
-------------
|
| 10 |
+
::
|
| 11 |
+
|
| 12 |
+
*Basic*
|
| 13 |
+
|
|
| 14 |
+
|
|
| 15 |
+
CodegenAST
|
| 16 |
+
|
|
| 17 |
+
|--->AssignmentBase
|
| 18 |
+
| |--->Assignment
|
| 19 |
+
| |--->AugmentedAssignment
|
| 20 |
+
| |--->AddAugmentedAssignment
|
| 21 |
+
| |--->SubAugmentedAssignment
|
| 22 |
+
| |--->MulAugmentedAssignment
|
| 23 |
+
| |--->DivAugmentedAssignment
|
| 24 |
+
| |--->ModAugmentedAssignment
|
| 25 |
+
|
|
| 26 |
+
|--->CodeBlock
|
| 27 |
+
|
|
| 28 |
+
|
|
| 29 |
+
|--->Token
|
| 30 |
+
|--->Attribute
|
| 31 |
+
|--->For
|
| 32 |
+
|--->String
|
| 33 |
+
| |--->QuotedString
|
| 34 |
+
| |--->Comment
|
| 35 |
+
|--->Type
|
| 36 |
+
| |--->IntBaseType
|
| 37 |
+
| | |--->_SizedIntType
|
| 38 |
+
| | |--->SignedIntType
|
| 39 |
+
| | |--->UnsignedIntType
|
| 40 |
+
| |--->FloatBaseType
|
| 41 |
+
| |--->FloatType
|
| 42 |
+
| |--->ComplexBaseType
|
| 43 |
+
| |--->ComplexType
|
| 44 |
+
|--->Node
|
| 45 |
+
| |--->Variable
|
| 46 |
+
| | |---> Pointer
|
| 47 |
+
| |--->FunctionPrototype
|
| 48 |
+
| |--->FunctionDefinition
|
| 49 |
+
|--->Element
|
| 50 |
+
|--->Declaration
|
| 51 |
+
|--->While
|
| 52 |
+
|--->Scope
|
| 53 |
+
|--->Stream
|
| 54 |
+
|--->Print
|
| 55 |
+
|--->FunctionCall
|
| 56 |
+
|--->BreakToken
|
| 57 |
+
|--->ContinueToken
|
| 58 |
+
|--->NoneToken
|
| 59 |
+
|--->Return
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
Predefined types
|
| 63 |
+
----------------
|
| 64 |
+
|
| 65 |
+
A number of ``Type`` instances are provided in the ``sympy.codegen.ast`` module
|
| 66 |
+
for convenience. Perhaps the two most common ones for code-generation (of numeric
|
| 67 |
+
codes) are ``float32`` and ``float64`` (known as single and double precision respectively).
|
| 68 |
+
There are also precision generic versions of Types (for which the codeprinters selects the
|
| 69 |
+
underlying data type at time of printing): ``real``, ``integer``, ``complex_``, ``bool_``.
|
| 70 |
+
|
| 71 |
+
The other ``Type`` instances defined are:
|
| 72 |
+
|
| 73 |
+
- ``intc``: Integer type used by C's "int".
|
| 74 |
+
- ``intp``: Integer type used by C's "unsigned".
|
| 75 |
+
- ``int8``, ``int16``, ``int32``, ``int64``: n-bit integers.
|
| 76 |
+
- ``uint8``, ``uint16``, ``uint32``, ``uint64``: n-bit unsigned integers.
|
| 77 |
+
- ``float80``: known as "extended precision" on modern x86/amd64 hardware.
|
| 78 |
+
- ``complex64``: Complex number represented by two ``float32`` numbers
|
| 79 |
+
- ``complex128``: Complex number represented by two ``float64`` numbers
|
| 80 |
+
|
| 81 |
+
Using the nodes
|
| 82 |
+
---------------
|
| 83 |
+
|
| 84 |
+
It is possible to construct simple algorithms using the AST nodes. Let's construct a loop applying
|
| 85 |
+
Newton's method::
|
| 86 |
+
|
| 87 |
+
>>> from sympy import symbols, cos
|
| 88 |
+
>>> from sympy.codegen.ast import While, Assignment, aug_assign, Print, QuotedString
|
| 89 |
+
>>> t, dx, x = symbols('tol delta val')
|
| 90 |
+
>>> expr = cos(x) - x**3
|
| 91 |
+
>>> whl = While(abs(dx) > t, [
|
| 92 |
+
... Assignment(dx, -expr/expr.diff(x)),
|
| 93 |
+
... aug_assign(x, '+', dx),
|
| 94 |
+
... Print([x])
|
| 95 |
+
... ])
|
| 96 |
+
>>> from sympy import pycode
|
| 97 |
+
>>> py_str = pycode(whl)
|
| 98 |
+
>>> print(py_str)
|
| 99 |
+
while (abs(delta) > tol):
|
| 100 |
+
delta = (val**3 - math.cos(val))/(-3*val**2 - math.sin(val))
|
| 101 |
+
val += delta
|
| 102 |
+
print(val)
|
| 103 |
+
>>> import math
|
| 104 |
+
>>> tol, val, delta = 1e-5, 0.5, float('inf')
|
| 105 |
+
>>> exec(py_str)
|
| 106 |
+
1.1121416371
|
| 107 |
+
0.909672693737
|
| 108 |
+
0.867263818209
|
| 109 |
+
0.865477135298
|
| 110 |
+
0.865474033111
|
| 111 |
+
>>> print('%3.1g' % (math.cos(val) - val**3))
|
| 112 |
+
-3e-11
|
| 113 |
+
|
| 114 |
+
If we want to generate Fortran code for the same while loop we simple call ``fcode``::
|
| 115 |
+
|
| 116 |
+
>>> from sympy import fcode
|
| 117 |
+
>>> print(fcode(whl, standard=2003, source_format='free'))
|
| 118 |
+
do while (abs(delta) > tol)
|
| 119 |
+
delta = (val**3 - cos(val))/(-3*val**2 - sin(val))
|
| 120 |
+
val = val + delta
|
| 121 |
+
print *, val
|
| 122 |
+
end do
|
| 123 |
+
|
| 124 |
+
There is a function constructing a loop (or a complete function) like this in
|
| 125 |
+
:mod:`sympy.codegen.algorithms`.
|
| 126 |
+
|
| 127 |
+
"""
|
| 128 |
+
|
| 129 |
+
from __future__ import annotations
|
| 130 |
+
from typing import Any
|
| 131 |
+
|
| 132 |
+
from collections import defaultdict
|
| 133 |
+
|
| 134 |
+
from sympy.core.relational import (Ge, Gt, Le, Lt)
|
| 135 |
+
from sympy.core import Symbol, Tuple, Dummy
|
| 136 |
+
from sympy.core.basic import Basic
|
| 137 |
+
from sympy.core.expr import Expr, Atom
|
| 138 |
+
from sympy.core.numbers import Float, Integer, oo
|
| 139 |
+
from sympy.core.sympify import _sympify, sympify, SympifyError
|
| 140 |
+
from sympy.utilities.iterables import (iterable, topological_sort,
|
| 141 |
+
numbered_symbols, filter_symbols)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def _mk_Tuple(args):
|
| 145 |
+
"""
|
| 146 |
+
Create a SymPy Tuple object from an iterable, converting Python strings to
|
| 147 |
+
AST strings.
|
| 148 |
+
|
| 149 |
+
Parameters
|
| 150 |
+
==========
|
| 151 |
+
|
| 152 |
+
args: iterable
|
| 153 |
+
Arguments to :class:`sympy.Tuple`.
|
| 154 |
+
|
| 155 |
+
Returns
|
| 156 |
+
=======
|
| 157 |
+
|
| 158 |
+
sympy.Tuple
|
| 159 |
+
"""
|
| 160 |
+
args = [String(arg) if isinstance(arg, str) else arg for arg in args]
|
| 161 |
+
return Tuple(*args)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
class CodegenAST(Basic):
|
| 165 |
+
__slots__ = ()
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
class Token(CodegenAST):
|
| 169 |
+
""" Base class for the AST types.
|
| 170 |
+
|
| 171 |
+
Explanation
|
| 172 |
+
===========
|
| 173 |
+
|
| 174 |
+
Defining fields are set in ``_fields``. Attributes (defined in _fields)
|
| 175 |
+
are only allowed to contain instances of Basic (unless atomic, see
|
| 176 |
+
``String``). The arguments to ``__new__()`` correspond to the attributes in
|
| 177 |
+
the order defined in ``_fields`. The ``defaults`` class attribute is a
|
| 178 |
+
dictionary mapping attribute names to their default values.
|
| 179 |
+
|
| 180 |
+
Subclasses should not need to override the ``__new__()`` method. They may
|
| 181 |
+
define a class or static method named ``_construct_<attr>`` for each
|
| 182 |
+
attribute to process the value passed to ``__new__()``. Attributes listed
|
| 183 |
+
in the class attribute ``not_in_args`` are not passed to :class:`~.Basic`.
|
| 184 |
+
"""
|
| 185 |
+
|
| 186 |
+
__slots__: tuple[str, ...] = ()
|
| 187 |
+
_fields = __slots__
|
| 188 |
+
defaults: dict[str, Any] = {}
|
| 189 |
+
not_in_args: list[str] = []
|
| 190 |
+
indented_args = ['body']
|
| 191 |
+
|
| 192 |
+
@property
|
| 193 |
+
def is_Atom(self):
|
| 194 |
+
return len(self._fields) == 0
|
| 195 |
+
|
| 196 |
+
@classmethod
|
| 197 |
+
def _get_constructor(cls, attr):
|
| 198 |
+
""" Get the constructor function for an attribute by name. """
|
| 199 |
+
return getattr(cls, '_construct_%s' % attr, lambda x: x)
|
| 200 |
+
|
| 201 |
+
@classmethod
|
| 202 |
+
def _construct(cls, attr, arg):
|
| 203 |
+
""" Construct an attribute value from argument passed to ``__new__()``. """
|
| 204 |
+
# arg may be ``NoneToken()``, so comparison is done using == instead of ``is`` operator
|
| 205 |
+
if arg == None:
|
| 206 |
+
return cls.defaults.get(attr, none)
|
| 207 |
+
else:
|
| 208 |
+
if isinstance(arg, Dummy): # SymPy's replace uses Dummy instances
|
| 209 |
+
return arg
|
| 210 |
+
else:
|
| 211 |
+
return cls._get_constructor(attr)(arg)
|
| 212 |
+
|
| 213 |
+
def __new__(cls, *args, **kwargs):
|
| 214 |
+
# Pass through existing instances when given as sole argument
|
| 215 |
+
if len(args) == 1 and not kwargs and isinstance(args[0], cls):
|
| 216 |
+
return args[0]
|
| 217 |
+
|
| 218 |
+
if len(args) > len(cls._fields):
|
| 219 |
+
raise ValueError("Too many arguments (%d), expected at most %d" % (len(args), len(cls._fields)))
|
| 220 |
+
|
| 221 |
+
attrvals = []
|
| 222 |
+
|
| 223 |
+
# Process positional arguments
|
| 224 |
+
for attrname, argval in zip(cls._fields, args):
|
| 225 |
+
if attrname in kwargs:
|
| 226 |
+
raise TypeError('Got multiple values for attribute %r' % attrname)
|
| 227 |
+
|
| 228 |
+
attrvals.append(cls._construct(attrname, argval))
|
| 229 |
+
|
| 230 |
+
# Process keyword arguments
|
| 231 |
+
for attrname in cls._fields[len(args):]:
|
| 232 |
+
if attrname in kwargs:
|
| 233 |
+
argval = kwargs.pop(attrname)
|
| 234 |
+
|
| 235 |
+
elif attrname in cls.defaults:
|
| 236 |
+
argval = cls.defaults[attrname]
|
| 237 |
+
|
| 238 |
+
else:
|
| 239 |
+
raise TypeError('No value for %r given and attribute has no default' % attrname)
|
| 240 |
+
|
| 241 |
+
attrvals.append(cls._construct(attrname, argval))
|
| 242 |
+
|
| 243 |
+
if kwargs:
|
| 244 |
+
raise ValueError("Unknown keyword arguments: %s" % ' '.join(kwargs))
|
| 245 |
+
|
| 246 |
+
# Parent constructor
|
| 247 |
+
basic_args = [
|
| 248 |
+
val for attr, val in zip(cls._fields, attrvals)
|
| 249 |
+
if attr not in cls.not_in_args
|
| 250 |
+
]
|
| 251 |
+
obj = CodegenAST.__new__(cls, *basic_args)
|
| 252 |
+
|
| 253 |
+
# Set attributes
|
| 254 |
+
for attr, arg in zip(cls._fields, attrvals):
|
| 255 |
+
setattr(obj, attr, arg)
|
| 256 |
+
|
| 257 |
+
return obj
|
| 258 |
+
|
| 259 |
+
def __eq__(self, other):
|
| 260 |
+
if not isinstance(other, self.__class__):
|
| 261 |
+
return False
|
| 262 |
+
for attr in self._fields:
|
| 263 |
+
if getattr(self, attr) != getattr(other, attr):
|
| 264 |
+
return False
|
| 265 |
+
return True
|
| 266 |
+
|
| 267 |
+
def _hashable_content(self):
|
| 268 |
+
return tuple([getattr(self, attr) for attr in self._fields])
|
| 269 |
+
|
| 270 |
+
def __hash__(self):
|
| 271 |
+
return super().__hash__()
|
| 272 |
+
|
| 273 |
+
def _joiner(self, k, indent_level):
|
| 274 |
+
return (',\n' + ' '*indent_level) if k in self.indented_args else ', '
|
| 275 |
+
|
| 276 |
+
def _indented(self, printer, k, v, *args, **kwargs):
|
| 277 |
+
il = printer._context['indent_level']
|
| 278 |
+
def _print(arg):
|
| 279 |
+
if isinstance(arg, Token):
|
| 280 |
+
return printer._print(arg, *args, joiner=self._joiner(k, il), **kwargs)
|
| 281 |
+
else:
|
| 282 |
+
return printer._print(arg, *args, **kwargs)
|
| 283 |
+
|
| 284 |
+
if isinstance(v, Tuple):
|
| 285 |
+
joined = self._joiner(k, il).join([_print(arg) for arg in v.args])
|
| 286 |
+
if k in self.indented_args:
|
| 287 |
+
return '(\n' + ' '*il + joined + ',\n' + ' '*(il - 4) + ')'
|
| 288 |
+
else:
|
| 289 |
+
return ('({0},)' if len(v.args) == 1 else '({0})').format(joined)
|
| 290 |
+
else:
|
| 291 |
+
return _print(v)
|
| 292 |
+
|
| 293 |
+
def _sympyrepr(self, printer, *args, joiner=', ', **kwargs):
|
| 294 |
+
from sympy.printing.printer import printer_context
|
| 295 |
+
exclude = kwargs.get('exclude', ())
|
| 296 |
+
values = [getattr(self, k) for k in self._fields]
|
| 297 |
+
indent_level = printer._context.get('indent_level', 0)
|
| 298 |
+
|
| 299 |
+
arg_reprs = []
|
| 300 |
+
|
| 301 |
+
for i, (attr, value) in enumerate(zip(self._fields, values)):
|
| 302 |
+
if attr in exclude:
|
| 303 |
+
continue
|
| 304 |
+
|
| 305 |
+
# Skip attributes which have the default value
|
| 306 |
+
if attr in self.defaults and value == self.defaults[attr]:
|
| 307 |
+
continue
|
| 308 |
+
|
| 309 |
+
ilvl = indent_level + 4 if attr in self.indented_args else 0
|
| 310 |
+
with printer_context(printer, indent_level=ilvl):
|
| 311 |
+
indented = self._indented(printer, attr, value, *args, **kwargs)
|
| 312 |
+
arg_reprs.append(('{1}' if i == 0 else '{0}={1}').format(attr, indented.lstrip()))
|
| 313 |
+
|
| 314 |
+
return "{}({})".format(self.__class__.__name__, joiner.join(arg_reprs))
|
| 315 |
+
|
| 316 |
+
_sympystr = _sympyrepr
|
| 317 |
+
|
| 318 |
+
def __repr__(self): # sympy.core.Basic.__repr__ uses sstr
|
| 319 |
+
from sympy.printing import srepr
|
| 320 |
+
return srepr(self)
|
| 321 |
+
|
| 322 |
+
def kwargs(self, exclude=(), apply=None):
|
| 323 |
+
""" Get instance's attributes as dict of keyword arguments.
|
| 324 |
+
|
| 325 |
+
Parameters
|
| 326 |
+
==========
|
| 327 |
+
|
| 328 |
+
exclude : collection of str
|
| 329 |
+
Collection of keywords to exclude.
|
| 330 |
+
|
| 331 |
+
apply : callable, optional
|
| 332 |
+
Function to apply to all values.
|
| 333 |
+
"""
|
| 334 |
+
kwargs = {k: getattr(self, k) for k in self._fields if k not in exclude}
|
| 335 |
+
if apply is not None:
|
| 336 |
+
return {k: apply(v) for k, v in kwargs.items()}
|
| 337 |
+
else:
|
| 338 |
+
return kwargs
|
| 339 |
+
|
| 340 |
+
class BreakToken(Token):
|
| 341 |
+
""" Represents 'break' in C/Python ('exit' in Fortran).
|
| 342 |
+
|
| 343 |
+
Use the premade instance ``break_`` or instantiate manually.
|
| 344 |
+
|
| 345 |
+
Examples
|
| 346 |
+
========
|
| 347 |
+
|
| 348 |
+
>>> from sympy import ccode, fcode
|
| 349 |
+
>>> from sympy.codegen.ast import break_
|
| 350 |
+
>>> ccode(break_)
|
| 351 |
+
'break'
|
| 352 |
+
>>> fcode(break_, source_format='free')
|
| 353 |
+
'exit'
|
| 354 |
+
"""
|
| 355 |
+
|
| 356 |
+
break_ = BreakToken()
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
class ContinueToken(Token):
|
| 360 |
+
""" Represents 'continue' in C/Python ('cycle' in Fortran)
|
| 361 |
+
|
| 362 |
+
Use the premade instance ``continue_`` or instantiate manually.
|
| 363 |
+
|
| 364 |
+
Examples
|
| 365 |
+
========
|
| 366 |
+
|
| 367 |
+
>>> from sympy import ccode, fcode
|
| 368 |
+
>>> from sympy.codegen.ast import continue_
|
| 369 |
+
>>> ccode(continue_)
|
| 370 |
+
'continue'
|
| 371 |
+
>>> fcode(continue_, source_format='free')
|
| 372 |
+
'cycle'
|
| 373 |
+
"""
|
| 374 |
+
|
| 375 |
+
continue_ = ContinueToken()
|
| 376 |
+
|
| 377 |
+
class NoneToken(Token):
|
| 378 |
+
""" The AST equivalence of Python's NoneType
|
| 379 |
+
|
| 380 |
+
The corresponding instance of Python's ``None`` is ``none``.
|
| 381 |
+
|
| 382 |
+
Examples
|
| 383 |
+
========
|
| 384 |
+
|
| 385 |
+
>>> from sympy.codegen.ast import none, Variable
|
| 386 |
+
>>> from sympy import pycode
|
| 387 |
+
>>> print(pycode(Variable('x').as_Declaration(value=none)))
|
| 388 |
+
x = None
|
| 389 |
+
|
| 390 |
+
"""
|
| 391 |
+
def __eq__(self, other):
|
| 392 |
+
return other is None or isinstance(other, NoneToken)
|
| 393 |
+
|
| 394 |
+
def _hashable_content(self):
|
| 395 |
+
return ()
|
| 396 |
+
|
| 397 |
+
def __hash__(self):
|
| 398 |
+
return super().__hash__()
|
| 399 |
+
|
| 400 |
+
|
| 401 |
+
none = NoneToken()
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
class AssignmentBase(CodegenAST):
|
| 405 |
+
""" Abstract base class for Assignment and AugmentedAssignment.
|
| 406 |
+
|
| 407 |
+
Attributes:
|
| 408 |
+
===========
|
| 409 |
+
|
| 410 |
+
op : str
|
| 411 |
+
Symbol for assignment operator, e.g. "=", "+=", etc.
|
| 412 |
+
"""
|
| 413 |
+
|
| 414 |
+
def __new__(cls, lhs, rhs):
|
| 415 |
+
lhs = _sympify(lhs)
|
| 416 |
+
rhs = _sympify(rhs)
|
| 417 |
+
|
| 418 |
+
cls._check_args(lhs, rhs)
|
| 419 |
+
|
| 420 |
+
return super().__new__(cls, lhs, rhs)
|
| 421 |
+
|
| 422 |
+
@property
|
| 423 |
+
def lhs(self):
|
| 424 |
+
return self.args[0]
|
| 425 |
+
|
| 426 |
+
@property
|
| 427 |
+
def rhs(self):
|
| 428 |
+
return self.args[1]
|
| 429 |
+
|
| 430 |
+
@classmethod
|
| 431 |
+
def _check_args(cls, lhs, rhs):
|
| 432 |
+
""" Check arguments to __new__ and raise exception if any problems found.
|
| 433 |
+
|
| 434 |
+
Derived classes may wish to override this.
|
| 435 |
+
"""
|
| 436 |
+
from sympy.matrices.expressions.matexpr import (
|
| 437 |
+
MatrixElement, MatrixSymbol)
|
| 438 |
+
from sympy.tensor.indexed import Indexed
|
| 439 |
+
from sympy.tensor.array.expressions import ArrayElement
|
| 440 |
+
|
| 441 |
+
# Tuple of things that can be on the lhs of an assignment
|
| 442 |
+
assignable = (Symbol, MatrixSymbol, MatrixElement, Indexed, Element, Variable,
|
| 443 |
+
ArrayElement)
|
| 444 |
+
if not isinstance(lhs, assignable):
|
| 445 |
+
raise TypeError("Cannot assign to lhs of type %s." % type(lhs))
|
| 446 |
+
|
| 447 |
+
# Indexed types implement shape, but don't define it until later. This
|
| 448 |
+
# causes issues in assignment validation. For now, matrices are defined
|
| 449 |
+
# as anything with a shape that is not an Indexed
|
| 450 |
+
lhs_is_mat = hasattr(lhs, 'shape') and not isinstance(lhs, Indexed)
|
| 451 |
+
rhs_is_mat = hasattr(rhs, 'shape') and not isinstance(rhs, Indexed)
|
| 452 |
+
|
| 453 |
+
# If lhs and rhs have same structure, then this assignment is ok
|
| 454 |
+
if lhs_is_mat:
|
| 455 |
+
if not rhs_is_mat:
|
| 456 |
+
raise ValueError("Cannot assign a scalar to a matrix.")
|
| 457 |
+
elif lhs.shape != rhs.shape:
|
| 458 |
+
raise ValueError("Dimensions of lhs and rhs do not align.")
|
| 459 |
+
elif rhs_is_mat and not lhs_is_mat:
|
| 460 |
+
raise ValueError("Cannot assign a matrix to a scalar.")
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
class Assignment(AssignmentBase):
|
| 464 |
+
"""
|
| 465 |
+
Represents variable assignment for code generation.
|
| 466 |
+
|
| 467 |
+
Parameters
|
| 468 |
+
==========
|
| 469 |
+
|
| 470 |
+
lhs : Expr
|
| 471 |
+
SymPy object representing the lhs of the expression. These should be
|
| 472 |
+
singular objects, such as one would use in writing code. Notable types
|
| 473 |
+
include Symbol, MatrixSymbol, MatrixElement, and Indexed. Types that
|
| 474 |
+
subclass these types are also supported.
|
| 475 |
+
|
| 476 |
+
rhs : Expr
|
| 477 |
+
SymPy object representing the rhs of the expression. This can be any
|
| 478 |
+
type, provided its shape corresponds to that of the lhs. For example,
|
| 479 |
+
a Matrix type can be assigned to MatrixSymbol, but not to Symbol, as
|
| 480 |
+
the dimensions will not align.
|
| 481 |
+
|
| 482 |
+
Examples
|
| 483 |
+
========
|
| 484 |
+
|
| 485 |
+
>>> from sympy import symbols, MatrixSymbol, Matrix
|
| 486 |
+
>>> from sympy.codegen.ast import Assignment
|
| 487 |
+
>>> x, y, z = symbols('x, y, z')
|
| 488 |
+
>>> Assignment(x, y)
|
| 489 |
+
Assignment(x, y)
|
| 490 |
+
>>> Assignment(x, 0)
|
| 491 |
+
Assignment(x, 0)
|
| 492 |
+
>>> A = MatrixSymbol('A', 1, 3)
|
| 493 |
+
>>> mat = Matrix([x, y, z]).T
|
| 494 |
+
>>> Assignment(A, mat)
|
| 495 |
+
Assignment(A, Matrix([[x, y, z]]))
|
| 496 |
+
>>> Assignment(A[0, 1], x)
|
| 497 |
+
Assignment(A[0, 1], x)
|
| 498 |
+
"""
|
| 499 |
+
|
| 500 |
+
op = ':='
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
class AugmentedAssignment(AssignmentBase):
|
| 504 |
+
"""
|
| 505 |
+
Base class for augmented assignments.
|
| 506 |
+
|
| 507 |
+
Attributes:
|
| 508 |
+
===========
|
| 509 |
+
|
| 510 |
+
binop : str
|
| 511 |
+
Symbol for binary operation being applied in the assignment, such as "+",
|
| 512 |
+
"*", etc.
|
| 513 |
+
"""
|
| 514 |
+
binop = None # type: str
|
| 515 |
+
|
| 516 |
+
@property
|
| 517 |
+
def op(self):
|
| 518 |
+
return self.binop + '='
|
| 519 |
+
|
| 520 |
+
|
| 521 |
+
class AddAugmentedAssignment(AugmentedAssignment):
|
| 522 |
+
binop = '+'
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
class SubAugmentedAssignment(AugmentedAssignment):
|
| 526 |
+
binop = '-'
|
| 527 |
+
|
| 528 |
+
|
| 529 |
+
class MulAugmentedAssignment(AugmentedAssignment):
|
| 530 |
+
binop = '*'
|
| 531 |
+
|
| 532 |
+
|
| 533 |
+
class DivAugmentedAssignment(AugmentedAssignment):
|
| 534 |
+
binop = '/'
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
class ModAugmentedAssignment(AugmentedAssignment):
|
| 538 |
+
binop = '%'
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
# Mapping from binary op strings to AugmentedAssignment subclasses
|
| 542 |
+
augassign_classes = {
|
| 543 |
+
cls.binop: cls for cls in [
|
| 544 |
+
AddAugmentedAssignment, SubAugmentedAssignment, MulAugmentedAssignment,
|
| 545 |
+
DivAugmentedAssignment, ModAugmentedAssignment
|
| 546 |
+
]
|
| 547 |
+
}
|
| 548 |
+
|
| 549 |
+
|
| 550 |
+
def aug_assign(lhs, op, rhs):
|
| 551 |
+
"""
|
| 552 |
+
Create 'lhs op= rhs'.
|
| 553 |
+
|
| 554 |
+
Explanation
|
| 555 |
+
===========
|
| 556 |
+
|
| 557 |
+
Represents augmented variable assignment for code generation. This is a
|
| 558 |
+
convenience function. You can also use the AugmentedAssignment classes
|
| 559 |
+
directly, like AddAugmentedAssignment(x, y).
|
| 560 |
+
|
| 561 |
+
Parameters
|
| 562 |
+
==========
|
| 563 |
+
|
| 564 |
+
lhs : Expr
|
| 565 |
+
SymPy object representing the lhs of the expression. These should be
|
| 566 |
+
singular objects, such as one would use in writing code. Notable types
|
| 567 |
+
include Symbol, MatrixSymbol, MatrixElement, and Indexed. Types that
|
| 568 |
+
subclass these types are also supported.
|
| 569 |
+
|
| 570 |
+
op : str
|
| 571 |
+
Operator (+, -, /, \\*, %).
|
| 572 |
+
|
| 573 |
+
rhs : Expr
|
| 574 |
+
SymPy object representing the rhs of the expression. This can be any
|
| 575 |
+
type, provided its shape corresponds to that of the lhs. For example,
|
| 576 |
+
a Matrix type can be assigned to MatrixSymbol, but not to Symbol, as
|
| 577 |
+
the dimensions will not align.
|
| 578 |
+
|
| 579 |
+
Examples
|
| 580 |
+
========
|
| 581 |
+
|
| 582 |
+
>>> from sympy import symbols
|
| 583 |
+
>>> from sympy.codegen.ast import aug_assign
|
| 584 |
+
>>> x, y = symbols('x, y')
|
| 585 |
+
>>> aug_assign(x, '+', y)
|
| 586 |
+
AddAugmentedAssignment(x, y)
|
| 587 |
+
"""
|
| 588 |
+
if op not in augassign_classes:
|
| 589 |
+
raise ValueError("Unrecognized operator %s" % op)
|
| 590 |
+
return augassign_classes[op](lhs, rhs)
|
| 591 |
+
|
| 592 |
+
|
| 593 |
+
class CodeBlock(CodegenAST):
|
| 594 |
+
"""
|
| 595 |
+
Represents a block of code.
|
| 596 |
+
|
| 597 |
+
Explanation
|
| 598 |
+
===========
|
| 599 |
+
|
| 600 |
+
For now only assignments are supported. This restriction will be lifted in
|
| 601 |
+
the future.
|
| 602 |
+
|
| 603 |
+
Useful attributes on this object are:
|
| 604 |
+
|
| 605 |
+
``left_hand_sides``:
|
| 606 |
+
Tuple of left-hand sides of assignments, in order.
|
| 607 |
+
``left_hand_sides``:
|
| 608 |
+
Tuple of right-hand sides of assignments, in order.
|
| 609 |
+
``free_symbols``: Free symbols of the expressions in the right-hand sides
|
| 610 |
+
which do not appear in the left-hand side of an assignment.
|
| 611 |
+
|
| 612 |
+
Useful methods on this object are:
|
| 613 |
+
|
| 614 |
+
``topological_sort``:
|
| 615 |
+
Class method. Return a CodeBlock with assignments
|
| 616 |
+
sorted so that variables are assigned before they
|
| 617 |
+
are used.
|
| 618 |
+
``cse``:
|
| 619 |
+
Return a new CodeBlock with common subexpressions eliminated and
|
| 620 |
+
pulled out as assignments.
|
| 621 |
+
|
| 622 |
+
Examples
|
| 623 |
+
========
|
| 624 |
+
|
| 625 |
+
>>> from sympy import symbols, ccode
|
| 626 |
+
>>> from sympy.codegen.ast import CodeBlock, Assignment
|
| 627 |
+
>>> x, y = symbols('x y')
|
| 628 |
+
>>> c = CodeBlock(Assignment(x, 1), Assignment(y, x + 1))
|
| 629 |
+
>>> print(ccode(c))
|
| 630 |
+
x = 1;
|
| 631 |
+
y = x + 1;
|
| 632 |
+
|
| 633 |
+
"""
|
| 634 |
+
def __new__(cls, *args):
|
| 635 |
+
left_hand_sides = []
|
| 636 |
+
right_hand_sides = []
|
| 637 |
+
for i in args:
|
| 638 |
+
if isinstance(i, Assignment):
|
| 639 |
+
lhs, rhs = i.args
|
| 640 |
+
left_hand_sides.append(lhs)
|
| 641 |
+
right_hand_sides.append(rhs)
|
| 642 |
+
|
| 643 |
+
obj = CodegenAST.__new__(cls, *args)
|
| 644 |
+
|
| 645 |
+
obj.left_hand_sides = Tuple(*left_hand_sides)
|
| 646 |
+
obj.right_hand_sides = Tuple(*right_hand_sides)
|
| 647 |
+
return obj
|
| 648 |
+
|
| 649 |
+
def __iter__(self):
|
| 650 |
+
return iter(self.args)
|
| 651 |
+
|
| 652 |
+
def _sympyrepr(self, printer, *args, **kwargs):
|
| 653 |
+
il = printer._context.get('indent_level', 0)
|
| 654 |
+
joiner = ',\n' + ' '*il
|
| 655 |
+
joined = joiner.join(map(printer._print, self.args))
|
| 656 |
+
return ('{}(\n'.format(' '*(il-4) + self.__class__.__name__,) +
|
| 657 |
+
' '*il + joined + '\n' + ' '*(il - 4) + ')')
|
| 658 |
+
|
| 659 |
+
_sympystr = _sympyrepr
|
| 660 |
+
|
| 661 |
+
@property
|
| 662 |
+
def free_symbols(self):
|
| 663 |
+
return super().free_symbols - set(self.left_hand_sides)
|
| 664 |
+
|
| 665 |
+
@classmethod
|
| 666 |
+
def topological_sort(cls, assignments):
|
| 667 |
+
"""
|
| 668 |
+
Return a CodeBlock with topologically sorted assignments so that
|
| 669 |
+
variables are assigned before they are used.
|
| 670 |
+
|
| 671 |
+
Examples
|
| 672 |
+
========
|
| 673 |
+
|
| 674 |
+
The existing order of assignments is preserved as much as possible.
|
| 675 |
+
|
| 676 |
+
This function assumes that variables are assigned to only once.
|
| 677 |
+
|
| 678 |
+
This is a class constructor so that the default constructor for
|
| 679 |
+
CodeBlock can error when variables are used before they are assigned.
|
| 680 |
+
|
| 681 |
+
>>> from sympy import symbols
|
| 682 |
+
>>> from sympy.codegen.ast import CodeBlock, Assignment
|
| 683 |
+
>>> x, y, z = symbols('x y z')
|
| 684 |
+
|
| 685 |
+
>>> assignments = [
|
| 686 |
+
... Assignment(x, y + z),
|
| 687 |
+
... Assignment(y, z + 1),
|
| 688 |
+
... Assignment(z, 2),
|
| 689 |
+
... ]
|
| 690 |
+
>>> CodeBlock.topological_sort(assignments)
|
| 691 |
+
CodeBlock(
|
| 692 |
+
Assignment(z, 2),
|
| 693 |
+
Assignment(y, z + 1),
|
| 694 |
+
Assignment(x, y + z)
|
| 695 |
+
)
|
| 696 |
+
|
| 697 |
+
"""
|
| 698 |
+
|
| 699 |
+
if not all(isinstance(i, Assignment) for i in assignments):
|
| 700 |
+
# Will support more things later
|
| 701 |
+
raise NotImplementedError("CodeBlock.topological_sort only supports Assignments")
|
| 702 |
+
|
| 703 |
+
if any(isinstance(i, AugmentedAssignment) for i in assignments):
|
| 704 |
+
raise NotImplementedError("CodeBlock.topological_sort does not yet work with AugmentedAssignments")
|
| 705 |
+
|
| 706 |
+
# Create a graph where the nodes are assignments and there is a directed edge
|
| 707 |
+
# between nodes that use a variable and nodes that assign that
|
| 708 |
+
# variable, like
|
| 709 |
+
|
| 710 |
+
# [(x := 1, y := x + 1), (x := 1, z := y + z), (y := x + 1, z := y + z)]
|
| 711 |
+
|
| 712 |
+
# If we then topologically sort these nodes, they will be in
|
| 713 |
+
# assignment order, like
|
| 714 |
+
|
| 715 |
+
# x := 1
|
| 716 |
+
# y := x + 1
|
| 717 |
+
# z := y + z
|
| 718 |
+
|
| 719 |
+
# A = The nodes
|
| 720 |
+
#
|
| 721 |
+
# enumerate keeps nodes in the same order they are already in if
|
| 722 |
+
# possible. It will also allow us to handle duplicate assignments to
|
| 723 |
+
# the same variable when those are implemented.
|
| 724 |
+
A = list(enumerate(assignments))
|
| 725 |
+
|
| 726 |
+
# var_map = {variable: [nodes for which this variable is assigned to]}
|
| 727 |
+
# like {x: [(1, x := y + z), (4, x := 2 * w)], ...}
|
| 728 |
+
var_map = defaultdict(list)
|
| 729 |
+
for node in A:
|
| 730 |
+
i, a = node
|
| 731 |
+
var_map[a.lhs].append(node)
|
| 732 |
+
|
| 733 |
+
# E = Edges in the graph
|
| 734 |
+
E = []
|
| 735 |
+
for dst_node in A:
|
| 736 |
+
i, a = dst_node
|
| 737 |
+
for s in a.rhs.free_symbols:
|
| 738 |
+
for src_node in var_map[s]:
|
| 739 |
+
E.append((src_node, dst_node))
|
| 740 |
+
|
| 741 |
+
ordered_assignments = topological_sort([A, E])
|
| 742 |
+
|
| 743 |
+
# De-enumerate the result
|
| 744 |
+
return cls(*[a for i, a in ordered_assignments])
|
| 745 |
+
|
| 746 |
+
def cse(self, symbols=None, optimizations=None, postprocess=None,
|
| 747 |
+
order='canonical'):
|
| 748 |
+
"""
|
| 749 |
+
Return a new code block with common subexpressions eliminated.
|
| 750 |
+
|
| 751 |
+
Explanation
|
| 752 |
+
===========
|
| 753 |
+
|
| 754 |
+
See the docstring of :func:`sympy.simplify.cse_main.cse` for more
|
| 755 |
+
information.
|
| 756 |
+
|
| 757 |
+
Examples
|
| 758 |
+
========
|
| 759 |
+
|
| 760 |
+
>>> from sympy import symbols, sin
|
| 761 |
+
>>> from sympy.codegen.ast import CodeBlock, Assignment
|
| 762 |
+
>>> x, y, z = symbols('x y z')
|
| 763 |
+
|
| 764 |
+
>>> c = CodeBlock(
|
| 765 |
+
... Assignment(x, 1),
|
| 766 |
+
... Assignment(y, sin(x) + 1),
|
| 767 |
+
... Assignment(z, sin(x) - 1),
|
| 768 |
+
... )
|
| 769 |
+
...
|
| 770 |
+
>>> c.cse()
|
| 771 |
+
CodeBlock(
|
| 772 |
+
Assignment(x, 1),
|
| 773 |
+
Assignment(x0, sin(x)),
|
| 774 |
+
Assignment(y, x0 + 1),
|
| 775 |
+
Assignment(z, x0 - 1)
|
| 776 |
+
)
|
| 777 |
+
|
| 778 |
+
"""
|
| 779 |
+
from sympy.simplify.cse_main import cse
|
| 780 |
+
|
| 781 |
+
# Check that the CodeBlock only contains assignments to unique variables
|
| 782 |
+
if not all(isinstance(i, Assignment) for i in self.args):
|
| 783 |
+
# Will support more things later
|
| 784 |
+
raise NotImplementedError("CodeBlock.cse only supports Assignments")
|
| 785 |
+
|
| 786 |
+
if any(isinstance(i, AugmentedAssignment) for i in self.args):
|
| 787 |
+
raise NotImplementedError("CodeBlock.cse does not yet work with AugmentedAssignments")
|
| 788 |
+
|
| 789 |
+
for i, lhs in enumerate(self.left_hand_sides):
|
| 790 |
+
if lhs in self.left_hand_sides[:i]:
|
| 791 |
+
raise NotImplementedError("Duplicate assignments to the same "
|
| 792 |
+
"variable are not yet supported (%s)" % lhs)
|
| 793 |
+
|
| 794 |
+
# Ensure new symbols for subexpressions do not conflict with existing
|
| 795 |
+
existing_symbols = self.atoms(Symbol)
|
| 796 |
+
if symbols is None:
|
| 797 |
+
symbols = numbered_symbols()
|
| 798 |
+
symbols = filter_symbols(symbols, existing_symbols)
|
| 799 |
+
|
| 800 |
+
replacements, reduced_exprs = cse(list(self.right_hand_sides),
|
| 801 |
+
symbols=symbols, optimizations=optimizations, postprocess=postprocess,
|
| 802 |
+
order=order)
|
| 803 |
+
|
| 804 |
+
new_block = [Assignment(var, expr) for var, expr in
|
| 805 |
+
zip(self.left_hand_sides, reduced_exprs)]
|
| 806 |
+
new_assignments = [Assignment(var, expr) for var, expr in replacements]
|
| 807 |
+
return self.topological_sort(new_assignments + new_block)
|
| 808 |
+
|
| 809 |
+
|
| 810 |
+
class For(Token):
|
| 811 |
+
"""Represents a 'for-loop' in the code.
|
| 812 |
+
|
| 813 |
+
Expressions are of the form:
|
| 814 |
+
"for target in iter:
|
| 815 |
+
body..."
|
| 816 |
+
|
| 817 |
+
Parameters
|
| 818 |
+
==========
|
| 819 |
+
|
| 820 |
+
target : symbol
|
| 821 |
+
iter : iterable
|
| 822 |
+
body : CodeBlock or iterable
|
| 823 |
+
! When passed an iterable it is used to instantiate a CodeBlock.
|
| 824 |
+
|
| 825 |
+
Examples
|
| 826 |
+
========
|
| 827 |
+
|
| 828 |
+
>>> from sympy import symbols, Range
|
| 829 |
+
>>> from sympy.codegen.ast import aug_assign, For
|
| 830 |
+
>>> x, i, j, k = symbols('x i j k')
|
| 831 |
+
>>> for_i = For(i, Range(10), [aug_assign(x, '+', i*j*k)])
|
| 832 |
+
>>> for_i # doctest: -NORMALIZE_WHITESPACE
|
| 833 |
+
For(i, iterable=Range(0, 10, 1), body=CodeBlock(
|
| 834 |
+
AddAugmentedAssignment(x, i*j*k)
|
| 835 |
+
))
|
| 836 |
+
>>> for_ji = For(j, Range(7), [for_i])
|
| 837 |
+
>>> for_ji # doctest: -NORMALIZE_WHITESPACE
|
| 838 |
+
For(j, iterable=Range(0, 7, 1), body=CodeBlock(
|
| 839 |
+
For(i, iterable=Range(0, 10, 1), body=CodeBlock(
|
| 840 |
+
AddAugmentedAssignment(x, i*j*k)
|
| 841 |
+
))
|
| 842 |
+
))
|
| 843 |
+
>>> for_kji =For(k, Range(5), [for_ji])
|
| 844 |
+
>>> for_kji # doctest: -NORMALIZE_WHITESPACE
|
| 845 |
+
For(k, iterable=Range(0, 5, 1), body=CodeBlock(
|
| 846 |
+
For(j, iterable=Range(0, 7, 1), body=CodeBlock(
|
| 847 |
+
For(i, iterable=Range(0, 10, 1), body=CodeBlock(
|
| 848 |
+
AddAugmentedAssignment(x, i*j*k)
|
| 849 |
+
))
|
| 850 |
+
))
|
| 851 |
+
))
|
| 852 |
+
"""
|
| 853 |
+
__slots__ = _fields = ('target', 'iterable', 'body')
|
| 854 |
+
_construct_target = staticmethod(_sympify)
|
| 855 |
+
|
| 856 |
+
@classmethod
|
| 857 |
+
def _construct_body(cls, itr):
|
| 858 |
+
if isinstance(itr, CodeBlock):
|
| 859 |
+
return itr
|
| 860 |
+
else:
|
| 861 |
+
return CodeBlock(*itr)
|
| 862 |
+
|
| 863 |
+
@classmethod
|
| 864 |
+
def _construct_iterable(cls, itr):
|
| 865 |
+
if not iterable(itr):
|
| 866 |
+
raise TypeError("iterable must be an iterable")
|
| 867 |
+
if isinstance(itr, list): # _sympify errors on lists because they are mutable
|
| 868 |
+
itr = tuple(itr)
|
| 869 |
+
return _sympify(itr)
|
| 870 |
+
|
| 871 |
+
|
| 872 |
+
class String(Atom, Token):
|
| 873 |
+
""" SymPy object representing a string.
|
| 874 |
+
|
| 875 |
+
Atomic object which is not an expression (as opposed to Symbol).
|
| 876 |
+
|
| 877 |
+
Parameters
|
| 878 |
+
==========
|
| 879 |
+
|
| 880 |
+
text : str
|
| 881 |
+
|
| 882 |
+
Examples
|
| 883 |
+
========
|
| 884 |
+
|
| 885 |
+
>>> from sympy.codegen.ast import String
|
| 886 |
+
>>> f = String('foo')
|
| 887 |
+
>>> f
|
| 888 |
+
foo
|
| 889 |
+
>>> str(f)
|
| 890 |
+
'foo'
|
| 891 |
+
>>> f.text
|
| 892 |
+
'foo'
|
| 893 |
+
>>> print(repr(f))
|
| 894 |
+
String('foo')
|
| 895 |
+
|
| 896 |
+
"""
|
| 897 |
+
__slots__ = _fields = ('text',)
|
| 898 |
+
not_in_args = ['text']
|
| 899 |
+
is_Atom = True
|
| 900 |
+
|
| 901 |
+
@classmethod
|
| 902 |
+
def _construct_text(cls, text):
|
| 903 |
+
if not isinstance(text, str):
|
| 904 |
+
raise TypeError("Argument text is not a string type.")
|
| 905 |
+
return text
|
| 906 |
+
|
| 907 |
+
def _sympystr(self, printer, *args, **kwargs):
|
| 908 |
+
return self.text
|
| 909 |
+
|
| 910 |
+
def kwargs(self, exclude = (), apply = None):
|
| 911 |
+
return {}
|
| 912 |
+
|
| 913 |
+
#to be removed when Atom is given a suitable func
|
| 914 |
+
@property
|
| 915 |
+
def func(self):
|
| 916 |
+
return lambda: self
|
| 917 |
+
|
| 918 |
+
def _latex(self, printer):
|
| 919 |
+
from sympy.printing.latex import latex_escape
|
| 920 |
+
return r'\texttt{{"{}"}}'.format(latex_escape(self.text))
|
| 921 |
+
|
| 922 |
+
class QuotedString(String):
|
| 923 |
+
""" Represents a string which should be printed with quotes. """
|
| 924 |
+
|
| 925 |
+
class Comment(String):
|
| 926 |
+
""" Represents a comment. """
|
| 927 |
+
|
| 928 |
+
class Node(Token):
|
| 929 |
+
""" Subclass of Token, carrying the attribute 'attrs' (Tuple)
|
| 930 |
+
|
| 931 |
+
Examples
|
| 932 |
+
========
|
| 933 |
+
|
| 934 |
+
>>> from sympy.codegen.ast import Node, value_const, pointer_const
|
| 935 |
+
>>> n1 = Node([value_const])
|
| 936 |
+
>>> n1.attr_params('value_const') # get the parameters of attribute (by name)
|
| 937 |
+
()
|
| 938 |
+
>>> from sympy.codegen.fnodes import dimension
|
| 939 |
+
>>> n2 = Node([value_const, dimension(5, 3)])
|
| 940 |
+
>>> n2.attr_params(value_const) # get the parameters of attribute (by Attribute instance)
|
| 941 |
+
()
|
| 942 |
+
>>> n2.attr_params('dimension') # get the parameters of attribute (by name)
|
| 943 |
+
(5, 3)
|
| 944 |
+
>>> n2.attr_params(pointer_const) is None
|
| 945 |
+
True
|
| 946 |
+
|
| 947 |
+
"""
|
| 948 |
+
|
| 949 |
+
__slots__: tuple[str, ...] = ('attrs',)
|
| 950 |
+
_fields = __slots__
|
| 951 |
+
|
| 952 |
+
defaults: dict[str, Any] = {'attrs': Tuple()}
|
| 953 |
+
|
| 954 |
+
_construct_attrs = staticmethod(_mk_Tuple)
|
| 955 |
+
|
| 956 |
+
def attr_params(self, looking_for):
|
| 957 |
+
""" Returns the parameters of the Attribute with name ``looking_for`` in self.attrs """
|
| 958 |
+
for attr in self.attrs:
|
| 959 |
+
if str(attr.name) == str(looking_for):
|
| 960 |
+
return attr.parameters
|
| 961 |
+
|
| 962 |
+
|
| 963 |
+
class Type(Token):
|
| 964 |
+
""" Represents a type.
|
| 965 |
+
|
| 966 |
+
Explanation
|
| 967 |
+
===========
|
| 968 |
+
|
| 969 |
+
The naming is a super-set of NumPy naming. Type has a classmethod
|
| 970 |
+
``from_expr`` which offer type deduction. It also has a method
|
| 971 |
+
``cast_check`` which casts the argument to its type, possibly raising an
|
| 972 |
+
exception if rounding error is not within tolerances, or if the value is not
|
| 973 |
+
representable by the underlying data type (e.g. unsigned integers).
|
| 974 |
+
|
| 975 |
+
Parameters
|
| 976 |
+
==========
|
| 977 |
+
|
| 978 |
+
name : str
|
| 979 |
+
Name of the type, e.g. ``object``, ``int16``, ``float16`` (where the latter two
|
| 980 |
+
would use the ``Type`` sub-classes ``IntType`` and ``FloatType`` respectively).
|
| 981 |
+
If a ``Type`` instance is given, the said instance is returned.
|
| 982 |
+
|
| 983 |
+
Examples
|
| 984 |
+
========
|
| 985 |
+
|
| 986 |
+
>>> from sympy.codegen.ast import Type
|
| 987 |
+
>>> t = Type.from_expr(42)
|
| 988 |
+
>>> t
|
| 989 |
+
integer
|
| 990 |
+
>>> print(repr(t))
|
| 991 |
+
IntBaseType(String('integer'))
|
| 992 |
+
>>> from sympy.codegen.ast import uint8
|
| 993 |
+
>>> uint8.cast_check(-1) # doctest: +ELLIPSIS
|
| 994 |
+
Traceback (most recent call last):
|
| 995 |
+
...
|
| 996 |
+
ValueError: Minimum value for data type bigger than new value.
|
| 997 |
+
>>> from sympy.codegen.ast import float32
|
| 998 |
+
>>> v6 = 0.123456
|
| 999 |
+
>>> float32.cast_check(v6)
|
| 1000 |
+
0.123456
|
| 1001 |
+
>>> v10 = 12345.67894
|
| 1002 |
+
>>> float32.cast_check(v10) # doctest: +ELLIPSIS
|
| 1003 |
+
Traceback (most recent call last):
|
| 1004 |
+
...
|
| 1005 |
+
ValueError: Casting gives a significantly different value.
|
| 1006 |
+
>>> boost_mp50 = Type('boost::multiprecision::cpp_dec_float_50')
|
| 1007 |
+
>>> from sympy import cxxcode
|
| 1008 |
+
>>> from sympy.codegen.ast import Declaration, Variable
|
| 1009 |
+
>>> cxxcode(Declaration(Variable('x', type=boost_mp50)))
|
| 1010 |
+
'boost::multiprecision::cpp_dec_float_50 x'
|
| 1011 |
+
|
| 1012 |
+
References
|
| 1013 |
+
==========
|
| 1014 |
+
|
| 1015 |
+
.. [1] https://numpy.org/doc/stable/user/basics.types.html
|
| 1016 |
+
|
| 1017 |
+
"""
|
| 1018 |
+
__slots__: tuple[str, ...] = ('name',)
|
| 1019 |
+
_fields = __slots__
|
| 1020 |
+
|
| 1021 |
+
_construct_name = String
|
| 1022 |
+
|
| 1023 |
+
def _sympystr(self, printer, *args, **kwargs):
|
| 1024 |
+
return str(self.name)
|
| 1025 |
+
|
| 1026 |
+
@classmethod
|
| 1027 |
+
def from_expr(cls, expr):
|
| 1028 |
+
""" Deduces type from an expression or a ``Symbol``.
|
| 1029 |
+
|
| 1030 |
+
Parameters
|
| 1031 |
+
==========
|
| 1032 |
+
|
| 1033 |
+
expr : number or SymPy object
|
| 1034 |
+
The type will be deduced from type or properties.
|
| 1035 |
+
|
| 1036 |
+
Examples
|
| 1037 |
+
========
|
| 1038 |
+
|
| 1039 |
+
>>> from sympy.codegen.ast import Type, integer, complex_
|
| 1040 |
+
>>> Type.from_expr(2) == integer
|
| 1041 |
+
True
|
| 1042 |
+
>>> from sympy import Symbol
|
| 1043 |
+
>>> Type.from_expr(Symbol('z', complex=True)) == complex_
|
| 1044 |
+
True
|
| 1045 |
+
>>> Type.from_expr(sum) # doctest: +ELLIPSIS
|
| 1046 |
+
Traceback (most recent call last):
|
| 1047 |
+
...
|
| 1048 |
+
ValueError: Could not deduce type from expr.
|
| 1049 |
+
|
| 1050 |
+
Raises
|
| 1051 |
+
======
|
| 1052 |
+
|
| 1053 |
+
ValueError when type deduction fails.
|
| 1054 |
+
|
| 1055 |
+
"""
|
| 1056 |
+
if isinstance(expr, (float, Float)):
|
| 1057 |
+
return real
|
| 1058 |
+
if isinstance(expr, (int, Integer)) or getattr(expr, 'is_integer', False):
|
| 1059 |
+
return integer
|
| 1060 |
+
if getattr(expr, 'is_real', False):
|
| 1061 |
+
return real
|
| 1062 |
+
if isinstance(expr, complex) or getattr(expr, 'is_complex', False):
|
| 1063 |
+
return complex_
|
| 1064 |
+
if isinstance(expr, bool) or getattr(expr, 'is_Relational', False):
|
| 1065 |
+
return bool_
|
| 1066 |
+
else:
|
| 1067 |
+
raise ValueError("Could not deduce type from expr.")
|
| 1068 |
+
|
| 1069 |
+
def _check(self, value):
|
| 1070 |
+
pass
|
| 1071 |
+
|
| 1072 |
+
def cast_check(self, value, rtol=None, atol=0, precision_targets=None):
|
| 1073 |
+
""" Casts a value to the data type of the instance.
|
| 1074 |
+
|
| 1075 |
+
Parameters
|
| 1076 |
+
==========
|
| 1077 |
+
|
| 1078 |
+
value : number
|
| 1079 |
+
rtol : floating point number
|
| 1080 |
+
Relative tolerance. (will be deduced if not given).
|
| 1081 |
+
atol : floating point number
|
| 1082 |
+
Absolute tolerance (in addition to ``rtol``).
|
| 1083 |
+
type_aliases : dict
|
| 1084 |
+
Maps substitutions for Type, e.g. {integer: int64, real: float32}
|
| 1085 |
+
|
| 1086 |
+
Examples
|
| 1087 |
+
========
|
| 1088 |
+
|
| 1089 |
+
>>> from sympy.codegen.ast import integer, float32, int8
|
| 1090 |
+
>>> integer.cast_check(3.0) == 3
|
| 1091 |
+
True
|
| 1092 |
+
>>> float32.cast_check(1e-40) # doctest: +ELLIPSIS
|
| 1093 |
+
Traceback (most recent call last):
|
| 1094 |
+
...
|
| 1095 |
+
ValueError: Minimum value for data type bigger than new value.
|
| 1096 |
+
>>> int8.cast_check(256) # doctest: +ELLIPSIS
|
| 1097 |
+
Traceback (most recent call last):
|
| 1098 |
+
...
|
| 1099 |
+
ValueError: Maximum value for data type smaller than new value.
|
| 1100 |
+
>>> v10 = 12345.67894
|
| 1101 |
+
>>> float32.cast_check(v10) # doctest: +ELLIPSIS
|
| 1102 |
+
Traceback (most recent call last):
|
| 1103 |
+
...
|
| 1104 |
+
ValueError: Casting gives a significantly different value.
|
| 1105 |
+
>>> from sympy.codegen.ast import float64
|
| 1106 |
+
>>> float64.cast_check(v10)
|
| 1107 |
+
12345.67894
|
| 1108 |
+
>>> from sympy import Float
|
| 1109 |
+
>>> v18 = Float('0.123456789012345646')
|
| 1110 |
+
>>> float64.cast_check(v18)
|
| 1111 |
+
Traceback (most recent call last):
|
| 1112 |
+
...
|
| 1113 |
+
ValueError: Casting gives a significantly different value.
|
| 1114 |
+
>>> from sympy.codegen.ast import float80
|
| 1115 |
+
>>> float80.cast_check(v18)
|
| 1116 |
+
0.123456789012345649
|
| 1117 |
+
|
| 1118 |
+
"""
|
| 1119 |
+
val = sympify(value)
|
| 1120 |
+
|
| 1121 |
+
ten = Integer(10)
|
| 1122 |
+
exp10 = getattr(self, 'decimal_dig', None)
|
| 1123 |
+
|
| 1124 |
+
if rtol is None:
|
| 1125 |
+
rtol = 1e-15 if exp10 is None else 2.0*ten**(-exp10)
|
| 1126 |
+
|
| 1127 |
+
def tol(num):
|
| 1128 |
+
return atol + rtol*abs(num)
|
| 1129 |
+
|
| 1130 |
+
new_val = self.cast_nocheck(value)
|
| 1131 |
+
self._check(new_val)
|
| 1132 |
+
|
| 1133 |
+
delta = new_val - val
|
| 1134 |
+
if abs(delta) > tol(val): # rounding, e.g. int(3.5) != 3.5
|
| 1135 |
+
raise ValueError("Casting gives a significantly different value.")
|
| 1136 |
+
|
| 1137 |
+
return new_val
|
| 1138 |
+
|
| 1139 |
+
def _latex(self, printer):
|
| 1140 |
+
from sympy.printing.latex import latex_escape
|
| 1141 |
+
type_name = latex_escape(self.__class__.__name__)
|
| 1142 |
+
name = latex_escape(self.name.text)
|
| 1143 |
+
return r"\text{{{}}}\left(\texttt{{{}}}\right)".format(type_name, name)
|
| 1144 |
+
|
| 1145 |
+
|
| 1146 |
+
class IntBaseType(Type):
|
| 1147 |
+
""" Integer base type, contains no size information. """
|
| 1148 |
+
__slots__ = ()
|
| 1149 |
+
cast_nocheck = lambda self, i: Integer(int(i))
|
| 1150 |
+
|
| 1151 |
+
|
| 1152 |
+
class _SizedIntType(IntBaseType):
|
| 1153 |
+
__slots__ = ('nbits',)
|
| 1154 |
+
_fields = Type._fields + __slots__
|
| 1155 |
+
|
| 1156 |
+
_construct_nbits = Integer
|
| 1157 |
+
|
| 1158 |
+
def _check(self, value):
|
| 1159 |
+
if value < self.min:
|
| 1160 |
+
raise ValueError("Value is too small: %d < %d" % (value, self.min))
|
| 1161 |
+
if value > self.max:
|
| 1162 |
+
raise ValueError("Value is too big: %d > %d" % (value, self.max))
|
| 1163 |
+
|
| 1164 |
+
|
| 1165 |
+
class SignedIntType(_SizedIntType):
|
| 1166 |
+
""" Represents a signed integer type. """
|
| 1167 |
+
__slots__ = ()
|
| 1168 |
+
@property
|
| 1169 |
+
def min(self):
|
| 1170 |
+
return -2**(self.nbits-1)
|
| 1171 |
+
|
| 1172 |
+
@property
|
| 1173 |
+
def max(self):
|
| 1174 |
+
return 2**(self.nbits-1) - 1
|
| 1175 |
+
|
| 1176 |
+
|
| 1177 |
+
class UnsignedIntType(_SizedIntType):
|
| 1178 |
+
""" Represents an unsigned integer type. """
|
| 1179 |
+
__slots__ = ()
|
| 1180 |
+
@property
|
| 1181 |
+
def min(self):
|
| 1182 |
+
return 0
|
| 1183 |
+
|
| 1184 |
+
@property
|
| 1185 |
+
def max(self):
|
| 1186 |
+
return 2**self.nbits - 1
|
| 1187 |
+
|
| 1188 |
+
two = Integer(2)
|
| 1189 |
+
|
| 1190 |
+
class FloatBaseType(Type):
|
| 1191 |
+
""" Represents a floating point number type. """
|
| 1192 |
+
__slots__ = ()
|
| 1193 |
+
cast_nocheck = Float
|
| 1194 |
+
|
| 1195 |
+
class FloatType(FloatBaseType):
|
| 1196 |
+
""" Represents a floating point type with fixed bit width.
|
| 1197 |
+
|
| 1198 |
+
Base 2 & one sign bit is assumed.
|
| 1199 |
+
|
| 1200 |
+
Parameters
|
| 1201 |
+
==========
|
| 1202 |
+
|
| 1203 |
+
name : str
|
| 1204 |
+
Name of the type.
|
| 1205 |
+
nbits : integer
|
| 1206 |
+
Number of bits used (storage).
|
| 1207 |
+
nmant : integer
|
| 1208 |
+
Number of bits used to represent the mantissa.
|
| 1209 |
+
nexp : integer
|
| 1210 |
+
Number of bits used to represent the mantissa.
|
| 1211 |
+
|
| 1212 |
+
Examples
|
| 1213 |
+
========
|
| 1214 |
+
|
| 1215 |
+
>>> from sympy import S
|
| 1216 |
+
>>> from sympy.codegen.ast import FloatType
|
| 1217 |
+
>>> half_precision = FloatType('f16', nbits=16, nmant=10, nexp=5)
|
| 1218 |
+
>>> half_precision.max
|
| 1219 |
+
65504
|
| 1220 |
+
>>> half_precision.tiny == S(2)**-14
|
| 1221 |
+
True
|
| 1222 |
+
>>> half_precision.eps == S(2)**-10
|
| 1223 |
+
True
|
| 1224 |
+
>>> half_precision.dig == 3
|
| 1225 |
+
True
|
| 1226 |
+
>>> half_precision.decimal_dig == 5
|
| 1227 |
+
True
|
| 1228 |
+
>>> half_precision.cast_check(1.0)
|
| 1229 |
+
1.0
|
| 1230 |
+
>>> half_precision.cast_check(1e5) # doctest: +ELLIPSIS
|
| 1231 |
+
Traceback (most recent call last):
|
| 1232 |
+
...
|
| 1233 |
+
ValueError: Maximum value for data type smaller than new value.
|
| 1234 |
+
"""
|
| 1235 |
+
|
| 1236 |
+
__slots__ = ('nbits', 'nmant', 'nexp',)
|
| 1237 |
+
_fields = Type._fields + __slots__
|
| 1238 |
+
|
| 1239 |
+
_construct_nbits = _construct_nmant = _construct_nexp = Integer
|
| 1240 |
+
|
| 1241 |
+
|
| 1242 |
+
@property
|
| 1243 |
+
def max_exponent(self):
|
| 1244 |
+
""" The largest positive number n, such that 2**(n - 1) is a representable finite value. """
|
| 1245 |
+
# cf. C++'s ``std::numeric_limits::max_exponent``
|
| 1246 |
+
return two**(self.nexp - 1)
|
| 1247 |
+
|
| 1248 |
+
@property
|
| 1249 |
+
def min_exponent(self):
|
| 1250 |
+
""" The lowest negative number n, such that 2**(n - 1) is a valid normalized number. """
|
| 1251 |
+
# cf. C++'s ``std::numeric_limits::min_exponent``
|
| 1252 |
+
return 3 - self.max_exponent
|
| 1253 |
+
|
| 1254 |
+
@property
|
| 1255 |
+
def max(self):
|
| 1256 |
+
""" Maximum value representable. """
|
| 1257 |
+
return (1 - two**-(self.nmant+1))*two**self.max_exponent
|
| 1258 |
+
|
| 1259 |
+
@property
|
| 1260 |
+
def tiny(self):
|
| 1261 |
+
""" The minimum positive normalized value. """
|
| 1262 |
+
# See C macros: FLT_MIN, DBL_MIN, LDBL_MIN
|
| 1263 |
+
# or C++'s ``std::numeric_limits::min``
|
| 1264 |
+
# or numpy.finfo(dtype).tiny
|
| 1265 |
+
return two**(self.min_exponent - 1)
|
| 1266 |
+
|
| 1267 |
+
|
| 1268 |
+
@property
|
| 1269 |
+
def eps(self):
|
| 1270 |
+
""" Difference between 1.0 and the next representable value. """
|
| 1271 |
+
return two**(-self.nmant)
|
| 1272 |
+
|
| 1273 |
+
@property
|
| 1274 |
+
def dig(self):
|
| 1275 |
+
""" Number of decimal digits that are guaranteed to be preserved in text.
|
| 1276 |
+
|
| 1277 |
+
When converting text -> float -> text, you are guaranteed that at least ``dig``
|
| 1278 |
+
number of digits are preserved with respect to rounding or overflow.
|
| 1279 |
+
"""
|
| 1280 |
+
from sympy.functions import floor, log
|
| 1281 |
+
return floor(self.nmant * log(2)/log(10))
|
| 1282 |
+
|
| 1283 |
+
@property
|
| 1284 |
+
def decimal_dig(self):
|
| 1285 |
+
""" Number of digits needed to store & load without loss.
|
| 1286 |
+
|
| 1287 |
+
Explanation
|
| 1288 |
+
===========
|
| 1289 |
+
|
| 1290 |
+
Number of decimal digits needed to guarantee that two consecutive conversions
|
| 1291 |
+
(float -> text -> float) to be idempotent. This is useful when one do not want
|
| 1292 |
+
to loose precision due to rounding errors when storing a floating point value
|
| 1293 |
+
as text.
|
| 1294 |
+
"""
|
| 1295 |
+
from sympy.functions import ceiling, log
|
| 1296 |
+
return ceiling((self.nmant + 1) * log(2)/log(10) + 1)
|
| 1297 |
+
|
| 1298 |
+
def cast_nocheck(self, value):
|
| 1299 |
+
""" Casts without checking if out of bounds or subnormal. """
|
| 1300 |
+
if value == oo: # float(oo) or oo
|
| 1301 |
+
return float(oo)
|
| 1302 |
+
elif value == -oo: # float(-oo) or -oo
|
| 1303 |
+
return float(-oo)
|
| 1304 |
+
return Float(str(sympify(value).evalf(self.decimal_dig)), self.decimal_dig)
|
| 1305 |
+
|
| 1306 |
+
def _check(self, value):
|
| 1307 |
+
if value < -self.max:
|
| 1308 |
+
raise ValueError("Value is too small: %d < %d" % (value, -self.max))
|
| 1309 |
+
if value > self.max:
|
| 1310 |
+
raise ValueError("Value is too big: %d > %d" % (value, self.max))
|
| 1311 |
+
if abs(value) < self.tiny:
|
| 1312 |
+
raise ValueError("Smallest (absolute) value for data type bigger than new value.")
|
| 1313 |
+
|
| 1314 |
+
class ComplexBaseType(FloatBaseType):
|
| 1315 |
+
|
| 1316 |
+
__slots__ = ()
|
| 1317 |
+
|
| 1318 |
+
def cast_nocheck(self, value):
|
| 1319 |
+
""" Casts without checking if out of bounds or subnormal. """
|
| 1320 |
+
from sympy.functions import re, im
|
| 1321 |
+
return (
|
| 1322 |
+
super().cast_nocheck(re(value)) +
|
| 1323 |
+
super().cast_nocheck(im(value))*1j
|
| 1324 |
+
)
|
| 1325 |
+
|
| 1326 |
+
def _check(self, value):
|
| 1327 |
+
from sympy.functions import re, im
|
| 1328 |
+
super()._check(re(value))
|
| 1329 |
+
super()._check(im(value))
|
| 1330 |
+
|
| 1331 |
+
|
| 1332 |
+
class ComplexType(ComplexBaseType, FloatType):
|
| 1333 |
+
""" Represents a complex floating point number. """
|
| 1334 |
+
__slots__ = ()
|
| 1335 |
+
|
| 1336 |
+
|
| 1337 |
+
# NumPy types:
|
| 1338 |
+
intc = IntBaseType('intc')
|
| 1339 |
+
intp = IntBaseType('intp')
|
| 1340 |
+
int8 = SignedIntType('int8', 8)
|
| 1341 |
+
int16 = SignedIntType('int16', 16)
|
| 1342 |
+
int32 = SignedIntType('int32', 32)
|
| 1343 |
+
int64 = SignedIntType('int64', 64)
|
| 1344 |
+
uint8 = UnsignedIntType('uint8', 8)
|
| 1345 |
+
uint16 = UnsignedIntType('uint16', 16)
|
| 1346 |
+
uint32 = UnsignedIntType('uint32', 32)
|
| 1347 |
+
uint64 = UnsignedIntType('uint64', 64)
|
| 1348 |
+
float16 = FloatType('float16', 16, nexp=5, nmant=10) # IEEE 754 binary16, Half precision
|
| 1349 |
+
float32 = FloatType('float32', 32, nexp=8, nmant=23) # IEEE 754 binary32, Single precision
|
| 1350 |
+
float64 = FloatType('float64', 64, nexp=11, nmant=52) # IEEE 754 binary64, Double precision
|
| 1351 |
+
float80 = FloatType('float80', 80, nexp=15, nmant=63) # x86 extended precision (1 integer part bit), "long double"
|
| 1352 |
+
float128 = FloatType('float128', 128, nexp=15, nmant=112) # IEEE 754 binary128, Quadruple precision
|
| 1353 |
+
float256 = FloatType('float256', 256, nexp=19, nmant=236) # IEEE 754 binary256, Octuple precision
|
| 1354 |
+
|
| 1355 |
+
complex64 = ComplexType('complex64', nbits=64, **float32.kwargs(exclude=('name', 'nbits')))
|
| 1356 |
+
complex128 = ComplexType('complex128', nbits=128, **float64.kwargs(exclude=('name', 'nbits')))
|
| 1357 |
+
|
| 1358 |
+
# Generic types (precision may be chosen by code printers):
|
| 1359 |
+
untyped = Type('untyped')
|
| 1360 |
+
real = FloatBaseType('real')
|
| 1361 |
+
integer = IntBaseType('integer')
|
| 1362 |
+
complex_ = ComplexBaseType('complex')
|
| 1363 |
+
bool_ = Type('bool')
|
| 1364 |
+
|
| 1365 |
+
|
| 1366 |
+
class Attribute(Token):
|
| 1367 |
+
""" Attribute (possibly parametrized)
|
| 1368 |
+
|
| 1369 |
+
For use with :class:`sympy.codegen.ast.Node` (which takes instances of
|
| 1370 |
+
``Attribute`` as ``attrs``).
|
| 1371 |
+
|
| 1372 |
+
Parameters
|
| 1373 |
+
==========
|
| 1374 |
+
|
| 1375 |
+
name : str
|
| 1376 |
+
parameters : Tuple
|
| 1377 |
+
|
| 1378 |
+
Examples
|
| 1379 |
+
========
|
| 1380 |
+
|
| 1381 |
+
>>> from sympy.codegen.ast import Attribute
|
| 1382 |
+
>>> volatile = Attribute('volatile')
|
| 1383 |
+
>>> volatile
|
| 1384 |
+
volatile
|
| 1385 |
+
>>> print(repr(volatile))
|
| 1386 |
+
Attribute(String('volatile'))
|
| 1387 |
+
>>> a = Attribute('foo', [1, 2, 3])
|
| 1388 |
+
>>> a
|
| 1389 |
+
foo(1, 2, 3)
|
| 1390 |
+
>>> a.parameters == (1, 2, 3)
|
| 1391 |
+
True
|
| 1392 |
+
"""
|
| 1393 |
+
__slots__ = _fields = ('name', 'parameters')
|
| 1394 |
+
defaults = {'parameters': Tuple()}
|
| 1395 |
+
|
| 1396 |
+
_construct_name = String
|
| 1397 |
+
_construct_parameters = staticmethod(_mk_Tuple)
|
| 1398 |
+
|
| 1399 |
+
def _sympystr(self, printer, *args, **kwargs):
|
| 1400 |
+
result = str(self.name)
|
| 1401 |
+
if self.parameters:
|
| 1402 |
+
result += '(%s)' % ', '.join((printer._print(
|
| 1403 |
+
arg, *args, **kwargs) for arg in self.parameters))
|
| 1404 |
+
return result
|
| 1405 |
+
|
| 1406 |
+
value_const = Attribute('value_const')
|
| 1407 |
+
pointer_const = Attribute('pointer_const')
|
| 1408 |
+
|
| 1409 |
+
|
| 1410 |
+
class Variable(Node):
|
| 1411 |
+
""" Represents a variable.
|
| 1412 |
+
|
| 1413 |
+
Parameters
|
| 1414 |
+
==========
|
| 1415 |
+
|
| 1416 |
+
symbol : Symbol
|
| 1417 |
+
type : Type (optional)
|
| 1418 |
+
Type of the variable.
|
| 1419 |
+
attrs : iterable of Attribute instances
|
| 1420 |
+
Will be stored as a Tuple.
|
| 1421 |
+
|
| 1422 |
+
Examples
|
| 1423 |
+
========
|
| 1424 |
+
|
| 1425 |
+
>>> from sympy import Symbol
|
| 1426 |
+
>>> from sympy.codegen.ast import Variable, float32, integer
|
| 1427 |
+
>>> x = Symbol('x')
|
| 1428 |
+
>>> v = Variable(x, type=float32)
|
| 1429 |
+
>>> v.attrs
|
| 1430 |
+
()
|
| 1431 |
+
>>> v == Variable('x')
|
| 1432 |
+
False
|
| 1433 |
+
>>> v == Variable('x', type=float32)
|
| 1434 |
+
True
|
| 1435 |
+
>>> v
|
| 1436 |
+
Variable(x, type=float32)
|
| 1437 |
+
|
| 1438 |
+
One may also construct a ``Variable`` instance with the type deduced from
|
| 1439 |
+
assumptions about the symbol using the ``deduced`` classmethod:
|
| 1440 |
+
|
| 1441 |
+
>>> i = Symbol('i', integer=True)
|
| 1442 |
+
>>> v = Variable.deduced(i)
|
| 1443 |
+
>>> v.type == integer
|
| 1444 |
+
True
|
| 1445 |
+
>>> v == Variable('i')
|
| 1446 |
+
False
|
| 1447 |
+
>>> from sympy.codegen.ast import value_const
|
| 1448 |
+
>>> value_const in v.attrs
|
| 1449 |
+
False
|
| 1450 |
+
>>> w = Variable('w', attrs=[value_const])
|
| 1451 |
+
>>> w
|
| 1452 |
+
Variable(w, attrs=(value_const,))
|
| 1453 |
+
>>> value_const in w.attrs
|
| 1454 |
+
True
|
| 1455 |
+
>>> w.as_Declaration(value=42)
|
| 1456 |
+
Declaration(Variable(w, value=42, attrs=(value_const,)))
|
| 1457 |
+
|
| 1458 |
+
"""
|
| 1459 |
+
|
| 1460 |
+
__slots__ = ('symbol', 'type', 'value')
|
| 1461 |
+
_fields = __slots__ + Node._fields
|
| 1462 |
+
|
| 1463 |
+
defaults = Node.defaults.copy()
|
| 1464 |
+
defaults.update({'type': untyped, 'value': none})
|
| 1465 |
+
|
| 1466 |
+
_construct_symbol = staticmethod(sympify)
|
| 1467 |
+
_construct_value = staticmethod(sympify)
|
| 1468 |
+
|
| 1469 |
+
@classmethod
|
| 1470 |
+
def deduced(cls, symbol, value=None, attrs=Tuple(), cast_check=True):
|
| 1471 |
+
""" Alt. constructor with type deduction from ``Type.from_expr``.
|
| 1472 |
+
|
| 1473 |
+
Deduces type primarily from ``symbol``, secondarily from ``value``.
|
| 1474 |
+
|
| 1475 |
+
Parameters
|
| 1476 |
+
==========
|
| 1477 |
+
|
| 1478 |
+
symbol : Symbol
|
| 1479 |
+
value : expr
|
| 1480 |
+
(optional) value of the variable.
|
| 1481 |
+
attrs : iterable of Attribute instances
|
| 1482 |
+
cast_check : bool
|
| 1483 |
+
Whether to apply ``Type.cast_check`` on ``value``.
|
| 1484 |
+
|
| 1485 |
+
Examples
|
| 1486 |
+
========
|
| 1487 |
+
|
| 1488 |
+
>>> from sympy import Symbol
|
| 1489 |
+
>>> from sympy.codegen.ast import Variable, complex_
|
| 1490 |
+
>>> n = Symbol('n', integer=True)
|
| 1491 |
+
>>> str(Variable.deduced(n).type)
|
| 1492 |
+
'integer'
|
| 1493 |
+
>>> x = Symbol('x', real=True)
|
| 1494 |
+
>>> v = Variable.deduced(x)
|
| 1495 |
+
>>> v.type
|
| 1496 |
+
real
|
| 1497 |
+
>>> z = Symbol('z', complex=True)
|
| 1498 |
+
>>> Variable.deduced(z).type == complex_
|
| 1499 |
+
True
|
| 1500 |
+
|
| 1501 |
+
"""
|
| 1502 |
+
if isinstance(symbol, Variable):
|
| 1503 |
+
return symbol
|
| 1504 |
+
|
| 1505 |
+
try:
|
| 1506 |
+
type_ = Type.from_expr(symbol)
|
| 1507 |
+
except ValueError:
|
| 1508 |
+
type_ = Type.from_expr(value)
|
| 1509 |
+
|
| 1510 |
+
if value is not None and cast_check:
|
| 1511 |
+
value = type_.cast_check(value)
|
| 1512 |
+
return cls(symbol, type=type_, value=value, attrs=attrs)
|
| 1513 |
+
|
| 1514 |
+
def as_Declaration(self, **kwargs):
|
| 1515 |
+
""" Convenience method for creating a Declaration instance.
|
| 1516 |
+
|
| 1517 |
+
Explanation
|
| 1518 |
+
===========
|
| 1519 |
+
|
| 1520 |
+
If the variable of the Declaration need to wrap a modified
|
| 1521 |
+
variable keyword arguments may be passed (overriding e.g.
|
| 1522 |
+
the ``value`` of the Variable instance).
|
| 1523 |
+
|
| 1524 |
+
Examples
|
| 1525 |
+
========
|
| 1526 |
+
|
| 1527 |
+
>>> from sympy.codegen.ast import Variable, NoneToken
|
| 1528 |
+
>>> x = Variable('x')
|
| 1529 |
+
>>> decl1 = x.as_Declaration()
|
| 1530 |
+
>>> # value is special NoneToken() which must be tested with == operator
|
| 1531 |
+
>>> decl1.variable.value is None # won't work
|
| 1532 |
+
False
|
| 1533 |
+
>>> decl1.variable.value == None # not PEP-8 compliant
|
| 1534 |
+
True
|
| 1535 |
+
>>> decl1.variable.value == NoneToken() # OK
|
| 1536 |
+
True
|
| 1537 |
+
>>> decl2 = x.as_Declaration(value=42.0)
|
| 1538 |
+
>>> decl2.variable.value == 42.0
|
| 1539 |
+
True
|
| 1540 |
+
|
| 1541 |
+
"""
|
| 1542 |
+
kw = self.kwargs()
|
| 1543 |
+
kw.update(kwargs)
|
| 1544 |
+
return Declaration(self.func(**kw))
|
| 1545 |
+
|
| 1546 |
+
def _relation(self, rhs, op):
|
| 1547 |
+
try:
|
| 1548 |
+
rhs = _sympify(rhs)
|
| 1549 |
+
except SympifyError:
|
| 1550 |
+
raise TypeError("Invalid comparison %s < %s" % (self, rhs))
|
| 1551 |
+
return op(self, rhs, evaluate=False)
|
| 1552 |
+
|
| 1553 |
+
__lt__ = lambda self, other: self._relation(other, Lt)
|
| 1554 |
+
__le__ = lambda self, other: self._relation(other, Le)
|
| 1555 |
+
__ge__ = lambda self, other: self._relation(other, Ge)
|
| 1556 |
+
__gt__ = lambda self, other: self._relation(other, Gt)
|
| 1557 |
+
|
| 1558 |
+
class Pointer(Variable):
|
| 1559 |
+
""" Represents a pointer. See ``Variable``.
|
| 1560 |
+
|
| 1561 |
+
Examples
|
| 1562 |
+
========
|
| 1563 |
+
|
| 1564 |
+
Can create instances of ``Element``:
|
| 1565 |
+
|
| 1566 |
+
>>> from sympy import Symbol
|
| 1567 |
+
>>> from sympy.codegen.ast import Pointer
|
| 1568 |
+
>>> i = Symbol('i', integer=True)
|
| 1569 |
+
>>> p = Pointer('x')
|
| 1570 |
+
>>> p[i+1]
|
| 1571 |
+
Element(x, indices=(i + 1,))
|
| 1572 |
+
|
| 1573 |
+
"""
|
| 1574 |
+
__slots__ = ()
|
| 1575 |
+
|
| 1576 |
+
def __getitem__(self, key):
|
| 1577 |
+
try:
|
| 1578 |
+
return Element(self.symbol, key)
|
| 1579 |
+
except TypeError:
|
| 1580 |
+
return Element(self.symbol, (key,))
|
| 1581 |
+
|
| 1582 |
+
|
| 1583 |
+
class Element(Token):
|
| 1584 |
+
""" Element in (a possibly N-dimensional) array.
|
| 1585 |
+
|
| 1586 |
+
Examples
|
| 1587 |
+
========
|
| 1588 |
+
|
| 1589 |
+
>>> from sympy.codegen.ast import Element
|
| 1590 |
+
>>> elem = Element('x', 'ijk')
|
| 1591 |
+
>>> elem.symbol.name == 'x'
|
| 1592 |
+
True
|
| 1593 |
+
>>> elem.indices
|
| 1594 |
+
(i, j, k)
|
| 1595 |
+
>>> from sympy import ccode
|
| 1596 |
+
>>> ccode(elem)
|
| 1597 |
+
'x[i][j][k]'
|
| 1598 |
+
>>> ccode(Element('x', 'ijk', strides='lmn', offset='o'))
|
| 1599 |
+
'x[i*l + j*m + k*n + o]'
|
| 1600 |
+
|
| 1601 |
+
"""
|
| 1602 |
+
__slots__ = _fields = ('symbol', 'indices', 'strides', 'offset')
|
| 1603 |
+
defaults = {'strides': none, 'offset': none}
|
| 1604 |
+
_construct_symbol = staticmethod(sympify)
|
| 1605 |
+
_construct_indices = staticmethod(lambda arg: Tuple(*arg))
|
| 1606 |
+
_construct_strides = staticmethod(lambda arg: Tuple(*arg))
|
| 1607 |
+
_construct_offset = staticmethod(sympify)
|
| 1608 |
+
|
| 1609 |
+
|
| 1610 |
+
class Declaration(Token):
|
| 1611 |
+
""" Represents a variable declaration
|
| 1612 |
+
|
| 1613 |
+
Parameters
|
| 1614 |
+
==========
|
| 1615 |
+
|
| 1616 |
+
variable : Variable
|
| 1617 |
+
|
| 1618 |
+
Examples
|
| 1619 |
+
========
|
| 1620 |
+
|
| 1621 |
+
>>> from sympy.codegen.ast import Declaration, NoneToken, untyped
|
| 1622 |
+
>>> z = Declaration('z')
|
| 1623 |
+
>>> z.variable.type == untyped
|
| 1624 |
+
True
|
| 1625 |
+
>>> # value is special NoneToken() which must be tested with == operator
|
| 1626 |
+
>>> z.variable.value is None # won't work
|
| 1627 |
+
False
|
| 1628 |
+
>>> z.variable.value == None # not PEP-8 compliant
|
| 1629 |
+
True
|
| 1630 |
+
>>> z.variable.value == NoneToken() # OK
|
| 1631 |
+
True
|
| 1632 |
+
"""
|
| 1633 |
+
__slots__ = _fields = ('variable',)
|
| 1634 |
+
_construct_variable = Variable
|
| 1635 |
+
|
| 1636 |
+
|
| 1637 |
+
class While(Token):
|
| 1638 |
+
""" Represents a 'for-loop' in the code.
|
| 1639 |
+
|
| 1640 |
+
Expressions are of the form:
|
| 1641 |
+
"while condition:
|
| 1642 |
+
body..."
|
| 1643 |
+
|
| 1644 |
+
Parameters
|
| 1645 |
+
==========
|
| 1646 |
+
|
| 1647 |
+
condition : expression convertible to Boolean
|
| 1648 |
+
body : CodeBlock or iterable
|
| 1649 |
+
When passed an iterable it is used to instantiate a CodeBlock.
|
| 1650 |
+
|
| 1651 |
+
Examples
|
| 1652 |
+
========
|
| 1653 |
+
|
| 1654 |
+
>>> from sympy import symbols, Gt, Abs
|
| 1655 |
+
>>> from sympy.codegen import aug_assign, Assignment, While
|
| 1656 |
+
>>> x, dx = symbols('x dx')
|
| 1657 |
+
>>> expr = 1 - x**2
|
| 1658 |
+
>>> whl = While(Gt(Abs(dx), 1e-9), [
|
| 1659 |
+
... Assignment(dx, -expr/expr.diff(x)),
|
| 1660 |
+
... aug_assign(x, '+', dx)
|
| 1661 |
+
... ])
|
| 1662 |
+
|
| 1663 |
+
"""
|
| 1664 |
+
__slots__ = _fields = ('condition', 'body')
|
| 1665 |
+
_construct_condition = staticmethod(lambda cond: _sympify(cond))
|
| 1666 |
+
|
| 1667 |
+
@classmethod
|
| 1668 |
+
def _construct_body(cls, itr):
|
| 1669 |
+
if isinstance(itr, CodeBlock):
|
| 1670 |
+
return itr
|
| 1671 |
+
else:
|
| 1672 |
+
return CodeBlock(*itr)
|
| 1673 |
+
|
| 1674 |
+
|
| 1675 |
+
class Scope(Token):
|
| 1676 |
+
""" Represents a scope in the code.
|
| 1677 |
+
|
| 1678 |
+
Parameters
|
| 1679 |
+
==========
|
| 1680 |
+
|
| 1681 |
+
body : CodeBlock or iterable
|
| 1682 |
+
When passed an iterable it is used to instantiate a CodeBlock.
|
| 1683 |
+
|
| 1684 |
+
"""
|
| 1685 |
+
__slots__ = _fields = ('body',)
|
| 1686 |
+
|
| 1687 |
+
@classmethod
|
| 1688 |
+
def _construct_body(cls, itr):
|
| 1689 |
+
if isinstance(itr, CodeBlock):
|
| 1690 |
+
return itr
|
| 1691 |
+
else:
|
| 1692 |
+
return CodeBlock(*itr)
|
| 1693 |
+
|
| 1694 |
+
|
| 1695 |
+
class Stream(Token):
|
| 1696 |
+
""" Represents a stream.
|
| 1697 |
+
|
| 1698 |
+
There are two predefined Stream instances ``stdout`` & ``stderr``.
|
| 1699 |
+
|
| 1700 |
+
Parameters
|
| 1701 |
+
==========
|
| 1702 |
+
|
| 1703 |
+
name : str
|
| 1704 |
+
|
| 1705 |
+
Examples
|
| 1706 |
+
========
|
| 1707 |
+
|
| 1708 |
+
>>> from sympy import pycode, Symbol
|
| 1709 |
+
>>> from sympy.codegen.ast import Print, stderr, QuotedString
|
| 1710 |
+
>>> print(pycode(Print(['x'], file=stderr)))
|
| 1711 |
+
print(x, file=sys.stderr)
|
| 1712 |
+
>>> x = Symbol('x')
|
| 1713 |
+
>>> print(pycode(Print([QuotedString('x')], file=stderr))) # print literally "x"
|
| 1714 |
+
print("x", file=sys.stderr)
|
| 1715 |
+
|
| 1716 |
+
"""
|
| 1717 |
+
__slots__ = _fields = ('name',)
|
| 1718 |
+
_construct_name = String
|
| 1719 |
+
|
| 1720 |
+
stdout = Stream('stdout')
|
| 1721 |
+
stderr = Stream('stderr')
|
| 1722 |
+
|
| 1723 |
+
|
| 1724 |
+
class Print(Token):
|
| 1725 |
+
r""" Represents print command in the code.
|
| 1726 |
+
|
| 1727 |
+
Parameters
|
| 1728 |
+
==========
|
| 1729 |
+
|
| 1730 |
+
formatstring : str
|
| 1731 |
+
*args : Basic instances (or convertible to such through sympify)
|
| 1732 |
+
|
| 1733 |
+
Examples
|
| 1734 |
+
========
|
| 1735 |
+
|
| 1736 |
+
>>> from sympy.codegen.ast import Print
|
| 1737 |
+
>>> from sympy import pycode
|
| 1738 |
+
>>> print(pycode(Print('x y'.split(), "coordinate: %12.5g %12.5g\\n")))
|
| 1739 |
+
print("coordinate: %12.5g %12.5g\n" % (x, y), end="")
|
| 1740 |
+
|
| 1741 |
+
"""
|
| 1742 |
+
|
| 1743 |
+
__slots__ = _fields = ('print_args', 'format_string', 'file')
|
| 1744 |
+
defaults = {'format_string': none, 'file': none}
|
| 1745 |
+
|
| 1746 |
+
_construct_print_args = staticmethod(_mk_Tuple)
|
| 1747 |
+
_construct_format_string = QuotedString
|
| 1748 |
+
_construct_file = Stream
|
| 1749 |
+
|
| 1750 |
+
|
| 1751 |
+
class FunctionPrototype(Node):
|
| 1752 |
+
""" Represents a function prototype
|
| 1753 |
+
|
| 1754 |
+
Allows the user to generate forward declaration in e.g. C/C++.
|
| 1755 |
+
|
| 1756 |
+
Parameters
|
| 1757 |
+
==========
|
| 1758 |
+
|
| 1759 |
+
return_type : Type
|
| 1760 |
+
name : str
|
| 1761 |
+
parameters: iterable of Variable instances
|
| 1762 |
+
attrs : iterable of Attribute instances
|
| 1763 |
+
|
| 1764 |
+
Examples
|
| 1765 |
+
========
|
| 1766 |
+
|
| 1767 |
+
>>> from sympy import ccode, symbols
|
| 1768 |
+
>>> from sympy.codegen.ast import real, FunctionPrototype
|
| 1769 |
+
>>> x, y = symbols('x y', real=True)
|
| 1770 |
+
>>> fp = FunctionPrototype(real, 'foo', [x, y])
|
| 1771 |
+
>>> ccode(fp)
|
| 1772 |
+
'double foo(double x, double y)'
|
| 1773 |
+
|
| 1774 |
+
"""
|
| 1775 |
+
|
| 1776 |
+
__slots__ = ('return_type', 'name', 'parameters')
|
| 1777 |
+
_fields: tuple[str, ...] = __slots__ + Node._fields
|
| 1778 |
+
|
| 1779 |
+
_construct_return_type = Type
|
| 1780 |
+
_construct_name = String
|
| 1781 |
+
|
| 1782 |
+
@staticmethod
|
| 1783 |
+
def _construct_parameters(args):
|
| 1784 |
+
def _var(arg):
|
| 1785 |
+
if isinstance(arg, Declaration):
|
| 1786 |
+
return arg.variable
|
| 1787 |
+
elif isinstance(arg, Variable):
|
| 1788 |
+
return arg
|
| 1789 |
+
else:
|
| 1790 |
+
return Variable.deduced(arg)
|
| 1791 |
+
return Tuple(*map(_var, args))
|
| 1792 |
+
|
| 1793 |
+
@classmethod
|
| 1794 |
+
def from_FunctionDefinition(cls, func_def):
|
| 1795 |
+
if not isinstance(func_def, FunctionDefinition):
|
| 1796 |
+
raise TypeError("func_def is not an instance of FunctionDefinition")
|
| 1797 |
+
return cls(**func_def.kwargs(exclude=('body',)))
|
| 1798 |
+
|
| 1799 |
+
|
| 1800 |
+
class FunctionDefinition(FunctionPrototype):
|
| 1801 |
+
""" Represents a function definition in the code.
|
| 1802 |
+
|
| 1803 |
+
Parameters
|
| 1804 |
+
==========
|
| 1805 |
+
|
| 1806 |
+
return_type : Type
|
| 1807 |
+
name : str
|
| 1808 |
+
parameters: iterable of Variable instances
|
| 1809 |
+
body : CodeBlock or iterable
|
| 1810 |
+
attrs : iterable of Attribute instances
|
| 1811 |
+
|
| 1812 |
+
Examples
|
| 1813 |
+
========
|
| 1814 |
+
|
| 1815 |
+
>>> from sympy import ccode, symbols
|
| 1816 |
+
>>> from sympy.codegen.ast import real, FunctionPrototype
|
| 1817 |
+
>>> x, y = symbols('x y', real=True)
|
| 1818 |
+
>>> fp = FunctionPrototype(real, 'foo', [x, y])
|
| 1819 |
+
>>> ccode(fp)
|
| 1820 |
+
'double foo(double x, double y)'
|
| 1821 |
+
>>> from sympy.codegen.ast import FunctionDefinition, Return
|
| 1822 |
+
>>> body = [Return(x*y)]
|
| 1823 |
+
>>> fd = FunctionDefinition.from_FunctionPrototype(fp, body)
|
| 1824 |
+
>>> print(ccode(fd))
|
| 1825 |
+
double foo(double x, double y){
|
| 1826 |
+
return x*y;
|
| 1827 |
+
}
|
| 1828 |
+
"""
|
| 1829 |
+
|
| 1830 |
+
__slots__ = ('body', )
|
| 1831 |
+
_fields = FunctionPrototype._fields[:-1] + __slots__ + Node._fields
|
| 1832 |
+
|
| 1833 |
+
@classmethod
|
| 1834 |
+
def _construct_body(cls, itr):
|
| 1835 |
+
if isinstance(itr, CodeBlock):
|
| 1836 |
+
return itr
|
| 1837 |
+
else:
|
| 1838 |
+
return CodeBlock(*itr)
|
| 1839 |
+
|
| 1840 |
+
@classmethod
|
| 1841 |
+
def from_FunctionPrototype(cls, func_proto, body):
|
| 1842 |
+
if not isinstance(func_proto, FunctionPrototype):
|
| 1843 |
+
raise TypeError("func_proto is not an instance of FunctionPrototype")
|
| 1844 |
+
return cls(body=body, **func_proto.kwargs())
|
| 1845 |
+
|
| 1846 |
+
|
| 1847 |
+
class Return(Token):
|
| 1848 |
+
""" Represents a return command in the code.
|
| 1849 |
+
|
| 1850 |
+
Parameters
|
| 1851 |
+
==========
|
| 1852 |
+
|
| 1853 |
+
return : Basic
|
| 1854 |
+
|
| 1855 |
+
Examples
|
| 1856 |
+
========
|
| 1857 |
+
|
| 1858 |
+
>>> from sympy.codegen.ast import Return
|
| 1859 |
+
>>> from sympy.printing.pycode import pycode
|
| 1860 |
+
>>> from sympy import Symbol
|
| 1861 |
+
>>> x = Symbol('x')
|
| 1862 |
+
>>> print(pycode(Return(x)))
|
| 1863 |
+
return x
|
| 1864 |
+
|
| 1865 |
+
"""
|
| 1866 |
+
__slots__ = _fields = ('return',)
|
| 1867 |
+
_construct_return=staticmethod(_sympify)
|
| 1868 |
+
|
| 1869 |
+
|
| 1870 |
+
class FunctionCall(Token, Expr):
|
| 1871 |
+
""" Represents a call to a function in the code.
|
| 1872 |
+
|
| 1873 |
+
Parameters
|
| 1874 |
+
==========
|
| 1875 |
+
|
| 1876 |
+
name : str
|
| 1877 |
+
function_args : Tuple
|
| 1878 |
+
|
| 1879 |
+
Examples
|
| 1880 |
+
========
|
| 1881 |
+
|
| 1882 |
+
>>> from sympy.codegen.ast import FunctionCall
|
| 1883 |
+
>>> from sympy import pycode
|
| 1884 |
+
>>> fcall = FunctionCall('foo', 'bar baz'.split())
|
| 1885 |
+
>>> print(pycode(fcall))
|
| 1886 |
+
foo(bar, baz)
|
| 1887 |
+
|
| 1888 |
+
"""
|
| 1889 |
+
__slots__ = _fields = ('name', 'function_args')
|
| 1890 |
+
|
| 1891 |
+
_construct_name = String
|
| 1892 |
+
_construct_function_args = staticmethod(lambda args: Tuple(*args))
|
| 1893 |
+
|
| 1894 |
+
|
| 1895 |
+
class Raise(Token):
|
| 1896 |
+
""" Prints as 'raise ...' in Python, 'throw ...' in C++"""
|
| 1897 |
+
__slots__ = _fields = ('exception',)
|
| 1898 |
+
|
| 1899 |
+
|
| 1900 |
+
class RuntimeError_(Token):
|
| 1901 |
+
""" Represents 'std::runtime_error' in C++ and 'RuntimeError' in Python.
|
| 1902 |
+
|
| 1903 |
+
Note that the latter is uncommon, and you might want to use e.g. ValueError.
|
| 1904 |
+
"""
|
| 1905 |
+
__slots__ = _fields = ('message',)
|
| 1906 |
+
_construct_message = String
|
pllava/lib/python3.10/site-packages/sympy/codegen/cnodes.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
AST nodes specific to the C family of languages
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from sympy.codegen.ast import (
|
| 6 |
+
Attribute, Declaration, Node, String, Token, Type, none,
|
| 7 |
+
FunctionCall, CodeBlock
|
| 8 |
+
)
|
| 9 |
+
from sympy.core.basic import Basic
|
| 10 |
+
from sympy.core.containers import Tuple
|
| 11 |
+
from sympy.core.sympify import sympify
|
| 12 |
+
|
| 13 |
+
void = Type('void')
|
| 14 |
+
|
| 15 |
+
restrict = Attribute('restrict') # guarantees no pointer aliasing
|
| 16 |
+
volatile = Attribute('volatile')
|
| 17 |
+
static = Attribute('static')
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def alignof(arg):
|
| 21 |
+
""" Generate of FunctionCall instance for calling 'alignof' """
|
| 22 |
+
return FunctionCall('alignof', [String(arg) if isinstance(arg, str) else arg])
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def sizeof(arg):
|
| 26 |
+
""" Generate of FunctionCall instance for calling 'sizeof'
|
| 27 |
+
|
| 28 |
+
Examples
|
| 29 |
+
========
|
| 30 |
+
|
| 31 |
+
>>> from sympy.codegen.ast import real
|
| 32 |
+
>>> from sympy.codegen.cnodes import sizeof
|
| 33 |
+
>>> from sympy import ccode
|
| 34 |
+
>>> ccode(sizeof(real))
|
| 35 |
+
'sizeof(double)'
|
| 36 |
+
"""
|
| 37 |
+
return FunctionCall('sizeof', [String(arg) if isinstance(arg, str) else arg])
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class CommaOperator(Basic):
|
| 41 |
+
""" Represents the comma operator in C """
|
| 42 |
+
def __new__(cls, *args):
|
| 43 |
+
return Basic.__new__(cls, *[sympify(arg) for arg in args])
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class Label(Node):
|
| 47 |
+
""" Label for use with e.g. goto statement.
|
| 48 |
+
|
| 49 |
+
Examples
|
| 50 |
+
========
|
| 51 |
+
|
| 52 |
+
>>> from sympy import ccode, Symbol
|
| 53 |
+
>>> from sympy.codegen.cnodes import Label, PreIncrement
|
| 54 |
+
>>> print(ccode(Label('foo')))
|
| 55 |
+
foo:
|
| 56 |
+
>>> print(ccode(Label('bar', [PreIncrement(Symbol('a'))])))
|
| 57 |
+
bar:
|
| 58 |
+
++(a);
|
| 59 |
+
|
| 60 |
+
"""
|
| 61 |
+
__slots__ = _fields = ('name', 'body')
|
| 62 |
+
defaults = {'body': none}
|
| 63 |
+
_construct_name = String
|
| 64 |
+
|
| 65 |
+
@classmethod
|
| 66 |
+
def _construct_body(cls, itr):
|
| 67 |
+
if isinstance(itr, CodeBlock):
|
| 68 |
+
return itr
|
| 69 |
+
else:
|
| 70 |
+
return CodeBlock(*itr)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class goto(Token):
|
| 74 |
+
""" Represents goto in C """
|
| 75 |
+
__slots__ = _fields = ('label',)
|
| 76 |
+
_construct_label = Label
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class PreDecrement(Basic):
|
| 80 |
+
""" Represents the pre-decrement operator
|
| 81 |
+
|
| 82 |
+
Examples
|
| 83 |
+
========
|
| 84 |
+
|
| 85 |
+
>>> from sympy.abc import x
|
| 86 |
+
>>> from sympy.codegen.cnodes import PreDecrement
|
| 87 |
+
>>> from sympy import ccode
|
| 88 |
+
>>> ccode(PreDecrement(x))
|
| 89 |
+
'--(x)'
|
| 90 |
+
|
| 91 |
+
"""
|
| 92 |
+
nargs = 1
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class PostDecrement(Basic):
|
| 96 |
+
""" Represents the post-decrement operator
|
| 97 |
+
|
| 98 |
+
Examples
|
| 99 |
+
========
|
| 100 |
+
|
| 101 |
+
>>> from sympy.abc import x
|
| 102 |
+
>>> from sympy.codegen.cnodes import PostDecrement
|
| 103 |
+
>>> from sympy import ccode
|
| 104 |
+
>>> ccode(PostDecrement(x))
|
| 105 |
+
'(x)--'
|
| 106 |
+
|
| 107 |
+
"""
|
| 108 |
+
nargs = 1
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
class PreIncrement(Basic):
|
| 112 |
+
""" Represents the pre-increment operator
|
| 113 |
+
|
| 114 |
+
Examples
|
| 115 |
+
========
|
| 116 |
+
|
| 117 |
+
>>> from sympy.abc import x
|
| 118 |
+
>>> from sympy.codegen.cnodes import PreIncrement
|
| 119 |
+
>>> from sympy import ccode
|
| 120 |
+
>>> ccode(PreIncrement(x))
|
| 121 |
+
'++(x)'
|
| 122 |
+
|
| 123 |
+
"""
|
| 124 |
+
nargs = 1
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
class PostIncrement(Basic):
|
| 128 |
+
""" Represents the post-increment operator
|
| 129 |
+
|
| 130 |
+
Examples
|
| 131 |
+
========
|
| 132 |
+
|
| 133 |
+
>>> from sympy.abc import x
|
| 134 |
+
>>> from sympy.codegen.cnodes import PostIncrement
|
| 135 |
+
>>> from sympy import ccode
|
| 136 |
+
>>> ccode(PostIncrement(x))
|
| 137 |
+
'(x)++'
|
| 138 |
+
|
| 139 |
+
"""
|
| 140 |
+
nargs = 1
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
class struct(Node):
|
| 144 |
+
""" Represents a struct in C """
|
| 145 |
+
__slots__ = _fields = ('name', 'declarations')
|
| 146 |
+
defaults = {'name': none}
|
| 147 |
+
_construct_name = String
|
| 148 |
+
|
| 149 |
+
@classmethod
|
| 150 |
+
def _construct_declarations(cls, args):
|
| 151 |
+
return Tuple(*[Declaration(arg) for arg in args])
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
class union(struct):
|
| 155 |
+
""" Represents a union in C """
|
| 156 |
+
__slots__ = ()
|
pllava/lib/python3.10/site-packages/sympy/codegen/cxxnodes.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
AST nodes specific to C++.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from sympy.codegen.ast import Attribute, String, Token, Type, none
|
| 6 |
+
|
| 7 |
+
class using(Token):
|
| 8 |
+
""" Represents a 'using' statement in C++ """
|
| 9 |
+
__slots__ = _fields = ('type', 'alias')
|
| 10 |
+
defaults = {'alias': none}
|
| 11 |
+
_construct_type = Type
|
| 12 |
+
_construct_alias = String
|
| 13 |
+
|
| 14 |
+
constexpr = Attribute('constexpr')
|
pllava/lib/python3.10/site-packages/sympy/codegen/futils.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from itertools import chain
|
| 2 |
+
from sympy.codegen.fnodes import Module
|
| 3 |
+
from sympy.core.symbol import Dummy
|
| 4 |
+
from sympy.printing.fortran import FCodePrinter
|
| 5 |
+
|
| 6 |
+
""" This module collects utilities for rendering Fortran code. """
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def render_as_module(definitions, name, declarations=(), printer_settings=None):
|
| 10 |
+
""" Creates a ``Module`` instance and renders it as a string.
|
| 11 |
+
|
| 12 |
+
This generates Fortran source code for a module with the correct ``use`` statements.
|
| 13 |
+
|
| 14 |
+
Parameters
|
| 15 |
+
==========
|
| 16 |
+
|
| 17 |
+
definitions : iterable
|
| 18 |
+
Passed to :class:`sympy.codegen.fnodes.Module`.
|
| 19 |
+
name : str
|
| 20 |
+
Passed to :class:`sympy.codegen.fnodes.Module`.
|
| 21 |
+
declarations : iterable
|
| 22 |
+
Passed to :class:`sympy.codegen.fnodes.Module`. It will be extended with
|
| 23 |
+
use statements, 'implicit none' and public list generated from ``definitions``.
|
| 24 |
+
printer_settings : dict
|
| 25 |
+
Passed to ``FCodePrinter`` (default: ``{'standard': 2003, 'source_format': 'free'}``).
|
| 26 |
+
|
| 27 |
+
"""
|
| 28 |
+
printer_settings = printer_settings or {'standard': 2003, 'source_format': 'free'}
|
| 29 |
+
printer = FCodePrinter(printer_settings)
|
| 30 |
+
dummy = Dummy()
|
| 31 |
+
if isinstance(definitions, Module):
|
| 32 |
+
raise ValueError("This function expects to construct a module on its own.")
|
| 33 |
+
mod = Module(name, chain(declarations, [dummy]), definitions)
|
| 34 |
+
fstr = printer.doprint(mod)
|
| 35 |
+
module_use_str = ' %s\n' % ' \n'.join(['use %s, only: %s' % (k, ', '.join(v)) for
|
| 36 |
+
k, v in printer.module_uses.items()])
|
| 37 |
+
module_use_str += ' implicit none\n'
|
| 38 |
+
module_use_str += ' private\n'
|
| 39 |
+
module_use_str += ' public %s\n' % ', '.join([str(node.name) for node in definitions if getattr(node, 'name', None)])
|
| 40 |
+
return fstr.replace(printer.doprint(dummy), module_use_str)
|
pllava/lib/python3.10/site-packages/sympy/codegen/matrix_nodes.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Additional AST nodes for operations on matrices. The nodes in this module
|
| 3 |
+
are meant to represent optimization of matrix expressions within codegen's
|
| 4 |
+
target languages that cannot be represented by SymPy expressions.
|
| 5 |
+
|
| 6 |
+
As an example, we can use :meth:`sympy.codegen.rewriting.optimize` and the
|
| 7 |
+
``matin_opt`` optimization provided in :mod:`sympy.codegen.rewriting` to
|
| 8 |
+
transform matrix multiplication under certain assumptions:
|
| 9 |
+
|
| 10 |
+
>>> from sympy import symbols, MatrixSymbol
|
| 11 |
+
>>> n = symbols('n', integer=True)
|
| 12 |
+
>>> A = MatrixSymbol('A', n, n)
|
| 13 |
+
>>> x = MatrixSymbol('x', n, 1)
|
| 14 |
+
>>> expr = A**(-1) * x
|
| 15 |
+
>>> from sympy import assuming, Q
|
| 16 |
+
>>> from sympy.codegen.rewriting import matinv_opt, optimize
|
| 17 |
+
>>> with assuming(Q.fullrank(A)):
|
| 18 |
+
... optimize(expr, [matinv_opt])
|
| 19 |
+
MatrixSolve(A, vector=x)
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
from .ast import Token
|
| 23 |
+
from sympy.matrices import MatrixExpr
|
| 24 |
+
from sympy.core.sympify import sympify
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class MatrixSolve(Token, MatrixExpr):
|
| 28 |
+
"""Represents an operation to solve a linear matrix equation.
|
| 29 |
+
|
| 30 |
+
Parameters
|
| 31 |
+
==========
|
| 32 |
+
|
| 33 |
+
matrix : MatrixSymbol
|
| 34 |
+
|
| 35 |
+
Matrix representing the coefficients of variables in the linear
|
| 36 |
+
equation. This matrix must be square and full-rank (i.e. all columns must
|
| 37 |
+
be linearly independent) for the solving operation to be valid.
|
| 38 |
+
|
| 39 |
+
vector : MatrixSymbol
|
| 40 |
+
|
| 41 |
+
One-column matrix representing the solutions to the equations
|
| 42 |
+
represented in ``matrix``.
|
| 43 |
+
|
| 44 |
+
Examples
|
| 45 |
+
========
|
| 46 |
+
|
| 47 |
+
>>> from sympy import symbols, MatrixSymbol
|
| 48 |
+
>>> from sympy.codegen.matrix_nodes import MatrixSolve
|
| 49 |
+
>>> n = symbols('n', integer=True)
|
| 50 |
+
>>> A = MatrixSymbol('A', n, n)
|
| 51 |
+
>>> x = MatrixSymbol('x', n, 1)
|
| 52 |
+
>>> from sympy.printing.numpy import NumPyPrinter
|
| 53 |
+
>>> NumPyPrinter().doprint(MatrixSolve(A, x))
|
| 54 |
+
'numpy.linalg.solve(A, x)'
|
| 55 |
+
>>> from sympy import octave_code
|
| 56 |
+
>>> octave_code(MatrixSolve(A, x))
|
| 57 |
+
'A \\\\ x'
|
| 58 |
+
|
| 59 |
+
"""
|
| 60 |
+
__slots__ = _fields = ('matrix', 'vector')
|
| 61 |
+
|
| 62 |
+
_construct_matrix = staticmethod(sympify)
|
| 63 |
+
_construct_vector = staticmethod(sympify)
|
| 64 |
+
|
| 65 |
+
@property
|
| 66 |
+
def shape(self):
|
| 67 |
+
return self.vector.shape
|
| 68 |
+
|
| 69 |
+
def _eval_derivative(self, x):
|
| 70 |
+
A, b = self.matrix, self.vector
|
| 71 |
+
return MatrixSolve(A, b.diff(x) - A.diff(x) * MatrixSolve(A, b))
|
pllava/lib/python3.10/site-packages/sympy/codegen/numpy_nodes.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.function import Add, ArgumentIndexError, Function
|
| 2 |
+
from sympy.core.power import Pow
|
| 3 |
+
from sympy.core.singleton import S
|
| 4 |
+
from sympy.core.sorting import default_sort_key
|
| 5 |
+
from sympy.functions.elementary.exponential import exp, log
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def _logaddexp(x1, x2, *, evaluate=True):
|
| 9 |
+
return log(Add(exp(x1, evaluate=evaluate), exp(x2, evaluate=evaluate), evaluate=evaluate))
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
_two = S.One*2
|
| 13 |
+
_ln2 = log(_two)
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _lb(x, *, evaluate=True):
|
| 17 |
+
return log(x, evaluate=evaluate)/_ln2
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _exp2(x, *, evaluate=True):
|
| 21 |
+
return Pow(_two, x, evaluate=evaluate)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _logaddexp2(x1, x2, *, evaluate=True):
|
| 25 |
+
return _lb(Add(_exp2(x1, evaluate=evaluate),
|
| 26 |
+
_exp2(x2, evaluate=evaluate), evaluate=evaluate))
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class logaddexp(Function):
|
| 30 |
+
""" Logarithm of the sum of exponentiations of the inputs.
|
| 31 |
+
|
| 32 |
+
Helper class for use with e.g. numpy.logaddexp
|
| 33 |
+
|
| 34 |
+
See Also
|
| 35 |
+
========
|
| 36 |
+
|
| 37 |
+
https://numpy.org/doc/stable/reference/generated/numpy.logaddexp.html
|
| 38 |
+
"""
|
| 39 |
+
nargs = 2
|
| 40 |
+
|
| 41 |
+
def __new__(cls, *args):
|
| 42 |
+
return Function.__new__(cls, *sorted(args, key=default_sort_key))
|
| 43 |
+
|
| 44 |
+
def fdiff(self, argindex=1):
|
| 45 |
+
"""
|
| 46 |
+
Returns the first derivative of this function.
|
| 47 |
+
"""
|
| 48 |
+
if argindex == 1:
|
| 49 |
+
wrt, other = self.args
|
| 50 |
+
elif argindex == 2:
|
| 51 |
+
other, wrt = self.args
|
| 52 |
+
else:
|
| 53 |
+
raise ArgumentIndexError(self, argindex)
|
| 54 |
+
return S.One/(S.One + exp(other-wrt))
|
| 55 |
+
|
| 56 |
+
def _eval_rewrite_as_log(self, x1, x2, **kwargs):
|
| 57 |
+
return _logaddexp(x1, x2)
|
| 58 |
+
|
| 59 |
+
def _eval_evalf(self, *args, **kwargs):
|
| 60 |
+
return self.rewrite(log).evalf(*args, **kwargs)
|
| 61 |
+
|
| 62 |
+
def _eval_simplify(self, *args, **kwargs):
|
| 63 |
+
a, b = (x.simplify(**kwargs) for x in self.args)
|
| 64 |
+
candidate = _logaddexp(a, b)
|
| 65 |
+
if candidate != _logaddexp(a, b, evaluate=False):
|
| 66 |
+
return candidate
|
| 67 |
+
else:
|
| 68 |
+
return logaddexp(a, b)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
class logaddexp2(Function):
|
| 72 |
+
""" Logarithm of the sum of exponentiations of the inputs in base-2.
|
| 73 |
+
|
| 74 |
+
Helper class for use with e.g. numpy.logaddexp2
|
| 75 |
+
|
| 76 |
+
See Also
|
| 77 |
+
========
|
| 78 |
+
|
| 79 |
+
https://numpy.org/doc/stable/reference/generated/numpy.logaddexp2.html
|
| 80 |
+
"""
|
| 81 |
+
nargs = 2
|
| 82 |
+
|
| 83 |
+
def __new__(cls, *args):
|
| 84 |
+
return Function.__new__(cls, *sorted(args, key=default_sort_key))
|
| 85 |
+
|
| 86 |
+
def fdiff(self, argindex=1):
|
| 87 |
+
"""
|
| 88 |
+
Returns the first derivative of this function.
|
| 89 |
+
"""
|
| 90 |
+
if argindex == 1:
|
| 91 |
+
wrt, other = self.args
|
| 92 |
+
elif argindex == 2:
|
| 93 |
+
other, wrt = self.args
|
| 94 |
+
else:
|
| 95 |
+
raise ArgumentIndexError(self, argindex)
|
| 96 |
+
return S.One/(S.One + _exp2(other-wrt))
|
| 97 |
+
|
| 98 |
+
def _eval_rewrite_as_log(self, x1, x2, **kwargs):
|
| 99 |
+
return _logaddexp2(x1, x2)
|
| 100 |
+
|
| 101 |
+
def _eval_evalf(self, *args, **kwargs):
|
| 102 |
+
return self.rewrite(log).evalf(*args, **kwargs)
|
| 103 |
+
|
| 104 |
+
def _eval_simplify(self, *args, **kwargs):
|
| 105 |
+
a, b = (x.simplify(**kwargs).factor() for x in self.args)
|
| 106 |
+
candidate = _logaddexp2(a, b)
|
| 107 |
+
if candidate != _logaddexp2(a, b, evaluate=False):
|
| 108 |
+
return candidate
|
| 109 |
+
else:
|
| 110 |
+
return logaddexp2(a, b)
|
pllava/lib/python3.10/site-packages/sympy/codegen/pynodes.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .abstract_nodes import List as AbstractList
|
| 2 |
+
from .ast import Token
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class List(AbstractList):
|
| 6 |
+
pass
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class NumExprEvaluate(Token):
|
| 10 |
+
"""represents a call to :class:`numexpr`s :func:`evaluate`"""
|
| 11 |
+
__slots__ = _fields = ('expr',)
|
pllava/lib/python3.10/site-packages/sympy/codegen/pyutils.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.printing.pycode import PythonCodePrinter
|
| 2 |
+
|
| 3 |
+
""" This module collects utilities for rendering Python code. """
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def render_as_module(content, standard='python3'):
|
| 7 |
+
"""Renders Python code as a module (with the required imports).
|
| 8 |
+
|
| 9 |
+
Parameters
|
| 10 |
+
==========
|
| 11 |
+
|
| 12 |
+
standard :
|
| 13 |
+
See the parameter ``standard`` in
|
| 14 |
+
:meth:`sympy.printing.pycode.pycode`
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
printer = PythonCodePrinter({'standard':standard})
|
| 18 |
+
pystr = printer.doprint(content)
|
| 19 |
+
if printer._settings['fully_qualified_modules']:
|
| 20 |
+
module_imports_str = '\n'.join('import %s' % k for k in printer.module_imports)
|
| 21 |
+
else:
|
| 22 |
+
module_imports_str = '\n'.join(['from %s import %s' % (k, ', '.join(v)) for
|
| 23 |
+
k, v in printer.module_imports.items()])
|
| 24 |
+
return module_imports_str + '\n\n' + pystr
|
pllava/lib/python3.10/site-packages/sympy/codegen/rewriting.py
ADDED
|
@@ -0,0 +1,357 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Classes and functions useful for rewriting expressions for optimized code
|
| 3 |
+
generation. Some languages (or standards thereof), e.g. C99, offer specialized
|
| 4 |
+
math functions for better performance and/or precision.
|
| 5 |
+
|
| 6 |
+
Using the ``optimize`` function in this module, together with a collection of
|
| 7 |
+
rules (represented as instances of ``Optimization``), one can rewrite the
|
| 8 |
+
expressions for this purpose::
|
| 9 |
+
|
| 10 |
+
>>> from sympy import Symbol, exp, log
|
| 11 |
+
>>> from sympy.codegen.rewriting import optimize, optims_c99
|
| 12 |
+
>>> x = Symbol('x')
|
| 13 |
+
>>> optimize(3*exp(2*x) - 3, optims_c99)
|
| 14 |
+
3*expm1(2*x)
|
| 15 |
+
>>> optimize(exp(2*x) - 1 - exp(-33), optims_c99)
|
| 16 |
+
expm1(2*x) - exp(-33)
|
| 17 |
+
>>> optimize(log(3*x + 3), optims_c99)
|
| 18 |
+
log1p(x) + log(3)
|
| 19 |
+
>>> optimize(log(2*x + 3), optims_c99)
|
| 20 |
+
log(2*x + 3)
|
| 21 |
+
|
| 22 |
+
The ``optims_c99`` imported above is tuple containing the following instances
|
| 23 |
+
(which may be imported from ``sympy.codegen.rewriting``):
|
| 24 |
+
|
| 25 |
+
- ``expm1_opt``
|
| 26 |
+
- ``log1p_opt``
|
| 27 |
+
- ``exp2_opt``
|
| 28 |
+
- ``log2_opt``
|
| 29 |
+
- ``log2const_opt``
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
"""
|
| 33 |
+
from sympy.core.function import expand_log
|
| 34 |
+
from sympy.core.singleton import S
|
| 35 |
+
from sympy.core.symbol import Wild
|
| 36 |
+
from sympy.functions.elementary.complexes import sign
|
| 37 |
+
from sympy.functions.elementary.exponential import (exp, log)
|
| 38 |
+
from sympy.functions.elementary.miscellaneous import (Max, Min)
|
| 39 |
+
from sympy.functions.elementary.trigonometric import (cos, sin, sinc)
|
| 40 |
+
from sympy.assumptions import Q, ask
|
| 41 |
+
from sympy.codegen.cfunctions import log1p, log2, exp2, expm1
|
| 42 |
+
from sympy.codegen.matrix_nodes import MatrixSolve
|
| 43 |
+
from sympy.core.expr import UnevaluatedExpr
|
| 44 |
+
from sympy.core.power import Pow
|
| 45 |
+
from sympy.codegen.numpy_nodes import logaddexp, logaddexp2
|
| 46 |
+
from sympy.codegen.scipy_nodes import cosm1, powm1
|
| 47 |
+
from sympy.core.mul import Mul
|
| 48 |
+
from sympy.matrices.expressions.matexpr import MatrixSymbol
|
| 49 |
+
from sympy.utilities.iterables import sift
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class Optimization:
|
| 53 |
+
""" Abstract base class for rewriting optimization.
|
| 54 |
+
|
| 55 |
+
Subclasses should implement ``__call__`` taking an expression
|
| 56 |
+
as argument.
|
| 57 |
+
|
| 58 |
+
Parameters
|
| 59 |
+
==========
|
| 60 |
+
cost_function : callable returning number
|
| 61 |
+
priority : number
|
| 62 |
+
|
| 63 |
+
"""
|
| 64 |
+
def __init__(self, cost_function=None, priority=1):
|
| 65 |
+
self.cost_function = cost_function
|
| 66 |
+
self.priority=priority
|
| 67 |
+
|
| 68 |
+
def cheapest(self, *args):
|
| 69 |
+
return min(args, key=self.cost_function)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class ReplaceOptim(Optimization):
|
| 73 |
+
""" Rewriting optimization calling replace on expressions.
|
| 74 |
+
|
| 75 |
+
Explanation
|
| 76 |
+
===========
|
| 77 |
+
|
| 78 |
+
The instance can be used as a function on expressions for which
|
| 79 |
+
it will apply the ``replace`` method (see
|
| 80 |
+
:meth:`sympy.core.basic.Basic.replace`).
|
| 81 |
+
|
| 82 |
+
Parameters
|
| 83 |
+
==========
|
| 84 |
+
|
| 85 |
+
query :
|
| 86 |
+
First argument passed to replace.
|
| 87 |
+
value :
|
| 88 |
+
Second argument passed to replace.
|
| 89 |
+
|
| 90 |
+
Examples
|
| 91 |
+
========
|
| 92 |
+
|
| 93 |
+
>>> from sympy import Symbol
|
| 94 |
+
>>> from sympy.codegen.rewriting import ReplaceOptim
|
| 95 |
+
>>> from sympy.codegen.cfunctions import exp2
|
| 96 |
+
>>> x = Symbol('x')
|
| 97 |
+
>>> exp2_opt = ReplaceOptim(lambda p: p.is_Pow and p.base == 2,
|
| 98 |
+
... lambda p: exp2(p.exp))
|
| 99 |
+
>>> exp2_opt(2**x)
|
| 100 |
+
exp2(x)
|
| 101 |
+
|
| 102 |
+
"""
|
| 103 |
+
|
| 104 |
+
def __init__(self, query, value, **kwargs):
|
| 105 |
+
super().__init__(**kwargs)
|
| 106 |
+
self.query = query
|
| 107 |
+
self.value = value
|
| 108 |
+
|
| 109 |
+
def __call__(self, expr):
|
| 110 |
+
return expr.replace(self.query, self.value)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def optimize(expr, optimizations):
|
| 114 |
+
""" Apply optimizations to an expression.
|
| 115 |
+
|
| 116 |
+
Parameters
|
| 117 |
+
==========
|
| 118 |
+
|
| 119 |
+
expr : expression
|
| 120 |
+
optimizations : iterable of ``Optimization`` instances
|
| 121 |
+
The optimizations will be sorted with respect to ``priority`` (highest first).
|
| 122 |
+
|
| 123 |
+
Examples
|
| 124 |
+
========
|
| 125 |
+
|
| 126 |
+
>>> from sympy import log, Symbol
|
| 127 |
+
>>> from sympy.codegen.rewriting import optims_c99, optimize
|
| 128 |
+
>>> x = Symbol('x')
|
| 129 |
+
>>> optimize(log(x+3)/log(2) + log(x**2 + 1), optims_c99)
|
| 130 |
+
log1p(x**2) + log2(x + 3)
|
| 131 |
+
|
| 132 |
+
"""
|
| 133 |
+
|
| 134 |
+
for optim in sorted(optimizations, key=lambda opt: opt.priority, reverse=True):
|
| 135 |
+
new_expr = optim(expr)
|
| 136 |
+
if optim.cost_function is None:
|
| 137 |
+
expr = new_expr
|
| 138 |
+
else:
|
| 139 |
+
expr = optim.cheapest(expr, new_expr)
|
| 140 |
+
return expr
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
exp2_opt = ReplaceOptim(
|
| 144 |
+
lambda p: p.is_Pow and p.base == 2,
|
| 145 |
+
lambda p: exp2(p.exp)
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
_d = Wild('d', properties=[lambda x: x.is_Dummy])
|
| 150 |
+
_u = Wild('u', properties=[lambda x: not x.is_number and not x.is_Add])
|
| 151 |
+
_v = Wild('v')
|
| 152 |
+
_w = Wild('w')
|
| 153 |
+
_n = Wild('n', properties=[lambda x: x.is_number])
|
| 154 |
+
|
| 155 |
+
sinc_opt1 = ReplaceOptim(
|
| 156 |
+
sin(_w)/_w, sinc(_w)
|
| 157 |
+
)
|
| 158 |
+
sinc_opt2 = ReplaceOptim(
|
| 159 |
+
sin(_n*_w)/_w, _n*sinc(_n*_w)
|
| 160 |
+
)
|
| 161 |
+
sinc_opts = (sinc_opt1, sinc_opt2)
|
| 162 |
+
|
| 163 |
+
log2_opt = ReplaceOptim(_v*log(_w)/log(2), _v*log2(_w), cost_function=lambda expr: expr.count(
|
| 164 |
+
lambda e: ( # division & eval of transcendentals are expensive floating point operations...
|
| 165 |
+
e.is_Pow and e.exp.is_negative # division
|
| 166 |
+
or (isinstance(e, (log, log2)) and not e.args[0].is_number)) # transcendental
|
| 167 |
+
)
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
log2const_opt = ReplaceOptim(log(2)*log2(_w), log(_w))
|
| 171 |
+
|
| 172 |
+
logsumexp_2terms_opt = ReplaceOptim(
|
| 173 |
+
lambda l: (isinstance(l, log)
|
| 174 |
+
and l.args[0].is_Add
|
| 175 |
+
and len(l.args[0].args) == 2
|
| 176 |
+
and all(isinstance(t, exp) for t in l.args[0].args)),
|
| 177 |
+
lambda l: (
|
| 178 |
+
Max(*[e.args[0] for e in l.args[0].args]) +
|
| 179 |
+
log1p(exp(Min(*[e.args[0] for e in l.args[0].args])))
|
| 180 |
+
)
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
class FuncMinusOneOptim(ReplaceOptim):
|
| 185 |
+
"""Specialization of ReplaceOptim for functions evaluating "f(x) - 1".
|
| 186 |
+
|
| 187 |
+
Explanation
|
| 188 |
+
===========
|
| 189 |
+
|
| 190 |
+
Numerical functions which go toward one as x go toward zero is often best
|
| 191 |
+
implemented by a dedicated function in order to avoid catastrophic
|
| 192 |
+
cancellation. One such example is ``expm1(x)`` in the C standard library
|
| 193 |
+
which evaluates ``exp(x) - 1``. Such functions preserves many more
|
| 194 |
+
significant digits when its argument is much smaller than one, compared
|
| 195 |
+
to subtracting one afterwards.
|
| 196 |
+
|
| 197 |
+
Parameters
|
| 198 |
+
==========
|
| 199 |
+
|
| 200 |
+
func :
|
| 201 |
+
The function which is subtracted by one.
|
| 202 |
+
func_m_1 :
|
| 203 |
+
The specialized function evaluating ``func(x) - 1``.
|
| 204 |
+
opportunistic : bool
|
| 205 |
+
When ``True``, apply the transformation as long as the magnitude of the
|
| 206 |
+
remaining number terms decreases. When ``False``, only apply the
|
| 207 |
+
transformation if it completely eliminates the number term.
|
| 208 |
+
|
| 209 |
+
Examples
|
| 210 |
+
========
|
| 211 |
+
|
| 212 |
+
>>> from sympy import symbols, exp
|
| 213 |
+
>>> from sympy.codegen.rewriting import FuncMinusOneOptim
|
| 214 |
+
>>> from sympy.codegen.cfunctions import expm1
|
| 215 |
+
>>> x, y = symbols('x y')
|
| 216 |
+
>>> expm1_opt = FuncMinusOneOptim(exp, expm1)
|
| 217 |
+
>>> expm1_opt(exp(x) + 2*exp(5*y) - 3)
|
| 218 |
+
expm1(x) + 2*expm1(5*y)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
"""
|
| 222 |
+
|
| 223 |
+
def __init__(self, func, func_m_1, opportunistic=True):
|
| 224 |
+
weight = 10 # <-- this is an arbitrary number (heuristic)
|
| 225 |
+
super().__init__(lambda e: e.is_Add, self.replace_in_Add,
|
| 226 |
+
cost_function=lambda expr: expr.count_ops() - weight*expr.count(func_m_1))
|
| 227 |
+
self.func = func
|
| 228 |
+
self.func_m_1 = func_m_1
|
| 229 |
+
self.opportunistic = opportunistic
|
| 230 |
+
|
| 231 |
+
def _group_Add_terms(self, add):
|
| 232 |
+
numbers, non_num = sift(add.args, lambda arg: arg.is_number, binary=True)
|
| 233 |
+
numsum = sum(numbers)
|
| 234 |
+
terms_with_func, other = sift(non_num, lambda arg: arg.has(self.func), binary=True)
|
| 235 |
+
return numsum, terms_with_func, other
|
| 236 |
+
|
| 237 |
+
def replace_in_Add(self, e):
|
| 238 |
+
""" passed as second argument to Basic.replace(...) """
|
| 239 |
+
numsum, terms_with_func, other_non_num_terms = self._group_Add_terms(e)
|
| 240 |
+
if numsum == 0:
|
| 241 |
+
return e
|
| 242 |
+
substituted, untouched = [], []
|
| 243 |
+
for with_func in terms_with_func:
|
| 244 |
+
if with_func.is_Mul:
|
| 245 |
+
func, coeff = sift(with_func.args, lambda arg: arg.func == self.func, binary=True)
|
| 246 |
+
if len(func) == 1 and len(coeff) == 1:
|
| 247 |
+
func, coeff = func[0], coeff[0]
|
| 248 |
+
else:
|
| 249 |
+
coeff = None
|
| 250 |
+
elif with_func.func == self.func:
|
| 251 |
+
func, coeff = with_func, S.One
|
| 252 |
+
else:
|
| 253 |
+
coeff = None
|
| 254 |
+
|
| 255 |
+
if coeff is not None and coeff.is_number and sign(coeff) == -sign(numsum):
|
| 256 |
+
if self.opportunistic:
|
| 257 |
+
do_substitute = abs(coeff+numsum) < abs(numsum)
|
| 258 |
+
else:
|
| 259 |
+
do_substitute = coeff+numsum == 0
|
| 260 |
+
|
| 261 |
+
if do_substitute: # advantageous substitution
|
| 262 |
+
numsum += coeff
|
| 263 |
+
substituted.append(coeff*self.func_m_1(*func.args))
|
| 264 |
+
continue
|
| 265 |
+
untouched.append(with_func)
|
| 266 |
+
|
| 267 |
+
return e.func(numsum, *substituted, *untouched, *other_non_num_terms)
|
| 268 |
+
|
| 269 |
+
def __call__(self, expr):
|
| 270 |
+
alt1 = super().__call__(expr)
|
| 271 |
+
alt2 = super().__call__(expr.factor())
|
| 272 |
+
return self.cheapest(alt1, alt2)
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
expm1_opt = FuncMinusOneOptim(exp, expm1)
|
| 276 |
+
cosm1_opt = FuncMinusOneOptim(cos, cosm1)
|
| 277 |
+
powm1_opt = FuncMinusOneOptim(Pow, powm1)
|
| 278 |
+
|
| 279 |
+
log1p_opt = ReplaceOptim(
|
| 280 |
+
lambda e: isinstance(e, log),
|
| 281 |
+
lambda l: expand_log(l.replace(
|
| 282 |
+
log, lambda arg: log(arg.factor())
|
| 283 |
+
)).replace(log(_u+1), log1p(_u))
|
| 284 |
+
)
|
| 285 |
+
|
| 286 |
+
def create_expand_pow_optimization(limit, *, base_req=lambda b: b.is_symbol):
|
| 287 |
+
""" Creates an instance of :class:`ReplaceOptim` for expanding ``Pow``.
|
| 288 |
+
|
| 289 |
+
Explanation
|
| 290 |
+
===========
|
| 291 |
+
|
| 292 |
+
The requirements for expansions are that the base needs to be a symbol
|
| 293 |
+
and the exponent needs to be an Integer (and be less than or equal to
|
| 294 |
+
``limit``).
|
| 295 |
+
|
| 296 |
+
Parameters
|
| 297 |
+
==========
|
| 298 |
+
|
| 299 |
+
limit : int
|
| 300 |
+
The highest power which is expanded into multiplication.
|
| 301 |
+
base_req : function returning bool
|
| 302 |
+
Requirement on base for expansion to happen, default is to return
|
| 303 |
+
the ``is_symbol`` attribute of the base.
|
| 304 |
+
|
| 305 |
+
Examples
|
| 306 |
+
========
|
| 307 |
+
|
| 308 |
+
>>> from sympy import Symbol, sin
|
| 309 |
+
>>> from sympy.codegen.rewriting import create_expand_pow_optimization
|
| 310 |
+
>>> x = Symbol('x')
|
| 311 |
+
>>> expand_opt = create_expand_pow_optimization(3)
|
| 312 |
+
>>> expand_opt(x**5 + x**3)
|
| 313 |
+
x**5 + x*x*x
|
| 314 |
+
>>> expand_opt(x**5 + x**3 + sin(x)**3)
|
| 315 |
+
x**5 + sin(x)**3 + x*x*x
|
| 316 |
+
>>> opt2 = create_expand_pow_optimization(3, base_req=lambda b: not b.is_Function)
|
| 317 |
+
>>> opt2((x+1)**2 + sin(x)**2)
|
| 318 |
+
sin(x)**2 + (x + 1)*(x + 1)
|
| 319 |
+
|
| 320 |
+
"""
|
| 321 |
+
return ReplaceOptim(
|
| 322 |
+
lambda e: e.is_Pow and base_req(e.base) and e.exp.is_Integer and abs(e.exp) <= limit,
|
| 323 |
+
lambda p: (
|
| 324 |
+
UnevaluatedExpr(Mul(*([p.base]*+p.exp), evaluate=False)) if p.exp > 0 else
|
| 325 |
+
1/UnevaluatedExpr(Mul(*([p.base]*-p.exp), evaluate=False))
|
| 326 |
+
))
|
| 327 |
+
|
| 328 |
+
# Optimization procedures for turning A**(-1) * x into MatrixSolve(A, x)
|
| 329 |
+
def _matinv_predicate(expr):
|
| 330 |
+
# TODO: We should be able to support more than 2 elements
|
| 331 |
+
if expr.is_MatMul and len(expr.args) == 2:
|
| 332 |
+
left, right = expr.args
|
| 333 |
+
if left.is_Inverse and right.shape[1] == 1:
|
| 334 |
+
inv_arg = left.arg
|
| 335 |
+
if isinstance(inv_arg, MatrixSymbol):
|
| 336 |
+
return bool(ask(Q.fullrank(left.arg)))
|
| 337 |
+
|
| 338 |
+
return False
|
| 339 |
+
|
| 340 |
+
def _matinv_transform(expr):
|
| 341 |
+
left, right = expr.args
|
| 342 |
+
inv_arg = left.arg
|
| 343 |
+
return MatrixSolve(inv_arg, right)
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
matinv_opt = ReplaceOptim(_matinv_predicate, _matinv_transform)
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
logaddexp_opt = ReplaceOptim(log(exp(_v)+exp(_w)), logaddexp(_v, _w))
|
| 350 |
+
logaddexp2_opt = ReplaceOptim(log(Pow(2, _v)+Pow(2, _w)), logaddexp2(_v, _w)*log(2))
|
| 351 |
+
|
| 352 |
+
# Collections of optimizations:
|
| 353 |
+
optims_c99 = (expm1_opt, log1p_opt, exp2_opt, log2_opt, log2const_opt)
|
| 354 |
+
|
| 355 |
+
optims_numpy = optims_c99 + (logaddexp_opt, logaddexp2_opt,) + sinc_opts
|
| 356 |
+
|
| 357 |
+
optims_scipy = (cosm1_opt, powm1_opt)
|
pllava/lib/python3.10/site-packages/sympy/codegen/scipy_nodes.py
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.function import Add, ArgumentIndexError, Function
|
| 2 |
+
from sympy.core.power import Pow
|
| 3 |
+
from sympy.core.singleton import S
|
| 4 |
+
from sympy.functions.elementary.exponential import log
|
| 5 |
+
from sympy.functions.elementary.trigonometric import cos, sin
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def _cosm1(x, *, evaluate=True):
|
| 9 |
+
return Add(cos(x, evaluate=evaluate), -S.One, evaluate=evaluate)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class cosm1(Function):
|
| 13 |
+
""" Minus one plus cosine of x, i.e. cos(x) - 1. For use when x is close to zero.
|
| 14 |
+
|
| 15 |
+
Helper class for use with e.g. scipy.special.cosm1
|
| 16 |
+
See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.cosm1.html
|
| 17 |
+
"""
|
| 18 |
+
nargs = 1
|
| 19 |
+
|
| 20 |
+
def fdiff(self, argindex=1):
|
| 21 |
+
"""
|
| 22 |
+
Returns the first derivative of this function.
|
| 23 |
+
"""
|
| 24 |
+
if argindex == 1:
|
| 25 |
+
return -sin(*self.args)
|
| 26 |
+
else:
|
| 27 |
+
raise ArgumentIndexError(self, argindex)
|
| 28 |
+
|
| 29 |
+
def _eval_rewrite_as_cos(self, x, **kwargs):
|
| 30 |
+
return _cosm1(x)
|
| 31 |
+
|
| 32 |
+
def _eval_evalf(self, *args, **kwargs):
|
| 33 |
+
return self.rewrite(cos).evalf(*args, **kwargs)
|
| 34 |
+
|
| 35 |
+
def _eval_simplify(self, **kwargs):
|
| 36 |
+
x, = self.args
|
| 37 |
+
candidate = _cosm1(x.simplify(**kwargs))
|
| 38 |
+
if candidate != _cosm1(x, evaluate=False):
|
| 39 |
+
return candidate
|
| 40 |
+
else:
|
| 41 |
+
return cosm1(x)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _powm1(x, y, *, evaluate=True):
|
| 45 |
+
return Add(Pow(x, y, evaluate=evaluate), -S.One, evaluate=evaluate)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class powm1(Function):
|
| 49 |
+
""" Minus one plus x to the power of y, i.e. x**y - 1. For use when x is close to one or y is close to zero.
|
| 50 |
+
|
| 51 |
+
Helper class for use with e.g. scipy.special.powm1
|
| 52 |
+
See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.powm1.html
|
| 53 |
+
"""
|
| 54 |
+
nargs = 2
|
| 55 |
+
|
| 56 |
+
def fdiff(self, argindex=1):
|
| 57 |
+
"""
|
| 58 |
+
Returns the first derivative of this function.
|
| 59 |
+
"""
|
| 60 |
+
if argindex == 1:
|
| 61 |
+
return Pow(self.args[0], self.args[1])*self.args[1]/self.args[0]
|
| 62 |
+
elif argindex == 2:
|
| 63 |
+
return log(self.args[0])*Pow(*self.args)
|
| 64 |
+
else:
|
| 65 |
+
raise ArgumentIndexError(self, argindex)
|
| 66 |
+
|
| 67 |
+
def _eval_rewrite_as_Pow(self, x, y, **kwargs):
|
| 68 |
+
return _powm1(x, y)
|
| 69 |
+
|
| 70 |
+
def _eval_evalf(self, *args, **kwargs):
|
| 71 |
+
return self.rewrite(Pow).evalf(*args, **kwargs)
|
| 72 |
+
|
| 73 |
+
def _eval_simplify(self, **kwargs):
|
| 74 |
+
x, y = self.args
|
| 75 |
+
candidate = _powm1(x.simplify(**kwargs), y.simplify(**kwargs))
|
| 76 |
+
if candidate != _powm1(x, y, evaluate=False):
|
| 77 |
+
return candidate
|
| 78 |
+
else:
|
| 79 |
+
return powm1(x, y)
|
pllava/lib/python3.10/site-packages/sympy/codegen/tests/__init__.py
ADDED
|
File without changes
|
pllava/lib/python3.10/site-packages/sympy/codegen/tests/__pycache__/test_abstract_nodes.cpython-310.pyc
ADDED
|
Binary file (857 Bytes). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/codegen/tests/__pycache__/test_approximations.cpython-310.pyc
ADDED
|
Binary file (2.09 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/codegen/tests/__pycache__/test_ast.cpython-310.pyc
ADDED
|
Binary file (22.6 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/codegen/tests/__pycache__/test_cxxnodes.cpython-310.pyc
ADDED
|
Binary file (651 Bytes). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/codegen/tests/__pycache__/test_matrix_nodes.cpython-310.pyc
ADDED
|
Binary file (2.47 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/codegen/tests/__pycache__/test_numpy_nodes.cpython-310.pyc
ADDED
|
Binary file (1.81 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/codegen/tests/__pycache__/test_pyutils.cpython-310.pyc
ADDED
|
Binary file (560 Bytes). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/codegen/tests/__pycache__/test_rewriting.cpython-310.pyc
ADDED
|
Binary file (14.8 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/codegen/tests/__pycache__/test_scipy_nodes.cpython-310.pyc
ADDED
|
Binary file (1.67 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/codegen/tests/test_abstract_nodes.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.symbol import symbols
|
| 2 |
+
from sympy.codegen.abstract_nodes import List
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def test_List():
|
| 6 |
+
l = List(2, 3, 4)
|
| 7 |
+
assert l == List(2, 3, 4)
|
| 8 |
+
assert str(l) == "[2, 3, 4]"
|
| 9 |
+
x, y, z = symbols('x y z')
|
| 10 |
+
l = List(x**2,y**3,z**4)
|
| 11 |
+
# contrary to python's built-in list, we can call e.g. "replace" on List.
|
| 12 |
+
m = l.replace(lambda arg: arg.is_Pow and arg.exp>2, lambda p: p.base-p.exp)
|
| 13 |
+
assert m == [x**2, y-3, z-4]
|
| 14 |
+
hash(m)
|
pllava/lib/python3.10/site-packages/sympy/codegen/tests/test_algorithms.py
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import tempfile
|
| 2 |
+
from sympy import log, Min, Max, sqrt
|
| 3 |
+
from sympy.core.numbers import Float
|
| 4 |
+
from sympy.core.symbol import Symbol, symbols
|
| 5 |
+
from sympy.functions.elementary.trigonometric import cos
|
| 6 |
+
from sympy.codegen.ast import Assignment, Raise, RuntimeError_, QuotedString
|
| 7 |
+
from sympy.codegen.algorithms import newtons_method, newtons_method_function
|
| 8 |
+
from sympy.codegen.cfunctions import expm1
|
| 9 |
+
from sympy.codegen.fnodes import bind_C
|
| 10 |
+
from sympy.codegen.futils import render_as_module as f_module
|
| 11 |
+
from sympy.codegen.pyutils import render_as_module as py_module
|
| 12 |
+
from sympy.external import import_module
|
| 13 |
+
from sympy.printing.codeprinter import ccode
|
| 14 |
+
from sympy.utilities._compilation import compile_link_import_strings, has_c, has_fortran
|
| 15 |
+
from sympy.utilities._compilation.util import may_xfail
|
| 16 |
+
from sympy.testing.pytest import skip, raises
|
| 17 |
+
|
| 18 |
+
cython = import_module('cython')
|
| 19 |
+
wurlitzer = import_module('wurlitzer')
|
| 20 |
+
|
| 21 |
+
def test_newtons_method():
|
| 22 |
+
x, dx, atol = symbols('x dx atol')
|
| 23 |
+
expr = cos(x) - x**3
|
| 24 |
+
algo = newtons_method(expr, x, atol, dx)
|
| 25 |
+
assert algo.has(Assignment(dx, -expr/expr.diff(x)))
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@may_xfail
|
| 29 |
+
def test_newtons_method_function__ccode():
|
| 30 |
+
x = Symbol('x', real=True)
|
| 31 |
+
expr = cos(x) - x**3
|
| 32 |
+
func = newtons_method_function(expr, x)
|
| 33 |
+
|
| 34 |
+
if not cython:
|
| 35 |
+
skip("cython not installed.")
|
| 36 |
+
if not has_c():
|
| 37 |
+
skip("No C compiler found.")
|
| 38 |
+
|
| 39 |
+
compile_kw = {"std": 'c99'}
|
| 40 |
+
with tempfile.TemporaryDirectory() as folder:
|
| 41 |
+
mod, info = compile_link_import_strings([
|
| 42 |
+
('newton.c', ('#include <math.h>\n'
|
| 43 |
+
'#include <stdio.h>\n') + ccode(func)),
|
| 44 |
+
('_newton.pyx', ("#cython: language_level={}\n".format("3") +
|
| 45 |
+
"cdef extern double newton(double)\n"
|
| 46 |
+
"def py_newton(x):\n"
|
| 47 |
+
" return newton(x)\n"))
|
| 48 |
+
], build_dir=folder, compile_kwargs=compile_kw)
|
| 49 |
+
assert abs(mod.py_newton(0.5) - 0.865474033102) < 1e-12
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@may_xfail
|
| 53 |
+
def test_newtons_method_function__fcode():
|
| 54 |
+
x = Symbol('x', real=True)
|
| 55 |
+
expr = cos(x) - x**3
|
| 56 |
+
func = newtons_method_function(expr, x, attrs=[bind_C(name='newton')])
|
| 57 |
+
|
| 58 |
+
if not cython:
|
| 59 |
+
skip("cython not installed.")
|
| 60 |
+
if not has_fortran():
|
| 61 |
+
skip("No Fortran compiler found.")
|
| 62 |
+
|
| 63 |
+
f_mod = f_module([func], 'mod_newton')
|
| 64 |
+
with tempfile.TemporaryDirectory() as folder:
|
| 65 |
+
mod, info = compile_link_import_strings([
|
| 66 |
+
('newton.f90', f_mod),
|
| 67 |
+
('_newton.pyx', ("#cython: language_level={}\n".format("3") +
|
| 68 |
+
"cdef extern double newton(double*)\n"
|
| 69 |
+
"def py_newton(double x):\n"
|
| 70 |
+
" return newton(&x)\n"))
|
| 71 |
+
], build_dir=folder)
|
| 72 |
+
assert abs(mod.py_newton(0.5) - 0.865474033102) < 1e-12
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def test_newtons_method_function__pycode():
|
| 76 |
+
x = Symbol('x', real=True)
|
| 77 |
+
expr = cos(x) - x**3
|
| 78 |
+
func = newtons_method_function(expr, x)
|
| 79 |
+
py_mod = py_module(func)
|
| 80 |
+
namespace = {}
|
| 81 |
+
exec(py_mod, namespace, namespace)
|
| 82 |
+
res = eval('newton(0.5)', namespace)
|
| 83 |
+
assert abs(res - 0.865474033102) < 1e-12
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
@may_xfail
|
| 87 |
+
def test_newtons_method_function__ccode_parameters():
|
| 88 |
+
args = x, A, k, p = symbols('x A k p')
|
| 89 |
+
expr = A*cos(k*x) - p*x**3
|
| 90 |
+
raises(ValueError, lambda: newtons_method_function(expr, x))
|
| 91 |
+
use_wurlitzer = wurlitzer
|
| 92 |
+
|
| 93 |
+
func = newtons_method_function(expr, x, args, debug=use_wurlitzer)
|
| 94 |
+
|
| 95 |
+
if not has_c():
|
| 96 |
+
skip("No C compiler found.")
|
| 97 |
+
if not cython:
|
| 98 |
+
skip("cython not installed.")
|
| 99 |
+
|
| 100 |
+
compile_kw = {"std": 'c99'}
|
| 101 |
+
with tempfile.TemporaryDirectory() as folder:
|
| 102 |
+
mod, info = compile_link_import_strings([
|
| 103 |
+
('newton_par.c', ('#include <math.h>\n'
|
| 104 |
+
'#include <stdio.h>\n') + ccode(func)),
|
| 105 |
+
('_newton_par.pyx', ("#cython: language_level={}\n".format("3") +
|
| 106 |
+
"cdef extern double newton(double, double, double, double)\n"
|
| 107 |
+
"def py_newton(x, A=1, k=1, p=1):\n"
|
| 108 |
+
" return newton(x, A, k, p)\n"))
|
| 109 |
+
], compile_kwargs=compile_kw, build_dir=folder)
|
| 110 |
+
|
| 111 |
+
if use_wurlitzer:
|
| 112 |
+
with wurlitzer.pipes() as (out, err):
|
| 113 |
+
result = mod.py_newton(0.5)
|
| 114 |
+
else:
|
| 115 |
+
result = mod.py_newton(0.5)
|
| 116 |
+
|
| 117 |
+
assert abs(result - 0.865474033102) < 1e-12
|
| 118 |
+
|
| 119 |
+
if not use_wurlitzer:
|
| 120 |
+
skip("C-level output only tested when package 'wurlitzer' is available.")
|
| 121 |
+
|
| 122 |
+
out, err = out.read(), err.read()
|
| 123 |
+
assert err == ''
|
| 124 |
+
assert out == """\
|
| 125 |
+
x= 0.5
|
| 126 |
+
x= 1.1121 d_x= 0.61214
|
| 127 |
+
x= 0.90967 d_x= -0.20247
|
| 128 |
+
x= 0.86726 d_x= -0.042409
|
| 129 |
+
x= 0.86548 d_x= -0.0017867
|
| 130 |
+
x= 0.86547 d_x= -3.1022e-06
|
| 131 |
+
x= 0.86547 d_x= -9.3421e-12
|
| 132 |
+
x= 0.86547 d_x= 3.6902e-17
|
| 133 |
+
""" # try to run tests with LC_ALL=C if this assertion fails
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def test_newtons_method_function__rtol_cse_nan():
|
| 137 |
+
a, b, c, N_geo, N_tot = symbols('a b c N_geo N_tot', real=True, nonnegative=True)
|
| 138 |
+
i = Symbol('i', integer=True, nonnegative=True)
|
| 139 |
+
N_ari = N_tot - N_geo - 1
|
| 140 |
+
delta_ari = (c-b)/N_ari
|
| 141 |
+
ln_delta_geo = log(b) + log(-expm1((log(a)-log(b))/N_geo))
|
| 142 |
+
eqb_log = ln_delta_geo - log(delta_ari)
|
| 143 |
+
|
| 144 |
+
def _clamp(low, expr, high):
|
| 145 |
+
return Min(Max(low, expr), high)
|
| 146 |
+
|
| 147 |
+
meth_kw = {
|
| 148 |
+
'clamped_newton': {'delta_fn': lambda e, x: _clamp(
|
| 149 |
+
(sqrt(a*x)-x)*0.99,
|
| 150 |
+
-e/e.diff(x),
|
| 151 |
+
(sqrt(c*x)-x)*0.99
|
| 152 |
+
)},
|
| 153 |
+
'halley': {'delta_fn': lambda e, x: (-2*(e*e.diff(x))/(2*e.diff(x)**2 - e*e.diff(x, 2)))},
|
| 154 |
+
'halley_alt': {'delta_fn': lambda e, x: (-e/e.diff(x)/(1-e/e.diff(x)*e.diff(x,2)/2/e.diff(x)))},
|
| 155 |
+
}
|
| 156 |
+
args = eqb_log, b
|
| 157 |
+
for use_cse in [False, True]:
|
| 158 |
+
kwargs = {
|
| 159 |
+
'params': (b, a, c, N_geo, N_tot), 'itermax': 60, 'debug': True, 'cse': use_cse,
|
| 160 |
+
'counter': i, 'atol': 1e-100, 'rtol': 2e-16, 'bounds': (a,c),
|
| 161 |
+
'handle_nan': Raise(RuntimeError_(QuotedString("encountered NaN.")))
|
| 162 |
+
}
|
| 163 |
+
func = {k: newtons_method_function(*args, func_name=f"{k}_b", **dict(kwargs, **kw)) for k, kw in meth_kw.items()}
|
| 164 |
+
py_mod = {k: py_module(v) for k, v in func.items()}
|
| 165 |
+
namespace = {}
|
| 166 |
+
root_find_b = {}
|
| 167 |
+
for k, v in py_mod.items():
|
| 168 |
+
ns = namespace[k] = {}
|
| 169 |
+
exec(v, ns, ns)
|
| 170 |
+
root_find_b[k] = ns[f'{k}_b']
|
| 171 |
+
ref = Float('13.2261515064168768938151923226496')
|
| 172 |
+
reftol = {'clamped_newton': 2e-16, 'halley': 2e-16, 'halley_alt': 3e-16}
|
| 173 |
+
guess = 4.0
|
| 174 |
+
for meth, func in root_find_b.items():
|
| 175 |
+
result = func(guess, 1e-2, 1e2, 50, 100)
|
| 176 |
+
req = ref*reftol[meth]
|
| 177 |
+
if use_cse:
|
| 178 |
+
req *= 2
|
| 179 |
+
assert abs(result - ref) < req
|
pllava/lib/python3.10/site-packages/sympy/codegen/tests/test_applications.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# This file contains tests that exercise multiple AST nodes
|
| 2 |
+
|
| 3 |
+
import tempfile
|
| 4 |
+
|
| 5 |
+
from sympy.external import import_module
|
| 6 |
+
from sympy.printing.codeprinter import ccode
|
| 7 |
+
from sympy.utilities._compilation import compile_link_import_strings, has_c
|
| 8 |
+
from sympy.utilities._compilation.util import may_xfail
|
| 9 |
+
from sympy.testing.pytest import skip
|
| 10 |
+
from sympy.codegen.ast import (
|
| 11 |
+
FunctionDefinition, FunctionPrototype, Variable, Pointer, real, Assignment,
|
| 12 |
+
integer, CodeBlock, While
|
| 13 |
+
)
|
| 14 |
+
from sympy.codegen.cnodes import void, PreIncrement
|
| 15 |
+
from sympy.codegen.cutils import render_as_source_file
|
| 16 |
+
|
| 17 |
+
cython = import_module('cython')
|
| 18 |
+
np = import_module('numpy')
|
| 19 |
+
|
| 20 |
+
def _mk_func1():
|
| 21 |
+
declars = n, inp, out = Variable('n', integer), Pointer('inp', real), Pointer('out', real)
|
| 22 |
+
i = Variable('i', integer)
|
| 23 |
+
whl = While(i<n, [Assignment(out[i], inp[i]), PreIncrement(i)])
|
| 24 |
+
body = CodeBlock(i.as_Declaration(value=0), whl)
|
| 25 |
+
return FunctionDefinition(void, 'our_test_function', declars, body)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _render_compile_import(funcdef, build_dir):
|
| 29 |
+
code_str = render_as_source_file(funcdef, settings={"contract": False})
|
| 30 |
+
declar = ccode(FunctionPrototype.from_FunctionDefinition(funcdef))
|
| 31 |
+
return compile_link_import_strings([
|
| 32 |
+
('our_test_func.c', code_str),
|
| 33 |
+
('_our_test_func.pyx', ("#cython: language_level={}\n".format("3") +
|
| 34 |
+
"cdef extern {declar}\n"
|
| 35 |
+
"def _{fname}({typ}[:] inp, {typ}[:] out):\n"
|
| 36 |
+
" {fname}(inp.size, &inp[0], &out[0])").format(
|
| 37 |
+
declar=declar, fname=funcdef.name, typ='double'
|
| 38 |
+
))
|
| 39 |
+
], build_dir=build_dir)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@may_xfail
|
| 43 |
+
def test_copying_function():
|
| 44 |
+
if not np:
|
| 45 |
+
skip("numpy not installed.")
|
| 46 |
+
if not has_c():
|
| 47 |
+
skip("No C compiler found.")
|
| 48 |
+
if not cython:
|
| 49 |
+
skip("Cython not found.")
|
| 50 |
+
|
| 51 |
+
info = None
|
| 52 |
+
with tempfile.TemporaryDirectory() as folder:
|
| 53 |
+
mod, info = _render_compile_import(_mk_func1(), build_dir=folder)
|
| 54 |
+
inp = np.arange(10.0)
|
| 55 |
+
out = np.empty_like(inp)
|
| 56 |
+
mod._our_test_function(inp, out)
|
| 57 |
+
assert np.allclose(inp, out)
|
pllava/lib/python3.10/site-packages/sympy/codegen/tests/test_approximations.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
from sympy.core.symbol import symbols
|
| 3 |
+
from sympy.functions.elementary.exponential import exp
|
| 4 |
+
from sympy.codegen.rewriting import optimize
|
| 5 |
+
from sympy.codegen.approximations import SumApprox, SeriesApprox
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def test_SumApprox_trivial():
|
| 9 |
+
x = symbols('x')
|
| 10 |
+
expr1 = 1 + x
|
| 11 |
+
sum_approx = SumApprox(bounds={x: (-1e-20, 1e-20)}, reltol=1e-16)
|
| 12 |
+
apx1 = optimize(expr1, [sum_approx])
|
| 13 |
+
assert apx1 - 1 == 0
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def test_SumApprox_monotone_terms():
|
| 17 |
+
x, y, z = symbols('x y z')
|
| 18 |
+
expr1 = exp(z)*(x**2 + y**2 + 1)
|
| 19 |
+
bnds1 = {x: (0, 1e-3), y: (100, 1000)}
|
| 20 |
+
sum_approx_m2 = SumApprox(bounds=bnds1, reltol=1e-2)
|
| 21 |
+
sum_approx_m5 = SumApprox(bounds=bnds1, reltol=1e-5)
|
| 22 |
+
sum_approx_m11 = SumApprox(bounds=bnds1, reltol=1e-11)
|
| 23 |
+
assert (optimize(expr1, [sum_approx_m2])/exp(z) - (y**2)).simplify() == 0
|
| 24 |
+
assert (optimize(expr1, [sum_approx_m5])/exp(z) - (y**2 + 1)).simplify() == 0
|
| 25 |
+
assert (optimize(expr1, [sum_approx_m11])/exp(z) - (y**2 + 1 + x**2)).simplify() == 0
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def test_SeriesApprox_trivial():
|
| 29 |
+
x, z = symbols('x z')
|
| 30 |
+
for factor in [1, exp(z)]:
|
| 31 |
+
x = symbols('x')
|
| 32 |
+
expr1 = exp(x)*factor
|
| 33 |
+
bnds1 = {x: (-1, 1)}
|
| 34 |
+
series_approx_50 = SeriesApprox(bounds=bnds1, reltol=0.50)
|
| 35 |
+
series_approx_10 = SeriesApprox(bounds=bnds1, reltol=0.10)
|
| 36 |
+
series_approx_05 = SeriesApprox(bounds=bnds1, reltol=0.05)
|
| 37 |
+
c = (bnds1[x][1] + bnds1[x][0])/2 # 0.0
|
| 38 |
+
f0 = math.exp(c) # 1.0
|
| 39 |
+
|
| 40 |
+
ref_50 = f0 + x + x**2/2
|
| 41 |
+
ref_10 = f0 + x + x**2/2 + x**3/6
|
| 42 |
+
ref_05 = f0 + x + x**2/2 + x**3/6 + x**4/24
|
| 43 |
+
|
| 44 |
+
res_50 = optimize(expr1, [series_approx_50])
|
| 45 |
+
res_10 = optimize(expr1, [series_approx_10])
|
| 46 |
+
res_05 = optimize(expr1, [series_approx_05])
|
| 47 |
+
|
| 48 |
+
assert (res_50/factor - ref_50).simplify() == 0
|
| 49 |
+
assert (res_10/factor - ref_10).simplify() == 0
|
| 50 |
+
assert (res_05/factor - ref_05).simplify() == 0
|
| 51 |
+
|
| 52 |
+
max_ord3 = SeriesApprox(bounds=bnds1, reltol=0.05, max_order=3)
|
| 53 |
+
assert optimize(expr1, [max_ord3]) == expr1
|
pllava/lib/python3.10/site-packages/sympy/codegen/tests/test_ast.py
ADDED
|
@@ -0,0 +1,661 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
from sympy.core.containers import Tuple
|
| 3 |
+
from sympy.core.numbers import nan, oo, Float, Integer
|
| 4 |
+
from sympy.core.relational import Lt
|
| 5 |
+
from sympy.core.symbol import symbols, Symbol
|
| 6 |
+
from sympy.functions.elementary.trigonometric import sin
|
| 7 |
+
from sympy.matrices.dense import Matrix
|
| 8 |
+
from sympy.matrices.expressions.matexpr import MatrixSymbol
|
| 9 |
+
from sympy.sets.fancysets import Range
|
| 10 |
+
from sympy.tensor.indexed import Idx, IndexedBase
|
| 11 |
+
from sympy.testing.pytest import raises
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
from sympy.codegen.ast import (
|
| 15 |
+
Assignment, Attribute, aug_assign, CodeBlock, For, Type, Variable, Pointer, Declaration,
|
| 16 |
+
AddAugmentedAssignment, SubAugmentedAssignment, MulAugmentedAssignment,
|
| 17 |
+
DivAugmentedAssignment, ModAugmentedAssignment, value_const, pointer_const,
|
| 18 |
+
integer, real, complex_, int8, uint8, float16 as f16, float32 as f32,
|
| 19 |
+
float64 as f64, float80 as f80, float128 as f128, complex64 as c64, complex128 as c128,
|
| 20 |
+
While, Scope, String, Print, QuotedString, FunctionPrototype, FunctionDefinition, Return,
|
| 21 |
+
FunctionCall, untyped, IntBaseType, intc, Node, none, NoneToken, Token, Comment
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
x, y, z, t, x0, x1, x2, a, b = symbols("x, y, z, t, x0, x1, x2, a, b")
|
| 25 |
+
n = symbols("n", integer=True)
|
| 26 |
+
A = MatrixSymbol('A', 3, 1)
|
| 27 |
+
mat = Matrix([1, 2, 3])
|
| 28 |
+
B = IndexedBase('B')
|
| 29 |
+
i = Idx("i", n)
|
| 30 |
+
A22 = MatrixSymbol('A22',2,2)
|
| 31 |
+
B22 = MatrixSymbol('B22',2,2)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def test_Assignment():
|
| 35 |
+
# Here we just do things to show they don't error
|
| 36 |
+
Assignment(x, y)
|
| 37 |
+
Assignment(x, 0)
|
| 38 |
+
Assignment(A, mat)
|
| 39 |
+
Assignment(A[1,0], 0)
|
| 40 |
+
Assignment(A[1,0], x)
|
| 41 |
+
Assignment(B[i], x)
|
| 42 |
+
Assignment(B[i], 0)
|
| 43 |
+
a = Assignment(x, y)
|
| 44 |
+
assert a.func(*a.args) == a
|
| 45 |
+
assert a.op == ':='
|
| 46 |
+
# Here we test things to show that they error
|
| 47 |
+
# Matrix to scalar
|
| 48 |
+
raises(ValueError, lambda: Assignment(B[i], A))
|
| 49 |
+
raises(ValueError, lambda: Assignment(B[i], mat))
|
| 50 |
+
raises(ValueError, lambda: Assignment(x, mat))
|
| 51 |
+
raises(ValueError, lambda: Assignment(x, A))
|
| 52 |
+
raises(ValueError, lambda: Assignment(A[1,0], mat))
|
| 53 |
+
# Scalar to matrix
|
| 54 |
+
raises(ValueError, lambda: Assignment(A, x))
|
| 55 |
+
raises(ValueError, lambda: Assignment(A, 0))
|
| 56 |
+
# Non-atomic lhs
|
| 57 |
+
raises(TypeError, lambda: Assignment(mat, A))
|
| 58 |
+
raises(TypeError, lambda: Assignment(0, x))
|
| 59 |
+
raises(TypeError, lambda: Assignment(x*x, 1))
|
| 60 |
+
raises(TypeError, lambda: Assignment(A + A, mat))
|
| 61 |
+
raises(TypeError, lambda: Assignment(B, 0))
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def test_AugAssign():
|
| 65 |
+
# Here we just do things to show they don't error
|
| 66 |
+
aug_assign(x, '+', y)
|
| 67 |
+
aug_assign(x, '+', 0)
|
| 68 |
+
aug_assign(A, '+', mat)
|
| 69 |
+
aug_assign(A[1, 0], '+', 0)
|
| 70 |
+
aug_assign(A[1, 0], '+', x)
|
| 71 |
+
aug_assign(B[i], '+', x)
|
| 72 |
+
aug_assign(B[i], '+', 0)
|
| 73 |
+
|
| 74 |
+
# Check creation via aug_assign vs constructor
|
| 75 |
+
for binop, cls in [
|
| 76 |
+
('+', AddAugmentedAssignment),
|
| 77 |
+
('-', SubAugmentedAssignment),
|
| 78 |
+
('*', MulAugmentedAssignment),
|
| 79 |
+
('/', DivAugmentedAssignment),
|
| 80 |
+
('%', ModAugmentedAssignment),
|
| 81 |
+
]:
|
| 82 |
+
a = aug_assign(x, binop, y)
|
| 83 |
+
b = cls(x, y)
|
| 84 |
+
assert a.func(*a.args) == a == b
|
| 85 |
+
assert a.binop == binop
|
| 86 |
+
assert a.op == binop + '='
|
| 87 |
+
|
| 88 |
+
# Here we test things to show that they error
|
| 89 |
+
# Matrix to scalar
|
| 90 |
+
raises(ValueError, lambda: aug_assign(B[i], '+', A))
|
| 91 |
+
raises(ValueError, lambda: aug_assign(B[i], '+', mat))
|
| 92 |
+
raises(ValueError, lambda: aug_assign(x, '+', mat))
|
| 93 |
+
raises(ValueError, lambda: aug_assign(x, '+', A))
|
| 94 |
+
raises(ValueError, lambda: aug_assign(A[1, 0], '+', mat))
|
| 95 |
+
# Scalar to matrix
|
| 96 |
+
raises(ValueError, lambda: aug_assign(A, '+', x))
|
| 97 |
+
raises(ValueError, lambda: aug_assign(A, '+', 0))
|
| 98 |
+
# Non-atomic lhs
|
| 99 |
+
raises(TypeError, lambda: aug_assign(mat, '+', A))
|
| 100 |
+
raises(TypeError, lambda: aug_assign(0, '+', x))
|
| 101 |
+
raises(TypeError, lambda: aug_assign(x * x, '+', 1))
|
| 102 |
+
raises(TypeError, lambda: aug_assign(A + A, '+', mat))
|
| 103 |
+
raises(TypeError, lambda: aug_assign(B, '+', 0))
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def test_Assignment_printing():
|
| 107 |
+
assignment_classes = [
|
| 108 |
+
Assignment,
|
| 109 |
+
AddAugmentedAssignment,
|
| 110 |
+
SubAugmentedAssignment,
|
| 111 |
+
MulAugmentedAssignment,
|
| 112 |
+
DivAugmentedAssignment,
|
| 113 |
+
ModAugmentedAssignment,
|
| 114 |
+
]
|
| 115 |
+
pairs = [
|
| 116 |
+
(x, 2 * y + 2),
|
| 117 |
+
(B[i], x),
|
| 118 |
+
(A22, B22),
|
| 119 |
+
(A[0, 0], x),
|
| 120 |
+
]
|
| 121 |
+
|
| 122 |
+
for cls in assignment_classes:
|
| 123 |
+
for lhs, rhs in pairs:
|
| 124 |
+
a = cls(lhs, rhs)
|
| 125 |
+
assert repr(a) == '%s(%s, %s)' % (cls.__name__, repr(lhs), repr(rhs))
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def test_CodeBlock():
|
| 129 |
+
c = CodeBlock(Assignment(x, 1), Assignment(y, x + 1))
|
| 130 |
+
assert c.func(*c.args) == c
|
| 131 |
+
|
| 132 |
+
assert c.left_hand_sides == Tuple(x, y)
|
| 133 |
+
assert c.right_hand_sides == Tuple(1, x + 1)
|
| 134 |
+
|
| 135 |
+
def test_CodeBlock_topological_sort():
|
| 136 |
+
assignments = [
|
| 137 |
+
Assignment(x, y + z),
|
| 138 |
+
Assignment(z, 1),
|
| 139 |
+
Assignment(t, x),
|
| 140 |
+
Assignment(y, 2),
|
| 141 |
+
]
|
| 142 |
+
|
| 143 |
+
ordered_assignments = [
|
| 144 |
+
# Note that the unrelated z=1 and y=2 are kept in that order
|
| 145 |
+
Assignment(z, 1),
|
| 146 |
+
Assignment(y, 2),
|
| 147 |
+
Assignment(x, y + z),
|
| 148 |
+
Assignment(t, x),
|
| 149 |
+
]
|
| 150 |
+
c1 = CodeBlock.topological_sort(assignments)
|
| 151 |
+
assert c1 == CodeBlock(*ordered_assignments)
|
| 152 |
+
|
| 153 |
+
# Cycle
|
| 154 |
+
invalid_assignments = [
|
| 155 |
+
Assignment(x, y + z),
|
| 156 |
+
Assignment(z, 1),
|
| 157 |
+
Assignment(y, x),
|
| 158 |
+
Assignment(y, 2),
|
| 159 |
+
]
|
| 160 |
+
|
| 161 |
+
raises(ValueError, lambda: CodeBlock.topological_sort(invalid_assignments))
|
| 162 |
+
|
| 163 |
+
# Free symbols
|
| 164 |
+
free_assignments = [
|
| 165 |
+
Assignment(x, y + z),
|
| 166 |
+
Assignment(z, a * b),
|
| 167 |
+
Assignment(t, x),
|
| 168 |
+
Assignment(y, b + 3),
|
| 169 |
+
]
|
| 170 |
+
|
| 171 |
+
free_assignments_ordered = [
|
| 172 |
+
Assignment(z, a * b),
|
| 173 |
+
Assignment(y, b + 3),
|
| 174 |
+
Assignment(x, y + z),
|
| 175 |
+
Assignment(t, x),
|
| 176 |
+
]
|
| 177 |
+
|
| 178 |
+
c2 = CodeBlock.topological_sort(free_assignments)
|
| 179 |
+
assert c2 == CodeBlock(*free_assignments_ordered)
|
| 180 |
+
|
| 181 |
+
def test_CodeBlock_free_symbols():
|
| 182 |
+
c1 = CodeBlock(
|
| 183 |
+
Assignment(x, y + z),
|
| 184 |
+
Assignment(z, 1),
|
| 185 |
+
Assignment(t, x),
|
| 186 |
+
Assignment(y, 2),
|
| 187 |
+
)
|
| 188 |
+
assert c1.free_symbols == set()
|
| 189 |
+
|
| 190 |
+
c2 = CodeBlock(
|
| 191 |
+
Assignment(x, y + z),
|
| 192 |
+
Assignment(z, a * b),
|
| 193 |
+
Assignment(t, x),
|
| 194 |
+
Assignment(y, b + 3),
|
| 195 |
+
)
|
| 196 |
+
assert c2.free_symbols == {a, b}
|
| 197 |
+
|
| 198 |
+
def test_CodeBlock_cse():
|
| 199 |
+
c1 = CodeBlock(
|
| 200 |
+
Assignment(y, 1),
|
| 201 |
+
Assignment(x, sin(y)),
|
| 202 |
+
Assignment(z, sin(y)),
|
| 203 |
+
Assignment(t, x*z),
|
| 204 |
+
)
|
| 205 |
+
assert c1.cse() == CodeBlock(
|
| 206 |
+
Assignment(y, 1),
|
| 207 |
+
Assignment(x0, sin(y)),
|
| 208 |
+
Assignment(x, x0),
|
| 209 |
+
Assignment(z, x0),
|
| 210 |
+
Assignment(t, x*z),
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
# Multiple assignments to same symbol not supported
|
| 214 |
+
raises(NotImplementedError, lambda: CodeBlock(
|
| 215 |
+
Assignment(x, 1),
|
| 216 |
+
Assignment(y, 1), Assignment(y, 2)
|
| 217 |
+
).cse())
|
| 218 |
+
|
| 219 |
+
# Check auto-generated symbols do not collide with existing ones
|
| 220 |
+
c2 = CodeBlock(
|
| 221 |
+
Assignment(x0, sin(y) + 1),
|
| 222 |
+
Assignment(x1, 2 * sin(y)),
|
| 223 |
+
Assignment(z, x * y),
|
| 224 |
+
)
|
| 225 |
+
assert c2.cse() == CodeBlock(
|
| 226 |
+
Assignment(x2, sin(y)),
|
| 227 |
+
Assignment(x0, x2 + 1),
|
| 228 |
+
Assignment(x1, 2 * x2),
|
| 229 |
+
Assignment(z, x * y),
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def test_CodeBlock_cse__issue_14118():
|
| 234 |
+
# see https://github.com/sympy/sympy/issues/14118
|
| 235 |
+
c = CodeBlock(
|
| 236 |
+
Assignment(A22, Matrix([[x, sin(y)],[3, 4]])),
|
| 237 |
+
Assignment(B22, Matrix([[sin(y), 2*sin(y)], [sin(y)**2, 7]]))
|
| 238 |
+
)
|
| 239 |
+
assert c.cse() == CodeBlock(
|
| 240 |
+
Assignment(x0, sin(y)),
|
| 241 |
+
Assignment(A22, Matrix([[x, x0],[3, 4]])),
|
| 242 |
+
Assignment(B22, Matrix([[x0, 2*x0], [x0**2, 7]]))
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
def test_For():
|
| 246 |
+
f = For(n, Range(0, 3), (Assignment(A[n, 0], x + n), aug_assign(x, '+', y)))
|
| 247 |
+
f = For(n, (1, 2, 3, 4, 5), (Assignment(A[n, 0], x + n),))
|
| 248 |
+
assert f.func(*f.args) == f
|
| 249 |
+
raises(TypeError, lambda: For(n, x, (x + y,)))
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def test_none():
|
| 253 |
+
assert none.is_Atom
|
| 254 |
+
assert none == none
|
| 255 |
+
class Foo(Token):
|
| 256 |
+
pass
|
| 257 |
+
foo = Foo()
|
| 258 |
+
assert foo != none
|
| 259 |
+
assert none == None
|
| 260 |
+
assert none == NoneToken()
|
| 261 |
+
assert none.func(*none.args) == none
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def test_String():
|
| 265 |
+
st = String('foobar')
|
| 266 |
+
assert st.is_Atom
|
| 267 |
+
assert st == String('foobar')
|
| 268 |
+
assert st.text == 'foobar'
|
| 269 |
+
assert st.func(**st.kwargs()) == st
|
| 270 |
+
assert st.func(*st.args) == st
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
class Signifier(String):
|
| 274 |
+
pass
|
| 275 |
+
|
| 276 |
+
si = Signifier('foobar')
|
| 277 |
+
assert si != st
|
| 278 |
+
assert si.text == st.text
|
| 279 |
+
s = String('foo')
|
| 280 |
+
assert str(s) == 'foo'
|
| 281 |
+
assert repr(s) == "String('foo')"
|
| 282 |
+
|
| 283 |
+
def test_Comment():
|
| 284 |
+
c = Comment('foobar')
|
| 285 |
+
assert c.text == 'foobar'
|
| 286 |
+
assert str(c) == 'foobar'
|
| 287 |
+
|
| 288 |
+
def test_Node():
|
| 289 |
+
n = Node()
|
| 290 |
+
assert n == Node()
|
| 291 |
+
assert n.func(*n.args) == n
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
def test_Type():
|
| 295 |
+
t = Type('MyType')
|
| 296 |
+
assert len(t.args) == 1
|
| 297 |
+
assert t.name == String('MyType')
|
| 298 |
+
assert str(t) == 'MyType'
|
| 299 |
+
assert repr(t) == "Type(String('MyType'))"
|
| 300 |
+
assert Type(t) == t
|
| 301 |
+
assert t.func(*t.args) == t
|
| 302 |
+
t1 = Type('t1')
|
| 303 |
+
t2 = Type('t2')
|
| 304 |
+
assert t1 != t2
|
| 305 |
+
assert t1 == t1 and t2 == t2
|
| 306 |
+
t1b = Type('t1')
|
| 307 |
+
assert t1 == t1b
|
| 308 |
+
assert t2 != t1b
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
def test_Type__from_expr():
|
| 312 |
+
assert Type.from_expr(i) == integer
|
| 313 |
+
u = symbols('u', real=True)
|
| 314 |
+
assert Type.from_expr(u) == real
|
| 315 |
+
assert Type.from_expr(n) == integer
|
| 316 |
+
assert Type.from_expr(3) == integer
|
| 317 |
+
assert Type.from_expr(3.0) == real
|
| 318 |
+
assert Type.from_expr(3+1j) == complex_
|
| 319 |
+
raises(ValueError, lambda: Type.from_expr(sum))
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def test_Type__cast_check__integers():
|
| 323 |
+
# Rounding
|
| 324 |
+
raises(ValueError, lambda: integer.cast_check(3.5))
|
| 325 |
+
assert integer.cast_check('3') == 3
|
| 326 |
+
assert integer.cast_check(Float('3.0000000000000000000')) == 3
|
| 327 |
+
assert integer.cast_check(Float('3.0000000000000000001')) == 3 # unintuitive maybe?
|
| 328 |
+
|
| 329 |
+
# Range
|
| 330 |
+
assert int8.cast_check(127.0) == 127
|
| 331 |
+
raises(ValueError, lambda: int8.cast_check(128))
|
| 332 |
+
assert int8.cast_check(-128) == -128
|
| 333 |
+
raises(ValueError, lambda: int8.cast_check(-129))
|
| 334 |
+
|
| 335 |
+
assert uint8.cast_check(0) == 0
|
| 336 |
+
assert uint8.cast_check(128) == 128
|
| 337 |
+
raises(ValueError, lambda: uint8.cast_check(256.0))
|
| 338 |
+
raises(ValueError, lambda: uint8.cast_check(-1))
|
| 339 |
+
|
| 340 |
+
def test_Attribute():
|
| 341 |
+
noexcept = Attribute('noexcept')
|
| 342 |
+
assert noexcept == Attribute('noexcept')
|
| 343 |
+
alignas16 = Attribute('alignas', [16])
|
| 344 |
+
alignas32 = Attribute('alignas', [32])
|
| 345 |
+
assert alignas16 != alignas32
|
| 346 |
+
assert alignas16.func(*alignas16.args) == alignas16
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
def test_Variable():
|
| 350 |
+
v = Variable(x, type=real)
|
| 351 |
+
assert v == Variable(v)
|
| 352 |
+
assert v == Variable('x', type=real)
|
| 353 |
+
assert v.symbol == x
|
| 354 |
+
assert v.type == real
|
| 355 |
+
assert value_const not in v.attrs
|
| 356 |
+
assert v.func(*v.args) == v
|
| 357 |
+
assert str(v) == 'Variable(x, type=real)'
|
| 358 |
+
|
| 359 |
+
w = Variable(y, f32, attrs={value_const})
|
| 360 |
+
assert w.symbol == y
|
| 361 |
+
assert w.type == f32
|
| 362 |
+
assert value_const in w.attrs
|
| 363 |
+
assert w.func(*w.args) == w
|
| 364 |
+
|
| 365 |
+
v_n = Variable(n, type=Type.from_expr(n))
|
| 366 |
+
assert v_n.type == integer
|
| 367 |
+
assert v_n.func(*v_n.args) == v_n
|
| 368 |
+
v_i = Variable(i, type=Type.from_expr(n))
|
| 369 |
+
assert v_i.type == integer
|
| 370 |
+
assert v_i != v_n
|
| 371 |
+
|
| 372 |
+
a_i = Variable.deduced(i)
|
| 373 |
+
assert a_i.type == integer
|
| 374 |
+
assert Variable.deduced(Symbol('x', real=True)).type == real
|
| 375 |
+
assert a_i.func(*a_i.args) == a_i
|
| 376 |
+
|
| 377 |
+
v_n2 = Variable.deduced(n, value=3.5, cast_check=False)
|
| 378 |
+
assert v_n2.func(*v_n2.args) == v_n2
|
| 379 |
+
assert abs(v_n2.value - 3.5) < 1e-15
|
| 380 |
+
raises(ValueError, lambda: Variable.deduced(n, value=3.5, cast_check=True))
|
| 381 |
+
|
| 382 |
+
v_n3 = Variable.deduced(n)
|
| 383 |
+
assert v_n3.type == integer
|
| 384 |
+
assert str(v_n3) == 'Variable(n, type=integer)'
|
| 385 |
+
assert Variable.deduced(z, value=3).type == integer
|
| 386 |
+
assert Variable.deduced(z, value=3.0).type == real
|
| 387 |
+
assert Variable.deduced(z, value=3.0+1j).type == complex_
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
def test_Pointer():
|
| 391 |
+
p = Pointer(x)
|
| 392 |
+
assert p.symbol == x
|
| 393 |
+
assert p.type == untyped
|
| 394 |
+
assert value_const not in p.attrs
|
| 395 |
+
assert pointer_const not in p.attrs
|
| 396 |
+
assert p.func(*p.args) == p
|
| 397 |
+
|
| 398 |
+
u = symbols('u', real=True)
|
| 399 |
+
pu = Pointer(u, type=Type.from_expr(u), attrs={value_const, pointer_const})
|
| 400 |
+
assert pu.symbol is u
|
| 401 |
+
assert pu.type == real
|
| 402 |
+
assert value_const in pu.attrs
|
| 403 |
+
assert pointer_const in pu.attrs
|
| 404 |
+
assert pu.func(*pu.args) == pu
|
| 405 |
+
|
| 406 |
+
i = symbols('i', integer=True)
|
| 407 |
+
deref = pu[i]
|
| 408 |
+
assert deref.indices == (i,)
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
def test_Declaration():
|
| 412 |
+
u = symbols('u', real=True)
|
| 413 |
+
vu = Variable(u, type=Type.from_expr(u))
|
| 414 |
+
assert Declaration(vu).variable.type == real
|
| 415 |
+
vn = Variable(n, type=Type.from_expr(n))
|
| 416 |
+
assert Declaration(vn).variable.type == integer
|
| 417 |
+
|
| 418 |
+
# PR 19107, does not allow comparison between expressions and Basic
|
| 419 |
+
# lt = StrictLessThan(vu, vn)
|
| 420 |
+
# assert isinstance(lt, StrictLessThan)
|
| 421 |
+
|
| 422 |
+
vuc = Variable(u, Type.from_expr(u), value=3.0, attrs={value_const})
|
| 423 |
+
assert value_const in vuc.attrs
|
| 424 |
+
assert pointer_const not in vuc.attrs
|
| 425 |
+
decl = Declaration(vuc)
|
| 426 |
+
assert decl.variable == vuc
|
| 427 |
+
assert isinstance(decl.variable.value, Float)
|
| 428 |
+
assert decl.variable.value == 3.0
|
| 429 |
+
assert decl.func(*decl.args) == decl
|
| 430 |
+
assert vuc.as_Declaration() == decl
|
| 431 |
+
assert vuc.as_Declaration(value=None, attrs=None) == Declaration(vu)
|
| 432 |
+
|
| 433 |
+
vy = Variable(y, type=integer, value=3)
|
| 434 |
+
decl2 = Declaration(vy)
|
| 435 |
+
assert decl2.variable == vy
|
| 436 |
+
assert decl2.variable.value == Integer(3)
|
| 437 |
+
|
| 438 |
+
vi = Variable(i, type=Type.from_expr(i), value=3.0)
|
| 439 |
+
decl3 = Declaration(vi)
|
| 440 |
+
assert decl3.variable.type == integer
|
| 441 |
+
assert decl3.variable.value == 3.0
|
| 442 |
+
|
| 443 |
+
raises(ValueError, lambda: Declaration(vi, 42))
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
def test_IntBaseType():
|
| 447 |
+
assert intc.name == String('intc')
|
| 448 |
+
assert intc.args == (intc.name,)
|
| 449 |
+
assert str(IntBaseType('a').name) == 'a'
|
| 450 |
+
|
| 451 |
+
|
| 452 |
+
def test_FloatType():
|
| 453 |
+
assert f16.dig == 3
|
| 454 |
+
assert f32.dig == 6
|
| 455 |
+
assert f64.dig == 15
|
| 456 |
+
assert f80.dig == 18
|
| 457 |
+
assert f128.dig == 33
|
| 458 |
+
|
| 459 |
+
assert f16.decimal_dig == 5
|
| 460 |
+
assert f32.decimal_dig == 9
|
| 461 |
+
assert f64.decimal_dig == 17
|
| 462 |
+
assert f80.decimal_dig == 21
|
| 463 |
+
assert f128.decimal_dig == 36
|
| 464 |
+
|
| 465 |
+
assert f16.max_exponent == 16
|
| 466 |
+
assert f32.max_exponent == 128
|
| 467 |
+
assert f64.max_exponent == 1024
|
| 468 |
+
assert f80.max_exponent == 16384
|
| 469 |
+
assert f128.max_exponent == 16384
|
| 470 |
+
|
| 471 |
+
assert f16.min_exponent == -13
|
| 472 |
+
assert f32.min_exponent == -125
|
| 473 |
+
assert f64.min_exponent == -1021
|
| 474 |
+
assert f80.min_exponent == -16381
|
| 475 |
+
assert f128.min_exponent == -16381
|
| 476 |
+
|
| 477 |
+
assert abs(f16.eps / Float('0.00097656', precision=16) - 1) < 0.1*10**-f16.dig
|
| 478 |
+
assert abs(f32.eps / Float('1.1920929e-07', precision=32) - 1) < 0.1*10**-f32.dig
|
| 479 |
+
assert abs(f64.eps / Float('2.2204460492503131e-16', precision=64) - 1) < 0.1*10**-f64.dig
|
| 480 |
+
assert abs(f80.eps / Float('1.08420217248550443401e-19', precision=80) - 1) < 0.1*10**-f80.dig
|
| 481 |
+
assert abs(f128.eps / Float(' 1.92592994438723585305597794258492732e-34', precision=128) - 1) < 0.1*10**-f128.dig
|
| 482 |
+
|
| 483 |
+
assert abs(f16.max / Float('65504', precision=16) - 1) < .1*10**-f16.dig
|
| 484 |
+
assert abs(f32.max / Float('3.40282347e+38', precision=32) - 1) < 0.1*10**-f32.dig
|
| 485 |
+
assert abs(f64.max / Float('1.79769313486231571e+308', precision=64) - 1) < 0.1*10**-f64.dig # cf. np.finfo(np.float64).max
|
| 486 |
+
assert abs(f80.max / Float('1.18973149535723176502e+4932', precision=80) - 1) < 0.1*10**-f80.dig
|
| 487 |
+
assert abs(f128.max / Float('1.18973149535723176508575932662800702e+4932', precision=128) - 1) < 0.1*10**-f128.dig
|
| 488 |
+
|
| 489 |
+
# cf. np.finfo(np.float32).tiny
|
| 490 |
+
assert abs(f16.tiny / Float('6.1035e-05', precision=16) - 1) < 0.1*10**-f16.dig
|
| 491 |
+
assert abs(f32.tiny / Float('1.17549435e-38', precision=32) - 1) < 0.1*10**-f32.dig
|
| 492 |
+
assert abs(f64.tiny / Float('2.22507385850720138e-308', precision=64) - 1) < 0.1*10**-f64.dig
|
| 493 |
+
assert abs(f80.tiny / Float('3.36210314311209350626e-4932', precision=80) - 1) < 0.1*10**-f80.dig
|
| 494 |
+
assert abs(f128.tiny / Float('3.3621031431120935062626778173217526e-4932', precision=128) - 1) < 0.1*10**-f128.dig
|
| 495 |
+
|
| 496 |
+
assert f64.cast_check(0.5) == Float(0.5, 17)
|
| 497 |
+
assert abs(f64.cast_check(3.7) - 3.7) < 3e-17
|
| 498 |
+
assert isinstance(f64.cast_check(3), (Float, float))
|
| 499 |
+
|
| 500 |
+
assert f64.cast_nocheck(oo) == float('inf')
|
| 501 |
+
assert f64.cast_nocheck(-oo) == float('-inf')
|
| 502 |
+
assert f64.cast_nocheck(float(oo)) == float('inf')
|
| 503 |
+
assert f64.cast_nocheck(float(-oo)) == float('-inf')
|
| 504 |
+
assert math.isnan(f64.cast_nocheck(nan))
|
| 505 |
+
|
| 506 |
+
assert f32 != f64
|
| 507 |
+
assert f64 == f64.func(*f64.args)
|
| 508 |
+
|
| 509 |
+
|
| 510 |
+
def test_Type__cast_check__floating_point():
|
| 511 |
+
raises(ValueError, lambda: f32.cast_check(123.45678949))
|
| 512 |
+
raises(ValueError, lambda: f32.cast_check(12.345678949))
|
| 513 |
+
raises(ValueError, lambda: f32.cast_check(1.2345678949))
|
| 514 |
+
raises(ValueError, lambda: f32.cast_check(.12345678949))
|
| 515 |
+
assert abs(123.456789049 - f32.cast_check(123.456789049) - 4.9e-8) < 1e-8
|
| 516 |
+
assert abs(0.12345678904 - f32.cast_check(0.12345678904) - 4e-11) < 1e-11
|
| 517 |
+
|
| 518 |
+
dcm21 = Float('0.123456789012345670499') # 21 decimals
|
| 519 |
+
assert abs(dcm21 - f64.cast_check(dcm21) - 4.99e-19) < 1e-19
|
| 520 |
+
|
| 521 |
+
f80.cast_check(Float('0.12345678901234567890103', precision=88))
|
| 522 |
+
raises(ValueError, lambda: f80.cast_check(Float('0.12345678901234567890149', precision=88)))
|
| 523 |
+
|
| 524 |
+
v10 = 12345.67894
|
| 525 |
+
raises(ValueError, lambda: f32.cast_check(v10))
|
| 526 |
+
assert abs(Float(str(v10), precision=64+8) - f64.cast_check(v10)) < v10*1e-16
|
| 527 |
+
|
| 528 |
+
assert abs(f32.cast_check(2147483647) - 2147483650) < 1
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
def test_Type__cast_check__complex_floating_point():
|
| 532 |
+
val9_11 = 123.456789049 + 0.123456789049j
|
| 533 |
+
raises(ValueError, lambda: c64.cast_check(.12345678949 + .12345678949j))
|
| 534 |
+
assert abs(val9_11 - c64.cast_check(val9_11) - 4.9e-8) < 1e-8
|
| 535 |
+
|
| 536 |
+
dcm21 = Float('0.123456789012345670499') + 1e-20j # 21 decimals
|
| 537 |
+
assert abs(dcm21 - c128.cast_check(dcm21) - 4.99e-19) < 1e-19
|
| 538 |
+
v19 = Float('0.1234567890123456749') + 1j*Float('0.1234567890123456749')
|
| 539 |
+
raises(ValueError, lambda: c128.cast_check(v19))
|
| 540 |
+
|
| 541 |
+
|
| 542 |
+
def test_While():
|
| 543 |
+
xpp = AddAugmentedAssignment(x, 1)
|
| 544 |
+
whl1 = While(x < 2, [xpp])
|
| 545 |
+
assert whl1.condition.args[0] == x
|
| 546 |
+
assert whl1.condition.args[1] == 2
|
| 547 |
+
assert whl1.condition == Lt(x, 2, evaluate=False)
|
| 548 |
+
assert whl1.body.args == (xpp,)
|
| 549 |
+
assert whl1.func(*whl1.args) == whl1
|
| 550 |
+
|
| 551 |
+
cblk = CodeBlock(AddAugmentedAssignment(x, 1))
|
| 552 |
+
whl2 = While(x < 2, cblk)
|
| 553 |
+
assert whl1 == whl2
|
| 554 |
+
assert whl1 != While(x < 3, [xpp])
|
| 555 |
+
|
| 556 |
+
|
| 557 |
+
def test_Scope():
|
| 558 |
+
assign = Assignment(x, y)
|
| 559 |
+
incr = AddAugmentedAssignment(x, 1)
|
| 560 |
+
scp = Scope([assign, incr])
|
| 561 |
+
cblk = CodeBlock(assign, incr)
|
| 562 |
+
assert scp.body == cblk
|
| 563 |
+
assert scp == Scope(cblk)
|
| 564 |
+
assert scp != Scope([incr, assign])
|
| 565 |
+
assert scp.func(*scp.args) == scp
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
def test_Print():
|
| 569 |
+
fmt = "%d %.3f"
|
| 570 |
+
ps = Print([n, x], fmt)
|
| 571 |
+
assert str(ps.format_string) == fmt
|
| 572 |
+
assert ps.print_args == Tuple(n, x)
|
| 573 |
+
assert ps.args == (Tuple(n, x), QuotedString(fmt), none)
|
| 574 |
+
assert ps == Print((n, x), fmt)
|
| 575 |
+
assert ps != Print([x, n], fmt)
|
| 576 |
+
assert ps.func(*ps.args) == ps
|
| 577 |
+
|
| 578 |
+
ps2 = Print([n, x])
|
| 579 |
+
assert ps2 == Print([n, x])
|
| 580 |
+
assert ps2 != ps
|
| 581 |
+
assert ps2.format_string == None
|
| 582 |
+
|
| 583 |
+
|
| 584 |
+
def test_FunctionPrototype_and_FunctionDefinition():
|
| 585 |
+
vx = Variable(x, type=real)
|
| 586 |
+
vn = Variable(n, type=integer)
|
| 587 |
+
fp1 = FunctionPrototype(real, 'power', [vx, vn])
|
| 588 |
+
assert fp1.return_type == real
|
| 589 |
+
assert fp1.name == String('power')
|
| 590 |
+
assert fp1.parameters == Tuple(vx, vn)
|
| 591 |
+
assert fp1 == FunctionPrototype(real, 'power', [vx, vn])
|
| 592 |
+
assert fp1 != FunctionPrototype(real, 'power', [vn, vx])
|
| 593 |
+
assert fp1.func(*fp1.args) == fp1
|
| 594 |
+
|
| 595 |
+
|
| 596 |
+
body = [Assignment(x, x**n), Return(x)]
|
| 597 |
+
fd1 = FunctionDefinition(real, 'power', [vx, vn], body)
|
| 598 |
+
assert fd1.return_type == real
|
| 599 |
+
assert str(fd1.name) == 'power'
|
| 600 |
+
assert fd1.parameters == Tuple(vx, vn)
|
| 601 |
+
assert fd1.body == CodeBlock(*body)
|
| 602 |
+
assert fd1 == FunctionDefinition(real, 'power', [vx, vn], body)
|
| 603 |
+
assert fd1 != FunctionDefinition(real, 'power', [vx, vn], body[::-1])
|
| 604 |
+
assert fd1.func(*fd1.args) == fd1
|
| 605 |
+
|
| 606 |
+
fp2 = FunctionPrototype.from_FunctionDefinition(fd1)
|
| 607 |
+
assert fp2 == fp1
|
| 608 |
+
|
| 609 |
+
fd2 = FunctionDefinition.from_FunctionPrototype(fp1, body)
|
| 610 |
+
assert fd2 == fd1
|
| 611 |
+
|
| 612 |
+
|
| 613 |
+
def test_Return():
|
| 614 |
+
rs = Return(x)
|
| 615 |
+
assert rs.args == (x,)
|
| 616 |
+
assert rs == Return(x)
|
| 617 |
+
assert rs != Return(y)
|
| 618 |
+
assert rs.func(*rs.args) == rs
|
| 619 |
+
|
| 620 |
+
|
| 621 |
+
def test_FunctionCall():
|
| 622 |
+
fc = FunctionCall('power', (x, 3))
|
| 623 |
+
assert fc.function_args[0] == x
|
| 624 |
+
assert fc.function_args[1] == 3
|
| 625 |
+
assert len(fc.function_args) == 2
|
| 626 |
+
assert isinstance(fc.function_args[1], Integer)
|
| 627 |
+
assert fc == FunctionCall('power', (x, 3))
|
| 628 |
+
assert fc != FunctionCall('power', (3, x))
|
| 629 |
+
assert fc != FunctionCall('Power', (x, 3))
|
| 630 |
+
assert fc.func(*fc.args) == fc
|
| 631 |
+
|
| 632 |
+
fc2 = FunctionCall('fma', [2, 3, 4])
|
| 633 |
+
assert len(fc2.function_args) == 3
|
| 634 |
+
assert fc2.function_args[0] == 2
|
| 635 |
+
assert fc2.function_args[1] == 3
|
| 636 |
+
assert fc2.function_args[2] == 4
|
| 637 |
+
assert str(fc2) in ( # not sure if QuotedString is a better default...
|
| 638 |
+
'FunctionCall(fma, function_args=(2, 3, 4))',
|
| 639 |
+
'FunctionCall("fma", function_args=(2, 3, 4))',
|
| 640 |
+
)
|
| 641 |
+
|
| 642 |
+
def test_ast_replace():
|
| 643 |
+
x = Variable('x', real)
|
| 644 |
+
y = Variable('y', real)
|
| 645 |
+
n = Variable('n', integer)
|
| 646 |
+
|
| 647 |
+
pwer = FunctionDefinition(real, 'pwer', [x, n], [pow(x.symbol, n.symbol)])
|
| 648 |
+
pname = pwer.name
|
| 649 |
+
pcall = FunctionCall('pwer', [y, 3])
|
| 650 |
+
|
| 651 |
+
tree1 = CodeBlock(pwer, pcall)
|
| 652 |
+
assert str(tree1.args[0].name) == 'pwer'
|
| 653 |
+
assert str(tree1.args[1].name) == 'pwer'
|
| 654 |
+
for a, b in zip(tree1, [pwer, pcall]):
|
| 655 |
+
assert a == b
|
| 656 |
+
|
| 657 |
+
tree2 = tree1.replace(pname, String('power'))
|
| 658 |
+
assert str(tree1.args[0].name) == 'pwer'
|
| 659 |
+
assert str(tree1.args[1].name) == 'pwer'
|
| 660 |
+
assert str(tree2.args[0].name) == 'power'
|
| 661 |
+
assert str(tree2.args[1].name) == 'power'
|
pllava/lib/python3.10/site-packages/sympy/codegen/tests/test_cfunctions.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.numbers import (Rational, pi)
|
| 2 |
+
from sympy.core.singleton import S
|
| 3 |
+
from sympy.core.symbol import (Symbol, symbols)
|
| 4 |
+
from sympy.functions.elementary.exponential import (exp, log)
|
| 5 |
+
from sympy.codegen.cfunctions import (
|
| 6 |
+
expm1, log1p, exp2, log2, fma, log10, Sqrt, Cbrt, hypot
|
| 7 |
+
)
|
| 8 |
+
from sympy.core.function import expand_log
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def test_expm1():
|
| 12 |
+
# Eval
|
| 13 |
+
assert expm1(0) == 0
|
| 14 |
+
|
| 15 |
+
x = Symbol('x', real=True)
|
| 16 |
+
|
| 17 |
+
# Expand and rewrite
|
| 18 |
+
assert expm1(x).expand(func=True) - exp(x) == -1
|
| 19 |
+
assert expm1(x).rewrite('tractable') - exp(x) == -1
|
| 20 |
+
assert expm1(x).rewrite('exp') - exp(x) == -1
|
| 21 |
+
|
| 22 |
+
# Precision
|
| 23 |
+
assert not ((exp(1e-10).evalf() - 1) - 1e-10 - 5e-21) < 1e-22 # for comparison
|
| 24 |
+
assert abs(expm1(1e-10).evalf() - 1e-10 - 5e-21) < 1e-22
|
| 25 |
+
|
| 26 |
+
# Properties
|
| 27 |
+
assert expm1(x).is_real
|
| 28 |
+
assert expm1(x).is_finite
|
| 29 |
+
|
| 30 |
+
# Diff
|
| 31 |
+
assert expm1(42*x).diff(x) - 42*exp(42*x) == 0
|
| 32 |
+
assert expm1(42*x).diff(x) - expm1(42*x).expand(func=True).diff(x) == 0
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def test_log1p():
|
| 36 |
+
# Eval
|
| 37 |
+
assert log1p(0) == 0
|
| 38 |
+
d = S(10)
|
| 39 |
+
assert expand_log(log1p(d**-1000) - log(d**1000 + 1) + log(d**1000)) == 0
|
| 40 |
+
|
| 41 |
+
x = Symbol('x', real=True)
|
| 42 |
+
|
| 43 |
+
# Expand and rewrite
|
| 44 |
+
assert log1p(x).expand(func=True) - log(x + 1) == 0
|
| 45 |
+
assert log1p(x).rewrite('tractable') - log(x + 1) == 0
|
| 46 |
+
assert log1p(x).rewrite('log') - log(x + 1) == 0
|
| 47 |
+
|
| 48 |
+
# Precision
|
| 49 |
+
assert not abs(log(1e-99 + 1).evalf() - 1e-99) < 1e-100 # for comparison
|
| 50 |
+
assert abs(expand_log(log1p(1e-99)).evalf() - 1e-99) < 1e-100
|
| 51 |
+
|
| 52 |
+
# Properties
|
| 53 |
+
assert log1p(-2**Rational(-1, 2)).is_real
|
| 54 |
+
|
| 55 |
+
assert not log1p(-1).is_finite
|
| 56 |
+
assert log1p(pi).is_finite
|
| 57 |
+
|
| 58 |
+
assert not log1p(x).is_positive
|
| 59 |
+
assert log1p(Symbol('y', positive=True)).is_positive
|
| 60 |
+
|
| 61 |
+
assert not log1p(x).is_zero
|
| 62 |
+
assert log1p(Symbol('z', zero=True)).is_zero
|
| 63 |
+
|
| 64 |
+
assert not log1p(x).is_nonnegative
|
| 65 |
+
assert log1p(Symbol('o', nonnegative=True)).is_nonnegative
|
| 66 |
+
|
| 67 |
+
# Diff
|
| 68 |
+
assert log1p(42*x).diff(x) - 42/(42*x + 1) == 0
|
| 69 |
+
assert log1p(42*x).diff(x) - log1p(42*x).expand(func=True).diff(x) == 0
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def test_exp2():
|
| 73 |
+
# Eval
|
| 74 |
+
assert exp2(2) == 4
|
| 75 |
+
|
| 76 |
+
x = Symbol('x', real=True)
|
| 77 |
+
|
| 78 |
+
# Expand
|
| 79 |
+
assert exp2(x).expand(func=True) - 2**x == 0
|
| 80 |
+
|
| 81 |
+
# Diff
|
| 82 |
+
assert exp2(42*x).diff(x) - 42*exp2(42*x)*log(2) == 0
|
| 83 |
+
assert exp2(42*x).diff(x) - exp2(42*x).diff(x) == 0
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def test_log2():
|
| 87 |
+
# Eval
|
| 88 |
+
assert log2(8) == 3
|
| 89 |
+
assert log2(pi) != log(pi)/log(2) # log2 should *save* (CPU) instructions
|
| 90 |
+
|
| 91 |
+
x = Symbol('x', real=True)
|
| 92 |
+
assert log2(x) != log(x)/log(2)
|
| 93 |
+
assert log2(2**x) == x
|
| 94 |
+
|
| 95 |
+
# Expand
|
| 96 |
+
assert log2(x).expand(func=True) - log(x)/log(2) == 0
|
| 97 |
+
|
| 98 |
+
# Diff
|
| 99 |
+
assert log2(42*x).diff() - 1/(log(2)*x) == 0
|
| 100 |
+
assert log2(42*x).diff() - log2(42*x).expand(func=True).diff(x) == 0
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def test_fma():
|
| 104 |
+
x, y, z = symbols('x y z')
|
| 105 |
+
|
| 106 |
+
# Expand
|
| 107 |
+
assert fma(x, y, z).expand(func=True) - x*y - z == 0
|
| 108 |
+
|
| 109 |
+
expr = fma(17*x, 42*y, 101*z)
|
| 110 |
+
|
| 111 |
+
# Diff
|
| 112 |
+
assert expr.diff(x) - expr.expand(func=True).diff(x) == 0
|
| 113 |
+
assert expr.diff(y) - expr.expand(func=True).diff(y) == 0
|
| 114 |
+
assert expr.diff(z) - expr.expand(func=True).diff(z) == 0
|
| 115 |
+
|
| 116 |
+
assert expr.diff(x) - 17*42*y == 0
|
| 117 |
+
assert expr.diff(y) - 17*42*x == 0
|
| 118 |
+
assert expr.diff(z) - 101 == 0
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def test_log10():
|
| 122 |
+
x = Symbol('x')
|
| 123 |
+
|
| 124 |
+
# Expand
|
| 125 |
+
assert log10(x).expand(func=True) - log(x)/log(10) == 0
|
| 126 |
+
|
| 127 |
+
# Diff
|
| 128 |
+
assert log10(42*x).diff(x) - 1/(log(10)*x) == 0
|
| 129 |
+
assert log10(42*x).diff(x) - log10(42*x).expand(func=True).diff(x) == 0
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def test_Cbrt():
|
| 133 |
+
x = Symbol('x')
|
| 134 |
+
|
| 135 |
+
# Expand
|
| 136 |
+
assert Cbrt(x).expand(func=True) - x**Rational(1, 3) == 0
|
| 137 |
+
|
| 138 |
+
# Diff
|
| 139 |
+
assert Cbrt(42*x).diff(x) - 42*(42*x)**(Rational(1, 3) - 1)/3 == 0
|
| 140 |
+
assert Cbrt(42*x).diff(x) - Cbrt(42*x).expand(func=True).diff(x) == 0
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def test_Sqrt():
|
| 144 |
+
x = Symbol('x')
|
| 145 |
+
|
| 146 |
+
# Expand
|
| 147 |
+
assert Sqrt(x).expand(func=True) - x**S.Half == 0
|
| 148 |
+
|
| 149 |
+
# Diff
|
| 150 |
+
assert Sqrt(42*x).diff(x) - 42*(42*x)**(S.Half - 1)/2 == 0
|
| 151 |
+
assert Sqrt(42*x).diff(x) - Sqrt(42*x).expand(func=True).diff(x) == 0
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def test_hypot():
|
| 155 |
+
x, y = symbols('x y')
|
| 156 |
+
|
| 157 |
+
# Expand
|
| 158 |
+
assert hypot(x, y).expand(func=True) - (x**2 + y**2)**S.Half == 0
|
| 159 |
+
|
| 160 |
+
# Diff
|
| 161 |
+
assert hypot(17*x, 42*y).diff(x).expand(func=True) - hypot(17*x, 42*y).expand(func=True).diff(x) == 0
|
| 162 |
+
assert hypot(17*x, 42*y).diff(y).expand(func=True) - hypot(17*x, 42*y).expand(func=True).diff(y) == 0
|
| 163 |
+
|
| 164 |
+
assert hypot(17*x, 42*y).diff(x).expand(func=True) - 2*17*17*x*((17*x)**2 + (42*y)**2)**Rational(-1, 2)/2 == 0
|
| 165 |
+
assert hypot(17*x, 42*y).diff(y).expand(func=True) - 2*42*42*y*((17*x)**2 + (42*y)**2)**Rational(-1, 2)/2 == 0
|
pllava/lib/python3.10/site-packages/sympy/codegen/tests/test_cnodes.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.symbol import symbols
|
| 2 |
+
from sympy.printing.codeprinter import ccode
|
| 3 |
+
from sympy.codegen.ast import Declaration, Variable, float64, int64, String, CodeBlock
|
| 4 |
+
from sympy.codegen.cnodes import (
|
| 5 |
+
alignof, CommaOperator, goto, Label, PreDecrement, PostDecrement, PreIncrement, PostIncrement,
|
| 6 |
+
sizeof, union, struct
|
| 7 |
+
)
|
| 8 |
+
|
| 9 |
+
x, y = symbols('x y')
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def test_alignof():
|
| 13 |
+
ax = alignof(x)
|
| 14 |
+
assert ccode(ax) == 'alignof(x)'
|
| 15 |
+
assert ax.func(*ax.args) == ax
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def test_CommaOperator():
|
| 19 |
+
expr = CommaOperator(PreIncrement(x), 2*x)
|
| 20 |
+
assert ccode(expr) == '(++(x), 2*x)'
|
| 21 |
+
assert expr.func(*expr.args) == expr
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def test_goto_Label():
|
| 25 |
+
s = 'early_exit'
|
| 26 |
+
g = goto(s)
|
| 27 |
+
assert g.func(*g.args) == g
|
| 28 |
+
assert g != goto('foobar')
|
| 29 |
+
assert ccode(g) == 'goto early_exit'
|
| 30 |
+
|
| 31 |
+
l1 = Label(s)
|
| 32 |
+
assert ccode(l1) == 'early_exit:'
|
| 33 |
+
assert l1 == Label('early_exit')
|
| 34 |
+
assert l1 != Label('foobar')
|
| 35 |
+
|
| 36 |
+
body = [PreIncrement(x)]
|
| 37 |
+
l2 = Label(s, body)
|
| 38 |
+
assert l2.name == String("early_exit")
|
| 39 |
+
assert l2.body == CodeBlock(PreIncrement(x))
|
| 40 |
+
assert ccode(l2) == ("early_exit:\n"
|
| 41 |
+
"++(x);")
|
| 42 |
+
|
| 43 |
+
body = [PreIncrement(x), PreDecrement(y)]
|
| 44 |
+
l2 = Label(s, body)
|
| 45 |
+
assert l2.name == String("early_exit")
|
| 46 |
+
assert l2.body == CodeBlock(PreIncrement(x), PreDecrement(y))
|
| 47 |
+
assert ccode(l2) == ("early_exit:\n"
|
| 48 |
+
"{\n ++(x);\n --(y);\n}")
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def test_PreDecrement():
|
| 52 |
+
p = PreDecrement(x)
|
| 53 |
+
assert p.func(*p.args) == p
|
| 54 |
+
assert ccode(p) == '--(x)'
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def test_PostDecrement():
|
| 58 |
+
p = PostDecrement(x)
|
| 59 |
+
assert p.func(*p.args) == p
|
| 60 |
+
assert ccode(p) == '(x)--'
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def test_PreIncrement():
|
| 64 |
+
p = PreIncrement(x)
|
| 65 |
+
assert p.func(*p.args) == p
|
| 66 |
+
assert ccode(p) == '++(x)'
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def test_PostIncrement():
|
| 70 |
+
p = PostIncrement(x)
|
| 71 |
+
assert p.func(*p.args) == p
|
| 72 |
+
assert ccode(p) == '(x)++'
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def test_sizeof():
|
| 76 |
+
typename = 'unsigned int'
|
| 77 |
+
sz = sizeof(typename)
|
| 78 |
+
assert ccode(sz) == 'sizeof(%s)' % typename
|
| 79 |
+
assert sz.func(*sz.args) == sz
|
| 80 |
+
assert not sz.is_Atom
|
| 81 |
+
assert sz.atoms() == {String('unsigned int'), String('sizeof')}
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def test_struct():
|
| 85 |
+
vx, vy = Variable(x, type=float64), Variable(y, type=float64)
|
| 86 |
+
s = struct('vec2', [vx, vy])
|
| 87 |
+
assert s.func(*s.args) == s
|
| 88 |
+
assert s == struct('vec2', (vx, vy))
|
| 89 |
+
assert s != struct('vec2', (vy, vx))
|
| 90 |
+
assert str(s.name) == 'vec2'
|
| 91 |
+
assert len(s.declarations) == 2
|
| 92 |
+
assert all(isinstance(arg, Declaration) for arg in s.declarations)
|
| 93 |
+
assert ccode(s) == (
|
| 94 |
+
"struct vec2 {\n"
|
| 95 |
+
" double x;\n"
|
| 96 |
+
" double y;\n"
|
| 97 |
+
"}")
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def test_union():
|
| 101 |
+
vx, vy = Variable(x, type=float64), Variable(y, type=int64)
|
| 102 |
+
u = union('dualuse', [vx, vy])
|
| 103 |
+
assert u.func(*u.args) == u
|
| 104 |
+
assert u == union('dualuse', (vx, vy))
|
| 105 |
+
assert str(u.name) == 'dualuse'
|
| 106 |
+
assert len(u.declarations) == 2
|
| 107 |
+
assert all(isinstance(arg, Declaration) for arg in u.declarations)
|
| 108 |
+
assert ccode(u) == (
|
| 109 |
+
"union dualuse {\n"
|
| 110 |
+
" double x;\n"
|
| 111 |
+
" int64_t y;\n"
|
| 112 |
+
"}")
|
pllava/lib/python3.10/site-packages/sympy/codegen/tests/test_cxxnodes.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.symbol import Symbol
|
| 2 |
+
from sympy.codegen.ast import Type
|
| 3 |
+
from sympy.codegen.cxxnodes import using
|
| 4 |
+
from sympy.printing.codeprinter import cxxcode
|
| 5 |
+
|
| 6 |
+
x = Symbol('x')
|
| 7 |
+
|
| 8 |
+
def test_using():
|
| 9 |
+
v = Type('std::vector')
|
| 10 |
+
u1 = using(v)
|
| 11 |
+
assert cxxcode(u1) == 'using std::vector'
|
| 12 |
+
|
| 13 |
+
u2 = using(v, 'vec')
|
| 14 |
+
assert cxxcode(u2) == 'using vec = std::vector'
|
pllava/lib/python3.10/site-packages/sympy/codegen/tests/test_fnodes.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import tempfile
|
| 3 |
+
from sympy.core.symbol import (Symbol, symbols)
|
| 4 |
+
from sympy.codegen.ast import (
|
| 5 |
+
Assignment, Print, Declaration, FunctionDefinition, Return, real,
|
| 6 |
+
FunctionCall, Variable, Element, integer
|
| 7 |
+
)
|
| 8 |
+
from sympy.codegen.fnodes import (
|
| 9 |
+
allocatable, ArrayConstructor, isign, dsign, cmplx, kind, literal_dp,
|
| 10 |
+
Program, Module, use, Subroutine, dimension, assumed_extent, ImpliedDoLoop,
|
| 11 |
+
intent_out, size, Do, SubroutineCall, sum_, array, bind_C
|
| 12 |
+
)
|
| 13 |
+
from sympy.codegen.futils import render_as_module
|
| 14 |
+
from sympy.core.expr import unchanged
|
| 15 |
+
from sympy.external import import_module
|
| 16 |
+
from sympy.printing.codeprinter import fcode
|
| 17 |
+
from sympy.utilities._compilation import has_fortran, compile_run_strings, compile_link_import_strings
|
| 18 |
+
from sympy.utilities._compilation.util import may_xfail
|
| 19 |
+
from sympy.testing.pytest import skip, XFAIL
|
| 20 |
+
|
| 21 |
+
cython = import_module('cython')
|
| 22 |
+
np = import_module('numpy')
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def test_size():
|
| 26 |
+
x = Symbol('x', real=True)
|
| 27 |
+
sx = size(x)
|
| 28 |
+
assert fcode(sx, source_format='free') == 'size(x)'
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@may_xfail
|
| 32 |
+
def test_size_assumed_shape():
|
| 33 |
+
if not has_fortran():
|
| 34 |
+
skip("No fortran compiler found.")
|
| 35 |
+
a = Symbol('a', real=True)
|
| 36 |
+
body = [Return((sum_(a**2)/size(a))**.5)]
|
| 37 |
+
arr = array(a, dim=[':'], intent='in')
|
| 38 |
+
fd = FunctionDefinition(real, 'rms', [arr], body)
|
| 39 |
+
render_as_module([fd], 'mod_rms')
|
| 40 |
+
|
| 41 |
+
(stdout, stderr), info = compile_run_strings([
|
| 42 |
+
('rms.f90', render_as_module([fd], 'mod_rms')),
|
| 43 |
+
('main.f90', (
|
| 44 |
+
'program myprog\n'
|
| 45 |
+
'use mod_rms, only: rms\n'
|
| 46 |
+
'real*8, dimension(4), parameter :: x = [4, 2, 2, 2]\n'
|
| 47 |
+
'print *, dsqrt(7d0) - rms(x)\n'
|
| 48 |
+
'end program\n'
|
| 49 |
+
))
|
| 50 |
+
], clean=True)
|
| 51 |
+
assert '0.00000' in stdout
|
| 52 |
+
assert stderr == ''
|
| 53 |
+
assert info['exit_status'] == os.EX_OK
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
@XFAIL # https://github.com/sympy/sympy/issues/20265
|
| 57 |
+
@may_xfail
|
| 58 |
+
def test_ImpliedDoLoop():
|
| 59 |
+
if not has_fortran():
|
| 60 |
+
skip("No fortran compiler found.")
|
| 61 |
+
|
| 62 |
+
a, i = symbols('a i', integer=True)
|
| 63 |
+
idl = ImpliedDoLoop(i**3, i, -3, 3, 2)
|
| 64 |
+
ac = ArrayConstructor([-28, idl, 28])
|
| 65 |
+
a = array(a, dim=[':'], attrs=[allocatable])
|
| 66 |
+
prog = Program('idlprog', [
|
| 67 |
+
a.as_Declaration(),
|
| 68 |
+
Assignment(a, ac),
|
| 69 |
+
Print([a])
|
| 70 |
+
])
|
| 71 |
+
fsrc = fcode(prog, standard=2003, source_format='free')
|
| 72 |
+
(stdout, stderr), info = compile_run_strings([('main.f90', fsrc)], clean=True)
|
| 73 |
+
for numstr in '-28 -27 -1 1 27 28'.split():
|
| 74 |
+
assert numstr in stdout
|
| 75 |
+
assert stderr == ''
|
| 76 |
+
assert info['exit_status'] == os.EX_OK
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
@may_xfail
|
| 80 |
+
def test_Program():
|
| 81 |
+
x = Symbol('x', real=True)
|
| 82 |
+
vx = Variable.deduced(x, 42)
|
| 83 |
+
decl = Declaration(vx)
|
| 84 |
+
prnt = Print([x, x+1])
|
| 85 |
+
prog = Program('foo', [decl, prnt])
|
| 86 |
+
if not has_fortran():
|
| 87 |
+
skip("No fortran compiler found.")
|
| 88 |
+
|
| 89 |
+
(stdout, stderr), info = compile_run_strings([('main.f90', fcode(prog, standard=90))], clean=True)
|
| 90 |
+
assert '42' in stdout
|
| 91 |
+
assert '43' in stdout
|
| 92 |
+
assert stderr == ''
|
| 93 |
+
assert info['exit_status'] == os.EX_OK
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
@may_xfail
|
| 97 |
+
def test_Module():
|
| 98 |
+
x = Symbol('x', real=True)
|
| 99 |
+
v_x = Variable.deduced(x)
|
| 100 |
+
sq = FunctionDefinition(real, 'sqr', [v_x], [Return(x**2)])
|
| 101 |
+
mod_sq = Module('mod_sq', [], [sq])
|
| 102 |
+
sq_call = FunctionCall('sqr', [42.])
|
| 103 |
+
prg_sq = Program('foobar', [
|
| 104 |
+
use('mod_sq', only=['sqr']),
|
| 105 |
+
Print(['"Square of 42 = "', sq_call])
|
| 106 |
+
])
|
| 107 |
+
if not has_fortran():
|
| 108 |
+
skip("No fortran compiler found.")
|
| 109 |
+
(stdout, stderr), info = compile_run_strings([
|
| 110 |
+
('mod_sq.f90', fcode(mod_sq, standard=90)),
|
| 111 |
+
('main.f90', fcode(prg_sq, standard=90))
|
| 112 |
+
], clean=True)
|
| 113 |
+
assert '42' in stdout
|
| 114 |
+
assert str(42**2) in stdout
|
| 115 |
+
assert stderr == ''
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
@XFAIL # https://github.com/sympy/sympy/issues/20265
|
| 119 |
+
@may_xfail
|
| 120 |
+
def test_Subroutine():
|
| 121 |
+
# Code to generate the subroutine in the example from
|
| 122 |
+
# http://www.fortran90.org/src/best-practices.html#arrays
|
| 123 |
+
r = Symbol('r', real=True)
|
| 124 |
+
i = Symbol('i', integer=True)
|
| 125 |
+
v_r = Variable.deduced(r, attrs=(dimension(assumed_extent), intent_out))
|
| 126 |
+
v_i = Variable.deduced(i)
|
| 127 |
+
v_n = Variable('n', integer)
|
| 128 |
+
do_loop = Do([
|
| 129 |
+
Assignment(Element(r, [i]), literal_dp(1)/i**2)
|
| 130 |
+
], i, 1, v_n)
|
| 131 |
+
sub = Subroutine("f", [v_r], [
|
| 132 |
+
Declaration(v_n),
|
| 133 |
+
Declaration(v_i),
|
| 134 |
+
Assignment(v_n, size(r)),
|
| 135 |
+
do_loop
|
| 136 |
+
])
|
| 137 |
+
x = Symbol('x', real=True)
|
| 138 |
+
v_x3 = Variable.deduced(x, attrs=[dimension(3)])
|
| 139 |
+
mod = Module('mymod', definitions=[sub])
|
| 140 |
+
prog = Program('foo', [
|
| 141 |
+
use(mod, only=[sub]),
|
| 142 |
+
Declaration(v_x3),
|
| 143 |
+
SubroutineCall(sub, [v_x3]),
|
| 144 |
+
Print([sum_(v_x3), v_x3])
|
| 145 |
+
])
|
| 146 |
+
|
| 147 |
+
if not has_fortran():
|
| 148 |
+
skip("No fortran compiler found.")
|
| 149 |
+
|
| 150 |
+
(stdout, stderr), info = compile_run_strings([
|
| 151 |
+
('a.f90', fcode(mod, standard=90)),
|
| 152 |
+
('b.f90', fcode(prog, standard=90))
|
| 153 |
+
], clean=True)
|
| 154 |
+
ref = [1.0/i**2 for i in range(1, 4)]
|
| 155 |
+
assert str(sum(ref))[:-3] in stdout
|
| 156 |
+
for _ in ref:
|
| 157 |
+
assert str(_)[:-3] in stdout
|
| 158 |
+
assert stderr == ''
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
def test_isign():
|
| 162 |
+
x = Symbol('x', integer=True)
|
| 163 |
+
assert unchanged(isign, 1, x)
|
| 164 |
+
assert fcode(isign(1, x), standard=95, source_format='free') == 'isign(1, x)'
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def test_dsign():
|
| 168 |
+
x = Symbol('x')
|
| 169 |
+
assert unchanged(dsign, 1, x)
|
| 170 |
+
assert fcode(dsign(literal_dp(1), x), standard=95, source_format='free') == 'dsign(1d0, x)'
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def test_cmplx():
|
| 174 |
+
x = Symbol('x')
|
| 175 |
+
assert unchanged(cmplx, 1, x)
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def test_kind():
|
| 179 |
+
x = Symbol('x')
|
| 180 |
+
assert unchanged(kind, x)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def test_literal_dp():
|
| 184 |
+
assert fcode(literal_dp(0), source_format='free') == '0d0'
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
@may_xfail
|
| 188 |
+
def test_bind_C():
|
| 189 |
+
if not has_fortran():
|
| 190 |
+
skip("No fortran compiler found.")
|
| 191 |
+
if not cython:
|
| 192 |
+
skip("Cython not found.")
|
| 193 |
+
if not np:
|
| 194 |
+
skip("NumPy not found.")
|
| 195 |
+
|
| 196 |
+
a = Symbol('a', real=True)
|
| 197 |
+
s = Symbol('s', integer=True)
|
| 198 |
+
body = [Return((sum_(a**2)/s)**.5)]
|
| 199 |
+
arr = array(a, dim=[s], intent='in')
|
| 200 |
+
fd = FunctionDefinition(real, 'rms', [arr, s], body, attrs=[bind_C('rms')])
|
| 201 |
+
f_mod = render_as_module([fd], 'mod_rms')
|
| 202 |
+
|
| 203 |
+
with tempfile.TemporaryDirectory() as folder:
|
| 204 |
+
mod, info = compile_link_import_strings([
|
| 205 |
+
('rms.f90', f_mod),
|
| 206 |
+
('_rms.pyx', (
|
| 207 |
+
"#cython: language_level={}\n".format("3") +
|
| 208 |
+
"cdef extern double rms(double*, int*)\n"
|
| 209 |
+
"def py_rms(double[::1] x):\n"
|
| 210 |
+
" cdef int s = x.size\n"
|
| 211 |
+
" return rms(&x[0], &s)\n"))
|
| 212 |
+
], build_dir=folder)
|
| 213 |
+
assert abs(mod.py_rms(np.array([2., 4., 2., 2.])) - 7**0.5) < 1e-14
|
pllava/lib/python3.10/site-packages/sympy/codegen/tests/test_matrix_nodes.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.symbol import symbols
|
| 2 |
+
from sympy.core.function import Function
|
| 3 |
+
from sympy.matrices.dense import Matrix
|
| 4 |
+
from sympy.matrices.dense import zeros
|
| 5 |
+
from sympy.simplify.simplify import simplify
|
| 6 |
+
from sympy.codegen.matrix_nodes import MatrixSolve
|
| 7 |
+
from sympy.utilities.lambdify import lambdify
|
| 8 |
+
from sympy.printing.numpy import NumPyPrinter
|
| 9 |
+
from sympy.testing.pytest import skip
|
| 10 |
+
from sympy.external import import_module
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def test_matrix_solve_issue_24862():
|
| 14 |
+
A = Matrix(3, 3, symbols('a:9'))
|
| 15 |
+
b = Matrix(3, 1, symbols('b:3'))
|
| 16 |
+
hash(MatrixSolve(A, b))
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def test_matrix_solve_derivative_exact():
|
| 20 |
+
q = symbols('q')
|
| 21 |
+
a11, a12, a21, a22, b1, b2 = (
|
| 22 |
+
f(q) for f in symbols('a11 a12 a21 a22 b1 b2', cls=Function))
|
| 23 |
+
A = Matrix([[a11, a12], [a21, a22]])
|
| 24 |
+
b = Matrix([b1, b2])
|
| 25 |
+
x_lu = A.LUsolve(b)
|
| 26 |
+
dxdq_lu = A.LUsolve(b.diff(q) - A.diff(q) * A.LUsolve(b))
|
| 27 |
+
assert simplify(x_lu.diff(q) - dxdq_lu) == zeros(2, 1)
|
| 28 |
+
# dxdq_ms is the MatrixSolve equivalent of dxdq_lu
|
| 29 |
+
dxdq_ms = MatrixSolve(A, b.diff(q) - A.diff(q) * MatrixSolve(A, b))
|
| 30 |
+
assert MatrixSolve(A, b).diff(q) == dxdq_ms
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def test_matrix_solve_derivative_numpy():
|
| 34 |
+
np = import_module('numpy')
|
| 35 |
+
if not np:
|
| 36 |
+
skip("numpy not installed.")
|
| 37 |
+
q = symbols('q')
|
| 38 |
+
a11, a12, a21, a22, b1, b2 = (
|
| 39 |
+
f(q) for f in symbols('a11 a12 a21 a22 b1 b2', cls=Function))
|
| 40 |
+
A = Matrix([[a11, a12], [a21, a22]])
|
| 41 |
+
b = Matrix([b1, b2])
|
| 42 |
+
dx_lu = A.LUsolve(b).diff(q)
|
| 43 |
+
subs = {a11.diff(q): 0.2, a12.diff(q): 0.3, a21.diff(q): 0.1,
|
| 44 |
+
a22.diff(q): 0.5, b1.diff(q): 0.4, b2.diff(q): 0.9,
|
| 45 |
+
a11: 1.3, a12: 0.5, a21: 1.2, a22: 4, b1: 6.2, b2: 3.5}
|
| 46 |
+
p, p_vals = zip(*subs.items())
|
| 47 |
+
dx_sm = MatrixSolve(A, b).diff(q)
|
| 48 |
+
np.testing.assert_allclose(
|
| 49 |
+
lambdify(p, dx_sm, printer=NumPyPrinter)(*p_vals),
|
| 50 |
+
lambdify(p, dx_lu, printer=NumPyPrinter)(*p_vals))
|
pllava/lib/python3.10/site-packages/sympy/codegen/tests/test_numpy_nodes.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from itertools import product
|
| 2 |
+
from sympy.core.singleton import S
|
| 3 |
+
from sympy.core.symbol import symbols
|
| 4 |
+
from sympy.functions.elementary.exponential import (exp, log)
|
| 5 |
+
from sympy.printing.repr import srepr
|
| 6 |
+
from sympy.codegen.numpy_nodes import logaddexp, logaddexp2
|
| 7 |
+
|
| 8 |
+
x, y, z = symbols('x y z')
|
| 9 |
+
|
| 10 |
+
def test_logaddexp():
|
| 11 |
+
lae_xy = logaddexp(x, y)
|
| 12 |
+
ref_xy = log(exp(x) + exp(y))
|
| 13 |
+
for wrt, deriv_order in product([x, y, z], range(3)):
|
| 14 |
+
assert (
|
| 15 |
+
lae_xy.diff(wrt, deriv_order) -
|
| 16 |
+
ref_xy.diff(wrt, deriv_order)
|
| 17 |
+
).rewrite(log).simplify() == 0
|
| 18 |
+
|
| 19 |
+
one_third_e = 1*exp(1)/3
|
| 20 |
+
two_thirds_e = 2*exp(1)/3
|
| 21 |
+
logThirdE = log(one_third_e)
|
| 22 |
+
logTwoThirdsE = log(two_thirds_e)
|
| 23 |
+
lae_sum_to_e = logaddexp(logThirdE, logTwoThirdsE)
|
| 24 |
+
assert lae_sum_to_e.rewrite(log) == 1
|
| 25 |
+
assert lae_sum_to_e.simplify() == 1
|
| 26 |
+
was = logaddexp(2, 3)
|
| 27 |
+
assert srepr(was) == srepr(was.simplify()) # cannot simplify with 2, 3
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def test_logaddexp2():
|
| 31 |
+
lae2_xy = logaddexp2(x, y)
|
| 32 |
+
ref2_xy = log(2**x + 2**y)/log(2)
|
| 33 |
+
for wrt, deriv_order in product([x, y, z], range(3)):
|
| 34 |
+
assert (
|
| 35 |
+
lae2_xy.diff(wrt, deriv_order) -
|
| 36 |
+
ref2_xy.diff(wrt, deriv_order)
|
| 37 |
+
).rewrite(log).cancel() == 0
|
| 38 |
+
|
| 39 |
+
def lb(x):
|
| 40 |
+
return log(x)/log(2)
|
| 41 |
+
|
| 42 |
+
two_thirds = S.One*2/3
|
| 43 |
+
four_thirds = 2*two_thirds
|
| 44 |
+
lbTwoThirds = lb(two_thirds)
|
| 45 |
+
lbFourThirds = lb(four_thirds)
|
| 46 |
+
lae2_sum_to_2 = logaddexp2(lbTwoThirds, lbFourThirds)
|
| 47 |
+
assert lae2_sum_to_2.rewrite(log) == 1
|
| 48 |
+
assert lae2_sum_to_2.simplify() == 1
|
| 49 |
+
was = logaddexp2(x, y)
|
| 50 |
+
assert srepr(was) == srepr(was.simplify()) # cannot simplify with x, y
|
pllava/lib/python3.10/site-packages/sympy/codegen/tests/test_pynodes.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.symbol import symbols
|
| 2 |
+
from sympy.codegen.pynodes import List
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def test_List():
|
| 6 |
+
l = List(2, 3, 4)
|
| 7 |
+
assert l == List(2, 3, 4)
|
| 8 |
+
assert str(l) == "[2, 3, 4]"
|
| 9 |
+
x, y, z = symbols('x y z')
|
| 10 |
+
l = List(x**2,y**3,z**4)
|
| 11 |
+
# contrary to python's built-in list, we can call e.g. "replace" on List.
|
| 12 |
+
m = l.replace(lambda arg: arg.is_Pow and arg.exp>2, lambda p: p.base-p.exp)
|
| 13 |
+
assert m == [x**2, y-3, z-4]
|
pllava/lib/python3.10/site-packages/sympy/codegen/tests/test_pyutils.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.codegen.ast import Print
|
| 2 |
+
from sympy.codegen.pyutils import render_as_module
|
| 3 |
+
|
| 4 |
+
def test_standard():
|
| 5 |
+
ast = Print('x y'.split(), r"coordinate: %12.5g %12.5g\n")
|
| 6 |
+
assert render_as_module(ast, standard='python3') == \
|
| 7 |
+
'\n\nprint("coordinate: %12.5g %12.5g\\n" % (x, y), end="")'
|
pllava/lib/python3.10/site-packages/sympy/codegen/tests/test_rewriting.py
ADDED
|
@@ -0,0 +1,479 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import tempfile
|
| 2 |
+
from sympy.core.numbers import pi, Rational
|
| 3 |
+
from sympy.core.power import Pow
|
| 4 |
+
from sympy.core.singleton import S
|
| 5 |
+
from sympy.core.symbol import Symbol
|
| 6 |
+
from sympy.functions.elementary.complexes import Abs
|
| 7 |
+
from sympy.functions.elementary.exponential import (exp, log)
|
| 8 |
+
from sympy.functions.elementary.trigonometric import (cos, sin, sinc)
|
| 9 |
+
from sympy.matrices.expressions.matexpr import MatrixSymbol
|
| 10 |
+
from sympy.assumptions import assuming, Q
|
| 11 |
+
from sympy.external import import_module
|
| 12 |
+
from sympy.printing.codeprinter import ccode
|
| 13 |
+
from sympy.codegen.matrix_nodes import MatrixSolve
|
| 14 |
+
from sympy.codegen.cfunctions import log2, exp2, expm1, log1p
|
| 15 |
+
from sympy.codegen.numpy_nodes import logaddexp, logaddexp2
|
| 16 |
+
from sympy.codegen.scipy_nodes import cosm1, powm1
|
| 17 |
+
from sympy.codegen.rewriting import (
|
| 18 |
+
optimize, cosm1_opt, log2_opt, exp2_opt, expm1_opt, log1p_opt, powm1_opt, optims_c99,
|
| 19 |
+
create_expand_pow_optimization, matinv_opt, logaddexp_opt, logaddexp2_opt,
|
| 20 |
+
optims_numpy, optims_scipy, sinc_opts, FuncMinusOneOptim
|
| 21 |
+
)
|
| 22 |
+
from sympy.testing.pytest import XFAIL, skip
|
| 23 |
+
from sympy.utilities import lambdify
|
| 24 |
+
from sympy.utilities._compilation import compile_link_import_strings, has_c
|
| 25 |
+
from sympy.utilities._compilation.util import may_xfail
|
| 26 |
+
|
| 27 |
+
cython = import_module('cython')
|
| 28 |
+
numpy = import_module('numpy')
|
| 29 |
+
scipy = import_module('scipy')
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def test_log2_opt():
|
| 33 |
+
x = Symbol('x')
|
| 34 |
+
expr1 = 7*log(3*x + 5)/(log(2))
|
| 35 |
+
opt1 = optimize(expr1, [log2_opt])
|
| 36 |
+
assert opt1 == 7*log2(3*x + 5)
|
| 37 |
+
assert opt1.rewrite(log) == expr1
|
| 38 |
+
|
| 39 |
+
expr2 = 3*log(5*x + 7)/(13*log(2))
|
| 40 |
+
opt2 = optimize(expr2, [log2_opt])
|
| 41 |
+
assert opt2 == 3*log2(5*x + 7)/13
|
| 42 |
+
assert opt2.rewrite(log) == expr2
|
| 43 |
+
|
| 44 |
+
expr3 = log(x)/log(2)
|
| 45 |
+
opt3 = optimize(expr3, [log2_opt])
|
| 46 |
+
assert opt3 == log2(x)
|
| 47 |
+
assert opt3.rewrite(log) == expr3
|
| 48 |
+
|
| 49 |
+
expr4 = log(x)/log(2) + log(x+1)
|
| 50 |
+
opt4 = optimize(expr4, [log2_opt])
|
| 51 |
+
assert opt4 == log2(x) + log(2)*log2(x+1)
|
| 52 |
+
assert opt4.rewrite(log) == expr4
|
| 53 |
+
|
| 54 |
+
expr5 = log(17)
|
| 55 |
+
opt5 = optimize(expr5, [log2_opt])
|
| 56 |
+
assert opt5 == expr5
|
| 57 |
+
|
| 58 |
+
expr6 = log(x + 3)/log(2)
|
| 59 |
+
opt6 = optimize(expr6, [log2_opt])
|
| 60 |
+
assert str(opt6) == 'log2(x + 3)'
|
| 61 |
+
assert opt6.rewrite(log) == expr6
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def test_exp2_opt():
|
| 65 |
+
x = Symbol('x')
|
| 66 |
+
expr1 = 1 + 2**x
|
| 67 |
+
opt1 = optimize(expr1, [exp2_opt])
|
| 68 |
+
assert opt1 == 1 + exp2(x)
|
| 69 |
+
assert opt1.rewrite(Pow) == expr1
|
| 70 |
+
|
| 71 |
+
expr2 = 1 + 3**x
|
| 72 |
+
assert expr2 == optimize(expr2, [exp2_opt])
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def test_expm1_opt():
|
| 76 |
+
x = Symbol('x')
|
| 77 |
+
|
| 78 |
+
expr1 = exp(x) - 1
|
| 79 |
+
opt1 = optimize(expr1, [expm1_opt])
|
| 80 |
+
assert expm1(x) - opt1 == 0
|
| 81 |
+
assert opt1.rewrite(exp) == expr1
|
| 82 |
+
|
| 83 |
+
expr2 = 3*exp(x) - 3
|
| 84 |
+
opt2 = optimize(expr2, [expm1_opt])
|
| 85 |
+
assert 3*expm1(x) == opt2
|
| 86 |
+
assert opt2.rewrite(exp) == expr2
|
| 87 |
+
|
| 88 |
+
expr3 = 3*exp(x) - 5
|
| 89 |
+
opt3 = optimize(expr3, [expm1_opt])
|
| 90 |
+
assert 3*expm1(x) - 2 == opt3
|
| 91 |
+
assert opt3.rewrite(exp) == expr3
|
| 92 |
+
expm1_opt_non_opportunistic = FuncMinusOneOptim(exp, expm1, opportunistic=False)
|
| 93 |
+
assert expr3 == optimize(expr3, [expm1_opt_non_opportunistic])
|
| 94 |
+
assert opt1 == optimize(expr1, [expm1_opt_non_opportunistic])
|
| 95 |
+
assert opt2 == optimize(expr2, [expm1_opt_non_opportunistic])
|
| 96 |
+
|
| 97 |
+
expr4 = 3*exp(x) + log(x) - 3
|
| 98 |
+
opt4 = optimize(expr4, [expm1_opt])
|
| 99 |
+
assert 3*expm1(x) + log(x) == opt4
|
| 100 |
+
assert opt4.rewrite(exp) == expr4
|
| 101 |
+
|
| 102 |
+
expr5 = 3*exp(2*x) - 3
|
| 103 |
+
opt5 = optimize(expr5, [expm1_opt])
|
| 104 |
+
assert 3*expm1(2*x) == opt5
|
| 105 |
+
assert opt5.rewrite(exp) == expr5
|
| 106 |
+
|
| 107 |
+
expr6 = (2*exp(x) + 1)/(exp(x) + 1) + 1
|
| 108 |
+
opt6 = optimize(expr6, [expm1_opt])
|
| 109 |
+
assert opt6.count_ops() <= expr6.count_ops()
|
| 110 |
+
|
| 111 |
+
def ev(e):
|
| 112 |
+
return e.subs(x, 3).evalf()
|
| 113 |
+
assert abs(ev(expr6) - ev(opt6)) < 1e-15
|
| 114 |
+
|
| 115 |
+
y = Symbol('y')
|
| 116 |
+
expr7 = (2*exp(x) - 1)/(1 - exp(y)) - 1/(1-exp(y))
|
| 117 |
+
opt7 = optimize(expr7, [expm1_opt])
|
| 118 |
+
assert -2*expm1(x)/expm1(y) == opt7
|
| 119 |
+
assert (opt7.rewrite(exp) - expr7).factor() == 0
|
| 120 |
+
|
| 121 |
+
expr8 = (1+exp(x))**2 - 4
|
| 122 |
+
opt8 = optimize(expr8, [expm1_opt])
|
| 123 |
+
tgt8a = (exp(x) + 3)*expm1(x)
|
| 124 |
+
tgt8b = 2*expm1(x) + expm1(2*x)
|
| 125 |
+
# Both tgt8a & tgt8b seem to give full precision (~16 digits for double)
|
| 126 |
+
# for x=1e-7 (compare with expr8 which only achieves ~8 significant digits).
|
| 127 |
+
# If we can show that either tgt8a or tgt8b is preferable, we can
|
| 128 |
+
# change this test to ensure the preferable version is returned.
|
| 129 |
+
assert (tgt8a - tgt8b).rewrite(exp).factor() == 0
|
| 130 |
+
assert opt8 in (tgt8a, tgt8b)
|
| 131 |
+
assert (opt8.rewrite(exp) - expr8).factor() == 0
|
| 132 |
+
|
| 133 |
+
expr9 = sin(expr8)
|
| 134 |
+
opt9 = optimize(expr9, [expm1_opt])
|
| 135 |
+
tgt9a = sin(tgt8a)
|
| 136 |
+
tgt9b = sin(tgt8b)
|
| 137 |
+
assert opt9 in (tgt9a, tgt9b)
|
| 138 |
+
assert (opt9.rewrite(exp) - expr9.rewrite(exp)).factor().is_zero
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def test_expm1_two_exp_terms():
|
| 142 |
+
x, y = map(Symbol, 'x y'.split())
|
| 143 |
+
expr1 = exp(x) + exp(y) - 2
|
| 144 |
+
opt1 = optimize(expr1, [expm1_opt])
|
| 145 |
+
assert opt1 == expm1(x) + expm1(y)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def test_cosm1_opt():
|
| 149 |
+
x = Symbol('x')
|
| 150 |
+
|
| 151 |
+
expr1 = cos(x) - 1
|
| 152 |
+
opt1 = optimize(expr1, [cosm1_opt])
|
| 153 |
+
assert cosm1(x) - opt1 == 0
|
| 154 |
+
assert opt1.rewrite(cos) == expr1
|
| 155 |
+
|
| 156 |
+
expr2 = 3*cos(x) - 3
|
| 157 |
+
opt2 = optimize(expr2, [cosm1_opt])
|
| 158 |
+
assert 3*cosm1(x) == opt2
|
| 159 |
+
assert opt2.rewrite(cos) == expr2
|
| 160 |
+
|
| 161 |
+
expr3 = 3*cos(x) - 5
|
| 162 |
+
opt3 = optimize(expr3, [cosm1_opt])
|
| 163 |
+
assert 3*cosm1(x) - 2 == opt3
|
| 164 |
+
assert opt3.rewrite(cos) == expr3
|
| 165 |
+
cosm1_opt_non_opportunistic = FuncMinusOneOptim(cos, cosm1, opportunistic=False)
|
| 166 |
+
assert expr3 == optimize(expr3, [cosm1_opt_non_opportunistic])
|
| 167 |
+
assert opt1 == optimize(expr1, [cosm1_opt_non_opportunistic])
|
| 168 |
+
assert opt2 == optimize(expr2, [cosm1_opt_non_opportunistic])
|
| 169 |
+
|
| 170 |
+
expr4 = 3*cos(x) + log(x) - 3
|
| 171 |
+
opt4 = optimize(expr4, [cosm1_opt])
|
| 172 |
+
assert 3*cosm1(x) + log(x) == opt4
|
| 173 |
+
assert opt4.rewrite(cos) == expr4
|
| 174 |
+
|
| 175 |
+
expr5 = 3*cos(2*x) - 3
|
| 176 |
+
opt5 = optimize(expr5, [cosm1_opt])
|
| 177 |
+
assert 3*cosm1(2*x) == opt5
|
| 178 |
+
assert opt5.rewrite(cos) == expr5
|
| 179 |
+
|
| 180 |
+
expr6 = 2 - 2*cos(x)
|
| 181 |
+
opt6 = optimize(expr6, [cosm1_opt])
|
| 182 |
+
assert -2*cosm1(x) == opt6
|
| 183 |
+
assert opt6.rewrite(cos) == expr6
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def test_cosm1_two_cos_terms():
|
| 187 |
+
x, y = map(Symbol, 'x y'.split())
|
| 188 |
+
expr1 = cos(x) + cos(y) - 2
|
| 189 |
+
opt1 = optimize(expr1, [cosm1_opt])
|
| 190 |
+
assert opt1 == cosm1(x) + cosm1(y)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def test_expm1_cosm1_mixed():
|
| 194 |
+
x = Symbol('x')
|
| 195 |
+
expr1 = exp(x) + cos(x) - 2
|
| 196 |
+
opt1 = optimize(expr1, [expm1_opt, cosm1_opt])
|
| 197 |
+
assert opt1 == cosm1(x) + expm1(x)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def _check_num_lambdify(expr, opt, val_subs, approx_ref, lambdify_kw=None, poorness=1e10):
|
| 201 |
+
""" poorness=1e10 signifies that `expr` loses precision of at least ten decimal digits. """
|
| 202 |
+
num_ref = expr.subs(val_subs).evalf()
|
| 203 |
+
eps = numpy.finfo(numpy.float64).eps
|
| 204 |
+
assert abs(num_ref - approx_ref) < approx_ref*eps
|
| 205 |
+
f1 = lambdify(list(val_subs.keys()), opt, **(lambdify_kw or {}))
|
| 206 |
+
args_float = tuple(map(float, val_subs.values()))
|
| 207 |
+
num_err1 = abs(f1(*args_float) - approx_ref)
|
| 208 |
+
assert num_err1 < abs(num_ref*eps)
|
| 209 |
+
f2 = lambdify(list(val_subs.keys()), expr, **(lambdify_kw or {}))
|
| 210 |
+
num_err2 = abs(f2(*args_float) - approx_ref)
|
| 211 |
+
assert num_err2 > abs(num_ref*eps*poorness) # this only ensures that the *test* works as intended
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def test_cosm1_apart():
|
| 215 |
+
x = Symbol('x')
|
| 216 |
+
|
| 217 |
+
expr1 = 1/cos(x) - 1
|
| 218 |
+
opt1 = optimize(expr1, [cosm1_opt])
|
| 219 |
+
assert opt1 == -cosm1(x)/cos(x)
|
| 220 |
+
if scipy:
|
| 221 |
+
_check_num_lambdify(expr1, opt1, {x: S(10)**-30}, 5e-61, lambdify_kw={"modules": 'scipy'})
|
| 222 |
+
|
| 223 |
+
expr2 = 2/cos(x) - 2
|
| 224 |
+
opt2 = optimize(expr2, optims_scipy)
|
| 225 |
+
assert opt2 == -2*cosm1(x)/cos(x)
|
| 226 |
+
if scipy:
|
| 227 |
+
_check_num_lambdify(expr2, opt2, {x: S(10)**-30}, 1e-60, lambdify_kw={"modules": 'scipy'})
|
| 228 |
+
|
| 229 |
+
expr3 = pi/cos(3*x) - pi
|
| 230 |
+
opt3 = optimize(expr3, [cosm1_opt])
|
| 231 |
+
assert opt3 == -pi*cosm1(3*x)/cos(3*x)
|
| 232 |
+
if scipy:
|
| 233 |
+
_check_num_lambdify(expr3, opt3, {x: S(10)**-30/3}, float(5e-61*pi), lambdify_kw={"modules": 'scipy'})
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def test_powm1():
|
| 237 |
+
args = x, y = map(Symbol, "xy")
|
| 238 |
+
|
| 239 |
+
expr1 = x**y - 1
|
| 240 |
+
opt1 = optimize(expr1, [powm1_opt])
|
| 241 |
+
assert opt1 == powm1(x, y)
|
| 242 |
+
for arg in args:
|
| 243 |
+
assert expr1.diff(arg) == opt1.diff(arg)
|
| 244 |
+
if scipy and tuple(map(int, scipy.version.version.split('.')[:3])) >= (1, 10, 0):
|
| 245 |
+
subs1_a = {x: Rational(*(1.0+1e-13).as_integer_ratio()), y: pi}
|
| 246 |
+
ref1_f64_a = 3.139081648208105e-13
|
| 247 |
+
_check_num_lambdify(expr1, opt1, subs1_a, ref1_f64_a, lambdify_kw={"modules": 'scipy'}, poorness=10**11)
|
| 248 |
+
|
| 249 |
+
subs1_b = {x: pi, y: Rational(*(1e-10).as_integer_ratio())}
|
| 250 |
+
ref1_f64_b = 1.1447298859149205e-10
|
| 251 |
+
_check_num_lambdify(expr1, opt1, subs1_b, ref1_f64_b, lambdify_kw={"modules": 'scipy'}, poorness=10**9)
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
def test_log1p_opt():
|
| 255 |
+
x = Symbol('x')
|
| 256 |
+
expr1 = log(x + 1)
|
| 257 |
+
opt1 = optimize(expr1, [log1p_opt])
|
| 258 |
+
assert log1p(x) - opt1 == 0
|
| 259 |
+
assert opt1.rewrite(log) == expr1
|
| 260 |
+
|
| 261 |
+
expr2 = log(3*x + 3)
|
| 262 |
+
opt2 = optimize(expr2, [log1p_opt])
|
| 263 |
+
assert log1p(x) + log(3) == opt2
|
| 264 |
+
assert (opt2.rewrite(log) - expr2).simplify() == 0
|
| 265 |
+
|
| 266 |
+
expr3 = log(2*x + 1)
|
| 267 |
+
opt3 = optimize(expr3, [log1p_opt])
|
| 268 |
+
assert log1p(2*x) - opt3 == 0
|
| 269 |
+
assert opt3.rewrite(log) == expr3
|
| 270 |
+
|
| 271 |
+
expr4 = log(x+3)
|
| 272 |
+
opt4 = optimize(expr4, [log1p_opt])
|
| 273 |
+
assert str(opt4) == 'log(x + 3)'
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def test_optims_c99():
|
| 277 |
+
x = Symbol('x')
|
| 278 |
+
|
| 279 |
+
expr1 = 2**x + log(x)/log(2) + log(x + 1) + exp(x) - 1
|
| 280 |
+
opt1 = optimize(expr1, optims_c99).simplify()
|
| 281 |
+
assert opt1 == exp2(x) + log2(x) + log1p(x) + expm1(x)
|
| 282 |
+
assert opt1.rewrite(exp).rewrite(log).rewrite(Pow) == expr1
|
| 283 |
+
|
| 284 |
+
expr2 = log(x)/log(2) + log(x + 1)
|
| 285 |
+
opt2 = optimize(expr2, optims_c99)
|
| 286 |
+
assert opt2 == log2(x) + log1p(x)
|
| 287 |
+
assert opt2.rewrite(log) == expr2
|
| 288 |
+
|
| 289 |
+
expr3 = log(x)/log(2) + log(17*x + 17)
|
| 290 |
+
opt3 = optimize(expr3, optims_c99)
|
| 291 |
+
delta3 = opt3 - (log2(x) + log(17) + log1p(x))
|
| 292 |
+
assert delta3 == 0
|
| 293 |
+
assert (opt3.rewrite(log) - expr3).simplify() == 0
|
| 294 |
+
|
| 295 |
+
expr4 = 2**x + 3*log(5*x + 7)/(13*log(2)) + 11*exp(x) - 11 + log(17*x + 17)
|
| 296 |
+
opt4 = optimize(expr4, optims_c99).simplify()
|
| 297 |
+
delta4 = opt4 - (exp2(x) + 3*log2(5*x + 7)/13 + 11*expm1(x) + log(17) + log1p(x))
|
| 298 |
+
assert delta4 == 0
|
| 299 |
+
assert (opt4.rewrite(exp).rewrite(log).rewrite(Pow) - expr4).simplify() == 0
|
| 300 |
+
|
| 301 |
+
expr5 = 3*exp(2*x) - 3
|
| 302 |
+
opt5 = optimize(expr5, optims_c99)
|
| 303 |
+
delta5 = opt5 - 3*expm1(2*x)
|
| 304 |
+
assert delta5 == 0
|
| 305 |
+
assert opt5.rewrite(exp) == expr5
|
| 306 |
+
|
| 307 |
+
expr6 = exp(2*x) - 3
|
| 308 |
+
opt6 = optimize(expr6, optims_c99)
|
| 309 |
+
assert opt6 in (expm1(2*x) - 2, expr6) # expm1(2*x) - 2 is not better or worse
|
| 310 |
+
|
| 311 |
+
expr7 = log(3*x + 3)
|
| 312 |
+
opt7 = optimize(expr7, optims_c99)
|
| 313 |
+
delta7 = opt7 - (log(3) + log1p(x))
|
| 314 |
+
assert delta7 == 0
|
| 315 |
+
assert (opt7.rewrite(log) - expr7).simplify() == 0
|
| 316 |
+
|
| 317 |
+
expr8 = log(2*x + 3)
|
| 318 |
+
opt8 = optimize(expr8, optims_c99)
|
| 319 |
+
assert opt8 == expr8
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def test_create_expand_pow_optimization():
|
| 323 |
+
cc = lambda x: ccode(
|
| 324 |
+
optimize(x, [create_expand_pow_optimization(4)]))
|
| 325 |
+
x = Symbol('x')
|
| 326 |
+
assert cc(x**4) == 'x*x*x*x'
|
| 327 |
+
assert cc(x**4 + x**2) == 'x*x + x*x*x*x'
|
| 328 |
+
assert cc(x**5 + x**4) == 'pow(x, 5) + x*x*x*x'
|
| 329 |
+
assert cc(sin(x)**4) == 'pow(sin(x), 4)'
|
| 330 |
+
# gh issue 15335
|
| 331 |
+
assert cc(x**(-4)) == '1.0/(x*x*x*x)'
|
| 332 |
+
assert cc(x**(-5)) == 'pow(x, -5)'
|
| 333 |
+
assert cc(-x**4) == '-(x*x*x*x)'
|
| 334 |
+
assert cc(x**4 - x**2) == '-(x*x) + x*x*x*x'
|
| 335 |
+
i = Symbol('i', integer=True)
|
| 336 |
+
assert cc(x**i - x**2) == 'pow(x, i) - (x*x)'
|
| 337 |
+
y = Symbol('y', real=True)
|
| 338 |
+
assert cc(Abs(exp(y**4))) == "exp(y*y*y*y)"
|
| 339 |
+
|
| 340 |
+
# gh issue 20753
|
| 341 |
+
cc2 = lambda x: ccode(optimize(x, [create_expand_pow_optimization(
|
| 342 |
+
4, base_req=lambda b: b.is_Function)]))
|
| 343 |
+
assert cc2(x**3 + sin(x)**3) == "pow(x, 3) + sin(x)*sin(x)*sin(x)"
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
def test_matsolve():
|
| 347 |
+
n = Symbol('n', integer=True)
|
| 348 |
+
A = MatrixSymbol('A', n, n)
|
| 349 |
+
x = MatrixSymbol('x', n, 1)
|
| 350 |
+
|
| 351 |
+
with assuming(Q.fullrank(A)):
|
| 352 |
+
assert optimize(A**(-1) * x, [matinv_opt]) == MatrixSolve(A, x)
|
| 353 |
+
assert optimize(A**(-1) * x + x, [matinv_opt]) == MatrixSolve(A, x) + x
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
def test_logaddexp_opt():
|
| 357 |
+
x, y = map(Symbol, 'x y'.split())
|
| 358 |
+
expr1 = log(exp(x) + exp(y))
|
| 359 |
+
opt1 = optimize(expr1, [logaddexp_opt])
|
| 360 |
+
assert logaddexp(x, y) - opt1 == 0
|
| 361 |
+
assert logaddexp(y, x) - opt1 == 0
|
| 362 |
+
assert opt1.rewrite(log) == expr1
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
def test_logaddexp2_opt():
|
| 366 |
+
x, y = map(Symbol, 'x y'.split())
|
| 367 |
+
expr1 = log(2**x + 2**y)/log(2)
|
| 368 |
+
opt1 = optimize(expr1, [logaddexp2_opt])
|
| 369 |
+
assert logaddexp2(x, y) - opt1 == 0
|
| 370 |
+
assert logaddexp2(y, x) - opt1 == 0
|
| 371 |
+
assert opt1.rewrite(log) == expr1
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
def test_sinc_opts():
|
| 375 |
+
def check(d):
|
| 376 |
+
for k, v in d.items():
|
| 377 |
+
assert optimize(k, sinc_opts) == v
|
| 378 |
+
|
| 379 |
+
x = Symbol('x')
|
| 380 |
+
check({
|
| 381 |
+
sin(x)/x : sinc(x),
|
| 382 |
+
sin(2*x)/(2*x) : sinc(2*x),
|
| 383 |
+
sin(3*x)/x : 3*sinc(3*x),
|
| 384 |
+
x*sin(x) : x*sin(x)
|
| 385 |
+
})
|
| 386 |
+
|
| 387 |
+
y = Symbol('y')
|
| 388 |
+
check({
|
| 389 |
+
sin(x*y)/(x*y) : sinc(x*y),
|
| 390 |
+
y*sin(x/y)/x : sinc(x/y),
|
| 391 |
+
sin(sin(x))/sin(x) : sinc(sin(x)),
|
| 392 |
+
sin(3*sin(x))/sin(x) : 3*sinc(3*sin(x)),
|
| 393 |
+
sin(x)/y : sin(x)/y
|
| 394 |
+
})
|
| 395 |
+
|
| 396 |
+
|
| 397 |
+
def test_optims_numpy():
|
| 398 |
+
def check(d):
|
| 399 |
+
for k, v in d.items():
|
| 400 |
+
assert optimize(k, optims_numpy) == v
|
| 401 |
+
|
| 402 |
+
x = Symbol('x')
|
| 403 |
+
check({
|
| 404 |
+
sin(2*x)/(2*x) + exp(2*x) - 1: sinc(2*x) + expm1(2*x),
|
| 405 |
+
log(x+3)/log(2) + log(x**2 + 1): log1p(x**2) + log2(x+3)
|
| 406 |
+
})
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
@XFAIL # room for improvement, ideally this test case should pass.
|
| 410 |
+
def test_optims_numpy_TODO():
|
| 411 |
+
def check(d):
|
| 412 |
+
for k, v in d.items():
|
| 413 |
+
assert optimize(k, optims_numpy) == v
|
| 414 |
+
|
| 415 |
+
x, y = map(Symbol, 'x y'.split())
|
| 416 |
+
check({
|
| 417 |
+
log(x*y)*sin(x*y)*log(x*y+1)/(log(2)*x*y): log2(x*y)*sinc(x*y)*log1p(x*y),
|
| 418 |
+
exp(x*sin(y)/y) - 1: expm1(x*sinc(y))
|
| 419 |
+
})
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
@may_xfail
|
| 423 |
+
def test_compiled_ccode_with_rewriting():
|
| 424 |
+
if not cython:
|
| 425 |
+
skip("cython not installed.")
|
| 426 |
+
if not has_c():
|
| 427 |
+
skip("No C compiler found.")
|
| 428 |
+
|
| 429 |
+
x = Symbol('x')
|
| 430 |
+
about_two = 2**(58/S(117))*3**(97/S(117))*5**(4/S(39))*7**(92/S(117))/S(30)*pi
|
| 431 |
+
# about_two: 1.999999999999581826
|
| 432 |
+
unchanged = 2*exp(x) - about_two
|
| 433 |
+
xval = S(10)**-11
|
| 434 |
+
ref = unchanged.subs(x, xval).n(19) # 2.0418173913673213e-11
|
| 435 |
+
|
| 436 |
+
rewritten = optimize(2*exp(x) - about_two, [expm1_opt])
|
| 437 |
+
|
| 438 |
+
# Unfortunately, we need to call ``.n()`` on our expressions before we hand them
|
| 439 |
+
# to ``ccode``, and we need to request a large number of significant digits.
|
| 440 |
+
# In this test, results converged for double precision when the following number
|
| 441 |
+
# of significant digits were chosen:
|
| 442 |
+
NUMBER_OF_DIGITS = 25 # TODO: this should ideally be automatically handled.
|
| 443 |
+
|
| 444 |
+
func_c = '''
|
| 445 |
+
#include <math.h>
|
| 446 |
+
|
| 447 |
+
double func_unchanged(double x) {
|
| 448 |
+
return %(unchanged)s;
|
| 449 |
+
}
|
| 450 |
+
double func_rewritten(double x) {
|
| 451 |
+
return %(rewritten)s;
|
| 452 |
+
}
|
| 453 |
+
''' % {"unchanged": ccode(unchanged.n(NUMBER_OF_DIGITS)),
|
| 454 |
+
"rewritten": ccode(rewritten.n(NUMBER_OF_DIGITS))}
|
| 455 |
+
|
| 456 |
+
func_pyx = '''
|
| 457 |
+
#cython: language_level=3
|
| 458 |
+
cdef extern double func_unchanged(double)
|
| 459 |
+
cdef extern double func_rewritten(double)
|
| 460 |
+
def py_unchanged(x):
|
| 461 |
+
return func_unchanged(x)
|
| 462 |
+
def py_rewritten(x):
|
| 463 |
+
return func_rewritten(x)
|
| 464 |
+
'''
|
| 465 |
+
with tempfile.TemporaryDirectory() as folder:
|
| 466 |
+
mod, info = compile_link_import_strings(
|
| 467 |
+
[('func.c', func_c), ('_func.pyx', func_pyx)],
|
| 468 |
+
build_dir=folder, compile_kwargs={"std": 'c99'}
|
| 469 |
+
)
|
| 470 |
+
err_rewritten = abs(mod.py_rewritten(1e-11) - ref)
|
| 471 |
+
err_unchanged = abs(mod.py_unchanged(1e-11) - ref)
|
| 472 |
+
assert 1e-27 < err_rewritten < 1e-25 # highly accurate.
|
| 473 |
+
assert 1e-19 < err_unchanged < 1e-16 # quite poor.
|
| 474 |
+
|
| 475 |
+
# Tolerances used above were determined as follows:
|
| 476 |
+
# >>> no_opt = unchanged.subs(x, xval.evalf()).evalf()
|
| 477 |
+
# >>> with_opt = rewritten.n(25).subs(x, 1e-11).evalf()
|
| 478 |
+
# >>> with_opt - ref, no_opt - ref
|
| 479 |
+
# (1.1536301877952077e-26, 1.6547074214222335e-18)
|
pllava/lib/python3.10/site-packages/sympy/codegen/tests/test_scipy_nodes.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from itertools import product
|
| 2 |
+
from sympy.core.power import Pow
|
| 3 |
+
from sympy.core.symbol import symbols
|
| 4 |
+
from sympy.functions.elementary.exponential import exp, log
|
| 5 |
+
from sympy.functions.elementary.trigonometric import cos
|
| 6 |
+
from sympy.core.numbers import pi
|
| 7 |
+
from sympy.codegen.scipy_nodes import cosm1, powm1
|
| 8 |
+
|
| 9 |
+
x, y, z = symbols('x y z')
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def test_cosm1():
|
| 13 |
+
cm1_xy = cosm1(x*y)
|
| 14 |
+
ref_xy = cos(x*y) - 1
|
| 15 |
+
for wrt, deriv_order in product([x, y, z], range(3)):
|
| 16 |
+
assert (
|
| 17 |
+
cm1_xy.diff(wrt, deriv_order) -
|
| 18 |
+
ref_xy.diff(wrt, deriv_order)
|
| 19 |
+
).rewrite(cos).simplify() == 0
|
| 20 |
+
|
| 21 |
+
expr_minus2 = cosm1(pi)
|
| 22 |
+
assert expr_minus2.rewrite(cos) == -2
|
| 23 |
+
assert cosm1(3.14).simplify() == cosm1(3.14) # cannot simplify with 3.14
|
| 24 |
+
assert cosm1(pi/2).simplify() == -1
|
| 25 |
+
assert (1/cos(x) - 1 + cosm1(x)/cos(x)).simplify() == 0
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def test_powm1():
|
| 29 |
+
cases = {
|
| 30 |
+
powm1(x, y): x**y - 1,
|
| 31 |
+
powm1(x*y, z): (x*y)**z - 1,
|
| 32 |
+
powm1(x, y*z): x**(y*z)-1,
|
| 33 |
+
powm1(x*y*z, x*y*z): (x*y*z)**(x*y*z)-1
|
| 34 |
+
}
|
| 35 |
+
for pm1_e, ref_e in cases.items():
|
| 36 |
+
for wrt, deriv_order in product([x, y, z], range(3)):
|
| 37 |
+
der = pm1_e.diff(wrt, deriv_order)
|
| 38 |
+
ref = ref_e.diff(wrt, deriv_order)
|
| 39 |
+
delta = (der - ref).rewrite(Pow)
|
| 40 |
+
assert delta.simplify() == 0
|
| 41 |
+
|
| 42 |
+
eulers_constant_m1 = powm1(x, 1/log(x))
|
| 43 |
+
assert eulers_constant_m1.rewrite(Pow) == exp(1) - 1
|
| 44 |
+
assert eulers_constant_m1.simplify() == exp(1) - 1
|
pllava/lib/python3.10/site-packages/sympy/functions/combinatorial/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (181 Bytes). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/functions/combinatorial/__pycache__/numbers.cpython-310.pyc
ADDED
|
Binary file (92.7 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/__pycache__/test_comb_factorials.cpython-310.pyc
ADDED
|
Binary file (22.1 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/functions/special/__pycache__/bessel.cpython-310.pyc
ADDED
|
Binary file (58.7 kB). View file
|
|
|