Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +1 -0
- evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Almaty +0 -0
- evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Barnaul +0 -0
- evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Beirut +0 -0
- evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Calcutta +0 -0
- evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Choibalsan +0 -0
- evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Chongqing +0 -0
- evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Chungking +0 -0
- evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Colombo +0 -0
- evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Dili +0 -0
- evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Jakarta +0 -0
- evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Kolkata +0 -0
- evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Novokuznetsk +0 -0
- evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Saigon +0 -0
- evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Samarkand +0 -0
- evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Shanghai +0 -0
- evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Tbilisi +0 -0
- evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Tel_Aviv +0 -0
- evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Thimbu +0 -0
- evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Tomsk +0 -0
- evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Vladivostok +0 -0
- evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Yakutsk +0 -0
- evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Yangon +0 -0
- evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Yekaterinburg +0 -0
- evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/CST6CDT +0 -0
- evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Factory +0 -0
- evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Kwajalein +0 -0
- evalkit_tf446/lib/python3.10/site-packages/sympy/codegen/__init__.py +24 -0
- evalkit_tf446/lib/python3.10/site-packages/sympy/codegen/algorithms.py +180 -0
- evalkit_tf446/lib/python3.10/site-packages/sympy/codegen/approximations.py +187 -0
- evalkit_tf446/lib/python3.10/site-packages/sympy/codegen/ast.py +1906 -0
- evalkit_tf446/lib/python3.10/site-packages/sympy/codegen/cfunctions.py +536 -0
- evalkit_tf446/lib/python3.10/site-packages/sympy/codegen/cnodes.py +156 -0
- evalkit_tf446/lib/python3.10/site-packages/sympy/codegen/cutils.py +8 -0
- evalkit_tf446/lib/python3.10/site-packages/sympy/codegen/cxxnodes.py +14 -0
- evalkit_tf446/lib/python3.10/site-packages/sympy/codegen/fnodes.py +657 -0
- evalkit_tf446/lib/python3.10/site-packages/sympy/codegen/matrix_nodes.py +71 -0
- evalkit_tf446/lib/python3.10/site-packages/sympy/codegen/numpy_nodes.py +110 -0
- evalkit_tf446/lib/python3.10/site-packages/sympy/codegen/scipy_nodes.py +79 -0
- evalkit_tf446/lib/python3.10/site-packages/sympy/functions/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_tf446/lib/python3.10/site-packages/sympy/functions/combinatorial/__init__.py +1 -0
- evalkit_tf446/lib/python3.10/site-packages/sympy/functions/combinatorial/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_tf446/lib/python3.10/site-packages/sympy/functions/combinatorial/__pycache__/numbers.cpython-310.pyc +0 -0
- evalkit_tf446/lib/python3.10/site-packages/sympy/functions/combinatorial/factorials.py +1133 -0
- evalkit_tf446/lib/python3.10/site-packages/sympy/functions/combinatorial/numbers.py +0 -0
- evalkit_tf446/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/__init__.py +0 -0
- evalkit_tf446/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_tf446/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/__pycache__/test_comb_factorials.cpython-310.pyc +0 -0
- evalkit_tf446/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/__pycache__/test_comb_numbers.cpython-310.pyc +0 -0
- evalkit_tf446/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/test_comb_factorials.py +653 -0
.gitattributes
CHANGED
|
@@ -1321,3 +1321,4 @@ evalkit_tf437/lib/python3.10/site-packages/pandas/core/__pycache__/generic.cpyth
|
|
| 1321 |
evalkit_tf446/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_spin.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1322 |
evalkit_tf446/lib/python3.10/site-packages/sympy/physics/control/__pycache__/lti.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1323 |
evalkit_tf446/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/__pycache__/beam.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 1321 |
evalkit_tf446/lib/python3.10/site-packages/sympy/physics/quantum/tests/__pycache__/test_spin.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1322 |
evalkit_tf446/lib/python3.10/site-packages/sympy/physics/control/__pycache__/lti.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1323 |
evalkit_tf446/lib/python3.10/site-packages/sympy/physics/continuum_mechanics/__pycache__/beam.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1324 |
+
evalkit_tf446/lib/python3.10/site-packages/sympy/matrices/tests/__pycache__/test_matrices.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Almaty
ADDED
|
Binary file (983 Bytes). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Barnaul
ADDED
|
Binary file (1.21 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Beirut
ADDED
|
Binary file (2.15 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Calcutta
ADDED
|
Binary file (285 Bytes). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Choibalsan
ADDED
|
Binary file (877 Bytes). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Chongqing
ADDED
|
Binary file (561 Bytes). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Chungking
ADDED
|
Binary file (561 Bytes). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Colombo
ADDED
|
Binary file (358 Bytes). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Dili
ADDED
|
Binary file (257 Bytes). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Jakarta
ADDED
|
Binary file (383 Bytes). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Kolkata
ADDED
|
Binary file (285 Bytes). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Novokuznetsk
ADDED
|
Binary file (1.15 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Saigon
ADDED
|
Binary file (337 Bytes). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Samarkand
ADDED
|
Binary file (563 Bytes). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Shanghai
ADDED
|
Binary file (561 Bytes). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Tbilisi
ADDED
|
Binary file (1.02 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Tel_Aviv
ADDED
|
Binary file (2.39 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Thimbu
ADDED
|
Binary file (189 Bytes). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Tomsk
ADDED
|
Binary file (1.21 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Vladivostok
ADDED
|
Binary file (1.19 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Yakutsk
ADDED
|
Binary file (1.19 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Yangon
ADDED
|
Binary file (254 Bytes). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Asia/Yekaterinburg
ADDED
|
Binary file (1.23 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/CST6CDT
ADDED
|
Binary file (3.59 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Factory
ADDED
|
Binary file (116 Bytes). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/pytz/zoneinfo/Kwajalein
ADDED
|
Binary file (302 Bytes). View file
|
|
|
evalkit_tf446/lib/python3.10/site-packages/sympy/codegen/__init__.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
""" The ``sympy.codegen`` module contains classes and functions for building
|
| 2 |
+
abstract syntax trees of algorithms. These trees may then be printed by the
|
| 3 |
+
code-printers in ``sympy.printing``.
|
| 4 |
+
|
| 5 |
+
There are several submodules available:
|
| 6 |
+
- ``sympy.codegen.ast``: AST nodes useful across multiple languages.
|
| 7 |
+
- ``sympy.codegen.cnodes``: AST nodes useful for the C family of languages.
|
| 8 |
+
- ``sympy.codegen.fnodes``: AST nodes useful for Fortran.
|
| 9 |
+
- ``sympy.codegen.cfunctions``: functions specific to C (C99 math functions)
|
| 10 |
+
- ``sympy.codegen.ffunctions``: functions specific to Fortran (e.g. ``kind``).
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
"""
|
| 15 |
+
from .ast import (
|
| 16 |
+
Assignment, aug_assign, CodeBlock, For, Attribute, Variable, Declaration,
|
| 17 |
+
While, Scope, Print, FunctionPrototype, FunctionDefinition, FunctionCall
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
__all__ = [
|
| 21 |
+
'Assignment', 'aug_assign', 'CodeBlock', 'For', 'Attribute', 'Variable',
|
| 22 |
+
'Declaration', 'While', 'Scope', 'Print', 'FunctionPrototype',
|
| 23 |
+
'FunctionDefinition', 'FunctionCall',
|
| 24 |
+
]
|
evalkit_tf446/lib/python3.10/site-packages/sympy/codegen/algorithms.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.containers import Tuple
|
| 2 |
+
from sympy.core.numbers import oo
|
| 3 |
+
from sympy.core.relational import (Gt, Lt)
|
| 4 |
+
from sympy.core.symbol import (Dummy, Symbol)
|
| 5 |
+
from sympy.functions.elementary.complexes import Abs
|
| 6 |
+
from sympy.functions.elementary.miscellaneous import Min, Max
|
| 7 |
+
from sympy.logic.boolalg import And
|
| 8 |
+
from sympy.codegen.ast import (
|
| 9 |
+
Assignment, AddAugmentedAssignment, break_, CodeBlock, Declaration, FunctionDefinition,
|
| 10 |
+
Print, Return, Scope, While, Variable, Pointer, real
|
| 11 |
+
)
|
| 12 |
+
from sympy.codegen.cfunctions import isnan
|
| 13 |
+
|
| 14 |
+
""" This module collects functions for constructing ASTs representing algorithms. """
|
| 15 |
+
|
| 16 |
+
def newtons_method(expr, wrt, atol=1e-12, delta=None, *, rtol=4e-16, debug=False,
|
| 17 |
+
itermax=None, counter=None, delta_fn=lambda e, x: -e/e.diff(x),
|
| 18 |
+
cse=False, handle_nan=None,
|
| 19 |
+
bounds=None):
|
| 20 |
+
""" Generates an AST for Newton-Raphson method (a root-finding algorithm).
|
| 21 |
+
|
| 22 |
+
Explanation
|
| 23 |
+
===========
|
| 24 |
+
|
| 25 |
+
Returns an abstract syntax tree (AST) based on ``sympy.codegen.ast`` for Netwon's
|
| 26 |
+
method of root-finding.
|
| 27 |
+
|
| 28 |
+
Parameters
|
| 29 |
+
==========
|
| 30 |
+
|
| 31 |
+
expr : expression
|
| 32 |
+
wrt : Symbol
|
| 33 |
+
With respect to, i.e. what is the variable.
|
| 34 |
+
atol : number or expression
|
| 35 |
+
Absolute tolerance (stopping criterion)
|
| 36 |
+
rtol : number or expression
|
| 37 |
+
Relative tolerance (stopping criterion)
|
| 38 |
+
delta : Symbol
|
| 39 |
+
Will be a ``Dummy`` if ``None``.
|
| 40 |
+
debug : bool
|
| 41 |
+
Whether to print convergence information during iterations
|
| 42 |
+
itermax : number or expr
|
| 43 |
+
Maximum number of iterations.
|
| 44 |
+
counter : Symbol
|
| 45 |
+
Will be a ``Dummy`` if ``None``.
|
| 46 |
+
delta_fn: Callable[[Expr, Symbol], Expr]
|
| 47 |
+
computes the step, default is newtons method. For e.g. Halley's method
|
| 48 |
+
use delta_fn=lambda e, x: -2*e*e.diff(x)/(2*e.diff(x)**2 - e*e.diff(x, 2))
|
| 49 |
+
cse: bool
|
| 50 |
+
Perform common sub-expression elimination on delta expression
|
| 51 |
+
handle_nan: Token
|
| 52 |
+
How to handle occurrence of not-a-number (NaN).
|
| 53 |
+
bounds: Optional[tuple[Expr, Expr]]
|
| 54 |
+
Perform optimization within bounds
|
| 55 |
+
|
| 56 |
+
Examples
|
| 57 |
+
========
|
| 58 |
+
|
| 59 |
+
>>> from sympy import symbols, cos
|
| 60 |
+
>>> from sympy.codegen.ast import Assignment
|
| 61 |
+
>>> from sympy.codegen.algorithms import newtons_method
|
| 62 |
+
>>> x, dx, atol = symbols('x dx atol')
|
| 63 |
+
>>> expr = cos(x) - x**3
|
| 64 |
+
>>> algo = newtons_method(expr, x, atol=atol, delta=dx)
|
| 65 |
+
>>> algo.has(Assignment(dx, -expr/expr.diff(x)))
|
| 66 |
+
True
|
| 67 |
+
|
| 68 |
+
References
|
| 69 |
+
==========
|
| 70 |
+
|
| 71 |
+
.. [1] https://en.wikipedia.org/wiki/Newton%27s_method
|
| 72 |
+
|
| 73 |
+
"""
|
| 74 |
+
|
| 75 |
+
if delta is None:
|
| 76 |
+
delta = Dummy()
|
| 77 |
+
Wrapper = Scope
|
| 78 |
+
name_d = 'delta'
|
| 79 |
+
else:
|
| 80 |
+
Wrapper = lambda x: x
|
| 81 |
+
name_d = delta.name
|
| 82 |
+
|
| 83 |
+
delta_expr = delta_fn(expr, wrt)
|
| 84 |
+
if cse:
|
| 85 |
+
from sympy.simplify.cse_main import cse
|
| 86 |
+
cses, (red,) = cse([delta_expr.factor()])
|
| 87 |
+
whl_bdy = [Assignment(dum, sub_e) for dum, sub_e in cses]
|
| 88 |
+
whl_bdy += [Assignment(delta, red)]
|
| 89 |
+
else:
|
| 90 |
+
whl_bdy = [Assignment(delta, delta_expr)]
|
| 91 |
+
if handle_nan is not None:
|
| 92 |
+
whl_bdy += [While(isnan(delta), CodeBlock(handle_nan, break_))]
|
| 93 |
+
whl_bdy += [AddAugmentedAssignment(wrt, delta)]
|
| 94 |
+
if bounds is not None:
|
| 95 |
+
whl_bdy += [Assignment(wrt, Min(Max(wrt, bounds[0]), bounds[1]))]
|
| 96 |
+
if debug:
|
| 97 |
+
prnt = Print([wrt, delta], r"{}=%12.5g {}=%12.5g\n".format(wrt.name, name_d))
|
| 98 |
+
whl_bdy += [prnt]
|
| 99 |
+
req = Gt(Abs(delta), atol + rtol*Abs(wrt))
|
| 100 |
+
declars = [Declaration(Variable(delta, type=real, value=oo))]
|
| 101 |
+
if itermax is not None:
|
| 102 |
+
counter = counter or Dummy(integer=True)
|
| 103 |
+
v_counter = Variable.deduced(counter, 0)
|
| 104 |
+
declars.append(Declaration(v_counter))
|
| 105 |
+
whl_bdy.append(AddAugmentedAssignment(counter, 1))
|
| 106 |
+
req = And(req, Lt(counter, itermax))
|
| 107 |
+
whl = While(req, CodeBlock(*whl_bdy))
|
| 108 |
+
blck = declars
|
| 109 |
+
if debug:
|
| 110 |
+
blck.append(Print([wrt], r"{}=%12.5g\n".format(wrt.name)))
|
| 111 |
+
blck += [whl]
|
| 112 |
+
return Wrapper(CodeBlock(*blck))
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def _symbol_of(arg):
|
| 116 |
+
if isinstance(arg, Declaration):
|
| 117 |
+
arg = arg.variable.symbol
|
| 118 |
+
elif isinstance(arg, Variable):
|
| 119 |
+
arg = arg.symbol
|
| 120 |
+
return arg
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def newtons_method_function(expr, wrt, params=None, func_name="newton", attrs=Tuple(), *, delta=None, **kwargs):
|
| 124 |
+
""" Generates an AST for a function implementing the Newton-Raphson method.
|
| 125 |
+
|
| 126 |
+
Parameters
|
| 127 |
+
==========
|
| 128 |
+
|
| 129 |
+
expr : expression
|
| 130 |
+
wrt : Symbol
|
| 131 |
+
With respect to, i.e. what is the variable
|
| 132 |
+
params : iterable of symbols
|
| 133 |
+
Symbols appearing in expr that are taken as constants during the iterations
|
| 134 |
+
(these will be accepted as parameters to the generated function).
|
| 135 |
+
func_name : str
|
| 136 |
+
Name of the generated function.
|
| 137 |
+
attrs : Tuple
|
| 138 |
+
Attribute instances passed as ``attrs`` to ``FunctionDefinition``.
|
| 139 |
+
\\*\\*kwargs :
|
| 140 |
+
Keyword arguments passed to :func:`sympy.codegen.algorithms.newtons_method`.
|
| 141 |
+
|
| 142 |
+
Examples
|
| 143 |
+
========
|
| 144 |
+
|
| 145 |
+
>>> from sympy import symbols, cos
|
| 146 |
+
>>> from sympy.codegen.algorithms import newtons_method_function
|
| 147 |
+
>>> from sympy.codegen.pyutils import render_as_module
|
| 148 |
+
>>> x = symbols('x')
|
| 149 |
+
>>> expr = cos(x) - x**3
|
| 150 |
+
>>> func = newtons_method_function(expr, x)
|
| 151 |
+
>>> py_mod = render_as_module(func) # source code as string
|
| 152 |
+
>>> namespace = {}
|
| 153 |
+
>>> exec(py_mod, namespace, namespace)
|
| 154 |
+
>>> res = eval('newton(0.5)', namespace)
|
| 155 |
+
>>> abs(res - 0.865474033102) < 1e-12
|
| 156 |
+
True
|
| 157 |
+
|
| 158 |
+
See Also
|
| 159 |
+
========
|
| 160 |
+
|
| 161 |
+
sympy.codegen.algorithms.newtons_method
|
| 162 |
+
|
| 163 |
+
"""
|
| 164 |
+
if params is None:
|
| 165 |
+
params = (wrt,)
|
| 166 |
+
pointer_subs = {p.symbol: Symbol('(*%s)' % p.symbol.name)
|
| 167 |
+
for p in params if isinstance(p, Pointer)}
|
| 168 |
+
if delta is None:
|
| 169 |
+
delta = Symbol('d_' + wrt.name)
|
| 170 |
+
if expr.has(delta):
|
| 171 |
+
delta = None # will use Dummy
|
| 172 |
+
algo = newtons_method(expr, wrt, delta=delta, **kwargs).xreplace(pointer_subs)
|
| 173 |
+
if isinstance(algo, Scope):
|
| 174 |
+
algo = algo.body
|
| 175 |
+
not_in_params = expr.free_symbols.difference({_symbol_of(p) for p in params})
|
| 176 |
+
if not_in_params:
|
| 177 |
+
raise ValueError("Missing symbols in params: %s" % ', '.join(map(str, not_in_params)))
|
| 178 |
+
declars = tuple(Variable(p, real) for p in params)
|
| 179 |
+
body = CodeBlock(algo, Return(wrt))
|
| 180 |
+
return FunctionDefinition(real, func_name, declars, body, attrs=attrs)
|
evalkit_tf446/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
|
evalkit_tf446/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
|
evalkit_tf446/lib/python3.10/site-packages/sympy/codegen/cfunctions.py
ADDED
|
@@ -0,0 +1,536 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This module contains SymPy functions mathcin corresponding to special math functions in the
|
| 3 |
+
C standard library (since C99, also available in C++11).
|
| 4 |
+
|
| 5 |
+
The functions defined in this module allows the user to express functions such as ``expm1``
|
| 6 |
+
as a SymPy function for symbolic manipulation.
|
| 7 |
+
|
| 8 |
+
"""
|
| 9 |
+
from sympy.core.function import ArgumentIndexError, Function
|
| 10 |
+
from sympy.core.numbers import Rational
|
| 11 |
+
from sympy.core.power import Pow
|
| 12 |
+
from sympy.core.singleton import S
|
| 13 |
+
from sympy.functions.elementary.exponential import exp, log
|
| 14 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def _expm1(x):
|
| 18 |
+
return exp(x) - S.One
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class expm1(Function):
|
| 22 |
+
"""
|
| 23 |
+
Represents the exponential function minus one.
|
| 24 |
+
|
| 25 |
+
Explanation
|
| 26 |
+
===========
|
| 27 |
+
|
| 28 |
+
The benefit of using ``expm1(x)`` over ``exp(x) - 1``
|
| 29 |
+
is that the latter is prone to cancellation under finite precision
|
| 30 |
+
arithmetic when x is close to zero.
|
| 31 |
+
|
| 32 |
+
Examples
|
| 33 |
+
========
|
| 34 |
+
|
| 35 |
+
>>> from sympy.abc import x
|
| 36 |
+
>>> from sympy.codegen.cfunctions import expm1
|
| 37 |
+
>>> '%.0e' % expm1(1e-99).evalf()
|
| 38 |
+
'1e-99'
|
| 39 |
+
>>> from math import exp
|
| 40 |
+
>>> exp(1e-99) - 1
|
| 41 |
+
0.0
|
| 42 |
+
>>> expm1(x).diff(x)
|
| 43 |
+
exp(x)
|
| 44 |
+
|
| 45 |
+
See Also
|
| 46 |
+
========
|
| 47 |
+
|
| 48 |
+
log1p
|
| 49 |
+
"""
|
| 50 |
+
nargs = 1
|
| 51 |
+
|
| 52 |
+
def fdiff(self, argindex=1):
|
| 53 |
+
"""
|
| 54 |
+
Returns the first derivative of this function.
|
| 55 |
+
"""
|
| 56 |
+
if argindex == 1:
|
| 57 |
+
return exp(*self.args)
|
| 58 |
+
else:
|
| 59 |
+
raise ArgumentIndexError(self, argindex)
|
| 60 |
+
|
| 61 |
+
def _eval_expand_func(self, **hints):
|
| 62 |
+
return _expm1(*self.args)
|
| 63 |
+
|
| 64 |
+
def _eval_rewrite_as_exp(self, arg, **kwargs):
|
| 65 |
+
return exp(arg) - S.One
|
| 66 |
+
|
| 67 |
+
_eval_rewrite_as_tractable = _eval_rewrite_as_exp
|
| 68 |
+
|
| 69 |
+
@classmethod
|
| 70 |
+
def eval(cls, arg):
|
| 71 |
+
exp_arg = exp.eval(arg)
|
| 72 |
+
if exp_arg is not None:
|
| 73 |
+
return exp_arg - S.One
|
| 74 |
+
|
| 75 |
+
def _eval_is_real(self):
|
| 76 |
+
return self.args[0].is_real
|
| 77 |
+
|
| 78 |
+
def _eval_is_finite(self):
|
| 79 |
+
return self.args[0].is_finite
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def _log1p(x):
|
| 83 |
+
return log(x + S.One)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class log1p(Function):
|
| 87 |
+
"""
|
| 88 |
+
Represents the natural logarithm of a number plus one.
|
| 89 |
+
|
| 90 |
+
Explanation
|
| 91 |
+
===========
|
| 92 |
+
|
| 93 |
+
The benefit of using ``log1p(x)`` over ``log(x + 1)``
|
| 94 |
+
is that the latter is prone to cancellation under finite precision
|
| 95 |
+
arithmetic when x is close to zero.
|
| 96 |
+
|
| 97 |
+
Examples
|
| 98 |
+
========
|
| 99 |
+
|
| 100 |
+
>>> from sympy.abc import x
|
| 101 |
+
>>> from sympy.codegen.cfunctions import log1p
|
| 102 |
+
>>> from sympy import expand_log
|
| 103 |
+
>>> '%.0e' % expand_log(log1p(1e-99)).evalf()
|
| 104 |
+
'1e-99'
|
| 105 |
+
>>> from math import log
|
| 106 |
+
>>> log(1 + 1e-99)
|
| 107 |
+
0.0
|
| 108 |
+
>>> log1p(x).diff(x)
|
| 109 |
+
1/(x + 1)
|
| 110 |
+
|
| 111 |
+
See Also
|
| 112 |
+
========
|
| 113 |
+
|
| 114 |
+
expm1
|
| 115 |
+
"""
|
| 116 |
+
nargs = 1
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def fdiff(self, argindex=1):
|
| 120 |
+
"""
|
| 121 |
+
Returns the first derivative of this function.
|
| 122 |
+
"""
|
| 123 |
+
if argindex == 1:
|
| 124 |
+
return S.One/(self.args[0] + S.One)
|
| 125 |
+
else:
|
| 126 |
+
raise ArgumentIndexError(self, argindex)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def _eval_expand_func(self, **hints):
|
| 130 |
+
return _log1p(*self.args)
|
| 131 |
+
|
| 132 |
+
def _eval_rewrite_as_log(self, arg, **kwargs):
|
| 133 |
+
return _log1p(arg)
|
| 134 |
+
|
| 135 |
+
_eval_rewrite_as_tractable = _eval_rewrite_as_log
|
| 136 |
+
|
| 137 |
+
@classmethod
|
| 138 |
+
def eval(cls, arg):
|
| 139 |
+
if arg.is_Rational:
|
| 140 |
+
return log(arg + S.One)
|
| 141 |
+
elif not arg.is_Float: # not safe to add 1 to Float
|
| 142 |
+
return log.eval(arg + S.One)
|
| 143 |
+
elif arg.is_number:
|
| 144 |
+
return log(Rational(arg) + S.One)
|
| 145 |
+
|
| 146 |
+
def _eval_is_real(self):
|
| 147 |
+
return (self.args[0] + S.One).is_nonnegative
|
| 148 |
+
|
| 149 |
+
def _eval_is_finite(self):
|
| 150 |
+
if (self.args[0] + S.One).is_zero:
|
| 151 |
+
return False
|
| 152 |
+
return self.args[0].is_finite
|
| 153 |
+
|
| 154 |
+
def _eval_is_positive(self):
|
| 155 |
+
return self.args[0].is_positive
|
| 156 |
+
|
| 157 |
+
def _eval_is_zero(self):
|
| 158 |
+
return self.args[0].is_zero
|
| 159 |
+
|
| 160 |
+
def _eval_is_nonnegative(self):
|
| 161 |
+
return self.args[0].is_nonnegative
|
| 162 |
+
|
| 163 |
+
_Two = S(2)
|
| 164 |
+
|
| 165 |
+
def _exp2(x):
|
| 166 |
+
return Pow(_Two, x)
|
| 167 |
+
|
| 168 |
+
class exp2(Function):
|
| 169 |
+
"""
|
| 170 |
+
Represents the exponential function with base two.
|
| 171 |
+
|
| 172 |
+
Explanation
|
| 173 |
+
===========
|
| 174 |
+
|
| 175 |
+
The benefit of using ``exp2(x)`` over ``2**x``
|
| 176 |
+
is that the latter is not as efficient under finite precision
|
| 177 |
+
arithmetic.
|
| 178 |
+
|
| 179 |
+
Examples
|
| 180 |
+
========
|
| 181 |
+
|
| 182 |
+
>>> from sympy.abc import x
|
| 183 |
+
>>> from sympy.codegen.cfunctions import exp2
|
| 184 |
+
>>> exp2(2).evalf() == 4.0
|
| 185 |
+
True
|
| 186 |
+
>>> exp2(x).diff(x)
|
| 187 |
+
log(2)*exp2(x)
|
| 188 |
+
|
| 189 |
+
See Also
|
| 190 |
+
========
|
| 191 |
+
|
| 192 |
+
log2
|
| 193 |
+
"""
|
| 194 |
+
nargs = 1
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def fdiff(self, argindex=1):
|
| 198 |
+
"""
|
| 199 |
+
Returns the first derivative of this function.
|
| 200 |
+
"""
|
| 201 |
+
if argindex == 1:
|
| 202 |
+
return self*log(_Two)
|
| 203 |
+
else:
|
| 204 |
+
raise ArgumentIndexError(self, argindex)
|
| 205 |
+
|
| 206 |
+
def _eval_rewrite_as_Pow(self, arg, **kwargs):
|
| 207 |
+
return _exp2(arg)
|
| 208 |
+
|
| 209 |
+
_eval_rewrite_as_tractable = _eval_rewrite_as_Pow
|
| 210 |
+
|
| 211 |
+
def _eval_expand_func(self, **hints):
|
| 212 |
+
return _exp2(*self.args)
|
| 213 |
+
|
| 214 |
+
@classmethod
|
| 215 |
+
def eval(cls, arg):
|
| 216 |
+
if arg.is_number:
|
| 217 |
+
return _exp2(arg)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def _log2(x):
|
| 221 |
+
return log(x)/log(_Two)
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
class log2(Function):
|
| 225 |
+
"""
|
| 226 |
+
Represents the logarithm function with base two.
|
| 227 |
+
|
| 228 |
+
Explanation
|
| 229 |
+
===========
|
| 230 |
+
|
| 231 |
+
The benefit of using ``log2(x)`` over ``log(x)/log(2)``
|
| 232 |
+
is that the latter is not as efficient under finite precision
|
| 233 |
+
arithmetic.
|
| 234 |
+
|
| 235 |
+
Examples
|
| 236 |
+
========
|
| 237 |
+
|
| 238 |
+
>>> from sympy.abc import x
|
| 239 |
+
>>> from sympy.codegen.cfunctions import log2
|
| 240 |
+
>>> log2(4).evalf() == 2.0
|
| 241 |
+
True
|
| 242 |
+
>>> log2(x).diff(x)
|
| 243 |
+
1/(x*log(2))
|
| 244 |
+
|
| 245 |
+
See Also
|
| 246 |
+
========
|
| 247 |
+
|
| 248 |
+
exp2
|
| 249 |
+
log10
|
| 250 |
+
"""
|
| 251 |
+
nargs = 1
|
| 252 |
+
|
| 253 |
+
def fdiff(self, argindex=1):
|
| 254 |
+
"""
|
| 255 |
+
Returns the first derivative of this function.
|
| 256 |
+
"""
|
| 257 |
+
if argindex == 1:
|
| 258 |
+
return S.One/(log(_Two)*self.args[0])
|
| 259 |
+
else:
|
| 260 |
+
raise ArgumentIndexError(self, argindex)
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
@classmethod
|
| 264 |
+
def eval(cls, arg):
|
| 265 |
+
if arg.is_number:
|
| 266 |
+
result = log.eval(arg, base=_Two)
|
| 267 |
+
if result.is_Atom:
|
| 268 |
+
return result
|
| 269 |
+
elif arg.is_Pow and arg.base == _Two:
|
| 270 |
+
return arg.exp
|
| 271 |
+
|
| 272 |
+
def _eval_evalf(self, *args, **kwargs):
|
| 273 |
+
return self.rewrite(log).evalf(*args, **kwargs)
|
| 274 |
+
|
| 275 |
+
def _eval_expand_func(self, **hints):
|
| 276 |
+
return _log2(*self.args)
|
| 277 |
+
|
| 278 |
+
def _eval_rewrite_as_log(self, arg, **kwargs):
|
| 279 |
+
return _log2(arg)
|
| 280 |
+
|
| 281 |
+
_eval_rewrite_as_tractable = _eval_rewrite_as_log
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def _fma(x, y, z):
|
| 285 |
+
return x*y + z
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
class fma(Function):
|
| 289 |
+
"""
|
| 290 |
+
Represents "fused multiply add".
|
| 291 |
+
|
| 292 |
+
Explanation
|
| 293 |
+
===========
|
| 294 |
+
|
| 295 |
+
The benefit of using ``fma(x, y, z)`` over ``x*y + z``
|
| 296 |
+
is that, under finite precision arithmetic, the former is
|
| 297 |
+
supported by special instructions on some CPUs.
|
| 298 |
+
|
| 299 |
+
Examples
|
| 300 |
+
========
|
| 301 |
+
|
| 302 |
+
>>> from sympy.abc import x, y, z
|
| 303 |
+
>>> from sympy.codegen.cfunctions import fma
|
| 304 |
+
>>> fma(x, y, z).diff(x)
|
| 305 |
+
y
|
| 306 |
+
|
| 307 |
+
"""
|
| 308 |
+
nargs = 3
|
| 309 |
+
|
| 310 |
+
def fdiff(self, argindex=1):
|
| 311 |
+
"""
|
| 312 |
+
Returns the first derivative of this function.
|
| 313 |
+
"""
|
| 314 |
+
if argindex in (1, 2):
|
| 315 |
+
return self.args[2 - argindex]
|
| 316 |
+
elif argindex == 3:
|
| 317 |
+
return S.One
|
| 318 |
+
else:
|
| 319 |
+
raise ArgumentIndexError(self, argindex)
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def _eval_expand_func(self, **hints):
|
| 323 |
+
return _fma(*self.args)
|
| 324 |
+
|
| 325 |
+
def _eval_rewrite_as_tractable(self, arg, limitvar=None, **kwargs):
|
| 326 |
+
return _fma(arg)
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
_Ten = S(10)
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
def _log10(x):
|
| 333 |
+
return log(x)/log(_Ten)
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
class log10(Function):
|
| 337 |
+
"""
|
| 338 |
+
Represents the logarithm function with base ten.
|
| 339 |
+
|
| 340 |
+
Examples
|
| 341 |
+
========
|
| 342 |
+
|
| 343 |
+
>>> from sympy.abc import x
|
| 344 |
+
>>> from sympy.codegen.cfunctions import log10
|
| 345 |
+
>>> log10(100).evalf() == 2.0
|
| 346 |
+
True
|
| 347 |
+
>>> log10(x).diff(x)
|
| 348 |
+
1/(x*log(10))
|
| 349 |
+
|
| 350 |
+
See Also
|
| 351 |
+
========
|
| 352 |
+
|
| 353 |
+
log2
|
| 354 |
+
"""
|
| 355 |
+
nargs = 1
|
| 356 |
+
|
| 357 |
+
def fdiff(self, argindex=1):
|
| 358 |
+
"""
|
| 359 |
+
Returns the first derivative of this function.
|
| 360 |
+
"""
|
| 361 |
+
if argindex == 1:
|
| 362 |
+
return S.One/(log(_Ten)*self.args[0])
|
| 363 |
+
else:
|
| 364 |
+
raise ArgumentIndexError(self, argindex)
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
@classmethod
|
| 368 |
+
def eval(cls, arg):
|
| 369 |
+
if arg.is_number:
|
| 370 |
+
result = log.eval(arg, base=_Ten)
|
| 371 |
+
if result.is_Atom:
|
| 372 |
+
return result
|
| 373 |
+
elif arg.is_Pow and arg.base == _Ten:
|
| 374 |
+
return arg.exp
|
| 375 |
+
|
| 376 |
+
def _eval_expand_func(self, **hints):
|
| 377 |
+
return _log10(*self.args)
|
| 378 |
+
|
| 379 |
+
def _eval_rewrite_as_log(self, arg, **kwargs):
|
| 380 |
+
return _log10(arg)
|
| 381 |
+
|
| 382 |
+
_eval_rewrite_as_tractable = _eval_rewrite_as_log
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
def _Sqrt(x):
|
| 386 |
+
return Pow(x, S.Half)
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
class Sqrt(Function): # 'sqrt' already defined in sympy.functions.elementary.miscellaneous
|
| 390 |
+
"""
|
| 391 |
+
Represents the square root function.
|
| 392 |
+
|
| 393 |
+
Explanation
|
| 394 |
+
===========
|
| 395 |
+
|
| 396 |
+
The reason why one would use ``Sqrt(x)`` over ``sqrt(x)``
|
| 397 |
+
is that the latter is internally represented as ``Pow(x, S.Half)`` which
|
| 398 |
+
may not be what one wants when doing code-generation.
|
| 399 |
+
|
| 400 |
+
Examples
|
| 401 |
+
========
|
| 402 |
+
|
| 403 |
+
>>> from sympy.abc import x
|
| 404 |
+
>>> from sympy.codegen.cfunctions import Sqrt
|
| 405 |
+
>>> Sqrt(x)
|
| 406 |
+
Sqrt(x)
|
| 407 |
+
>>> Sqrt(x).diff(x)
|
| 408 |
+
1/(2*sqrt(x))
|
| 409 |
+
|
| 410 |
+
See Also
|
| 411 |
+
========
|
| 412 |
+
|
| 413 |
+
Cbrt
|
| 414 |
+
"""
|
| 415 |
+
nargs = 1
|
| 416 |
+
|
| 417 |
+
def fdiff(self, argindex=1):
|
| 418 |
+
"""
|
| 419 |
+
Returns the first derivative of this function.
|
| 420 |
+
"""
|
| 421 |
+
if argindex == 1:
|
| 422 |
+
return Pow(self.args[0], Rational(-1, 2))/_Two
|
| 423 |
+
else:
|
| 424 |
+
raise ArgumentIndexError(self, argindex)
|
| 425 |
+
|
| 426 |
+
def _eval_expand_func(self, **hints):
|
| 427 |
+
return _Sqrt(*self.args)
|
| 428 |
+
|
| 429 |
+
def _eval_rewrite_as_Pow(self, arg, **kwargs):
|
| 430 |
+
return _Sqrt(arg)
|
| 431 |
+
|
| 432 |
+
_eval_rewrite_as_tractable = _eval_rewrite_as_Pow
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
def _Cbrt(x):
|
| 436 |
+
return Pow(x, Rational(1, 3))
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
class Cbrt(Function): # 'cbrt' already defined in sympy.functions.elementary.miscellaneous
|
| 440 |
+
"""
|
| 441 |
+
Represents the cube root function.
|
| 442 |
+
|
| 443 |
+
Explanation
|
| 444 |
+
===========
|
| 445 |
+
|
| 446 |
+
The reason why one would use ``Cbrt(x)`` over ``cbrt(x)``
|
| 447 |
+
is that the latter is internally represented as ``Pow(x, Rational(1, 3))`` which
|
| 448 |
+
may not be what one wants when doing code-generation.
|
| 449 |
+
|
| 450 |
+
Examples
|
| 451 |
+
========
|
| 452 |
+
|
| 453 |
+
>>> from sympy.abc import x
|
| 454 |
+
>>> from sympy.codegen.cfunctions import Cbrt
|
| 455 |
+
>>> Cbrt(x)
|
| 456 |
+
Cbrt(x)
|
| 457 |
+
>>> Cbrt(x).diff(x)
|
| 458 |
+
1/(3*x**(2/3))
|
| 459 |
+
|
| 460 |
+
See Also
|
| 461 |
+
========
|
| 462 |
+
|
| 463 |
+
Sqrt
|
| 464 |
+
"""
|
| 465 |
+
nargs = 1
|
| 466 |
+
|
| 467 |
+
def fdiff(self, argindex=1):
|
| 468 |
+
"""
|
| 469 |
+
Returns the first derivative of this function.
|
| 470 |
+
"""
|
| 471 |
+
if argindex == 1:
|
| 472 |
+
return Pow(self.args[0], Rational(-_Two/3))/3
|
| 473 |
+
else:
|
| 474 |
+
raise ArgumentIndexError(self, argindex)
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
def _eval_expand_func(self, **hints):
|
| 478 |
+
return _Cbrt(*self.args)
|
| 479 |
+
|
| 480 |
+
def _eval_rewrite_as_Pow(self, arg, **kwargs):
|
| 481 |
+
return _Cbrt(arg)
|
| 482 |
+
|
| 483 |
+
_eval_rewrite_as_tractable = _eval_rewrite_as_Pow
|
| 484 |
+
|
| 485 |
+
|
| 486 |
+
def _hypot(x, y):
|
| 487 |
+
return sqrt(Pow(x, 2) + Pow(y, 2))
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
class hypot(Function):
|
| 491 |
+
"""
|
| 492 |
+
Represents the hypotenuse function.
|
| 493 |
+
|
| 494 |
+
Explanation
|
| 495 |
+
===========
|
| 496 |
+
|
| 497 |
+
The hypotenuse function is provided by e.g. the math library
|
| 498 |
+
in the C99 standard, hence one may want to represent the function
|
| 499 |
+
symbolically when doing code-generation.
|
| 500 |
+
|
| 501 |
+
Examples
|
| 502 |
+
========
|
| 503 |
+
|
| 504 |
+
>>> from sympy.abc import x, y
|
| 505 |
+
>>> from sympy.codegen.cfunctions import hypot
|
| 506 |
+
>>> hypot(3, 4).evalf() == 5.0
|
| 507 |
+
True
|
| 508 |
+
>>> hypot(x, y)
|
| 509 |
+
hypot(x, y)
|
| 510 |
+
>>> hypot(x, y).diff(x)
|
| 511 |
+
x/hypot(x, y)
|
| 512 |
+
|
| 513 |
+
"""
|
| 514 |
+
nargs = 2
|
| 515 |
+
|
| 516 |
+
def fdiff(self, argindex=1):
|
| 517 |
+
"""
|
| 518 |
+
Returns the first derivative of this function.
|
| 519 |
+
"""
|
| 520 |
+
if argindex in (1, 2):
|
| 521 |
+
return 2*self.args[argindex-1]/(_Two*self.func(*self.args))
|
| 522 |
+
else:
|
| 523 |
+
raise ArgumentIndexError(self, argindex)
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
def _eval_expand_func(self, **hints):
|
| 527 |
+
return _hypot(*self.args)
|
| 528 |
+
|
| 529 |
+
def _eval_rewrite_as_Pow(self, arg, **kwargs):
|
| 530 |
+
return _hypot(arg)
|
| 531 |
+
|
| 532 |
+
_eval_rewrite_as_tractable = _eval_rewrite_as_Pow
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
class isnan(Function):
|
| 536 |
+
nargs = 1
|
evalkit_tf446/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__ = ()
|
evalkit_tf446/lib/python3.10/site-packages/sympy/codegen/cutils.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.printing.c import C99CodePrinter
|
| 2 |
+
|
| 3 |
+
def render_as_source_file(content, Printer=C99CodePrinter, settings=None):
|
| 4 |
+
""" Renders a C source file (with required #include statements) """
|
| 5 |
+
printer = Printer(settings or {})
|
| 6 |
+
code_str = printer.doprint(content)
|
| 7 |
+
includes = '\n'.join(['#include <%s>' % h for h in printer.headers])
|
| 8 |
+
return includes + '\n\n' + code_str
|
evalkit_tf446/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')
|
evalkit_tf446/lib/python3.10/site-packages/sympy/codegen/fnodes.py
ADDED
|
@@ -0,0 +1,657 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
AST nodes specific to Fortran.
|
| 3 |
+
|
| 4 |
+
The functions defined in this module allows the user to express functions such as ``dsign``
|
| 5 |
+
as a SymPy function for symbolic manipulation.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from sympy.codegen.ast import (
|
| 9 |
+
Attribute, CodeBlock, FunctionCall, Node, none, String,
|
| 10 |
+
Token, _mk_Tuple, Variable
|
| 11 |
+
)
|
| 12 |
+
from sympy.core.basic import Basic
|
| 13 |
+
from sympy.core.containers import Tuple
|
| 14 |
+
from sympy.core.expr import Expr
|
| 15 |
+
from sympy.core.function import Function
|
| 16 |
+
from sympy.core.numbers import Float, Integer
|
| 17 |
+
from sympy.core.symbol import Str
|
| 18 |
+
from sympy.core.sympify import sympify
|
| 19 |
+
from sympy.logic import true, false
|
| 20 |
+
from sympy.utilities.iterables import iterable
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
pure = Attribute('pure')
|
| 25 |
+
elemental = Attribute('elemental') # (all elemental procedures are also pure)
|
| 26 |
+
|
| 27 |
+
intent_in = Attribute('intent_in')
|
| 28 |
+
intent_out = Attribute('intent_out')
|
| 29 |
+
intent_inout = Attribute('intent_inout')
|
| 30 |
+
|
| 31 |
+
allocatable = Attribute('allocatable')
|
| 32 |
+
|
| 33 |
+
class Program(Token):
|
| 34 |
+
""" Represents a 'program' block in Fortran.
|
| 35 |
+
|
| 36 |
+
Examples
|
| 37 |
+
========
|
| 38 |
+
|
| 39 |
+
>>> from sympy.codegen.ast import Print
|
| 40 |
+
>>> from sympy.codegen.fnodes import Program
|
| 41 |
+
>>> prog = Program('myprogram', [Print([42])])
|
| 42 |
+
>>> from sympy import fcode
|
| 43 |
+
>>> print(fcode(prog, source_format='free'))
|
| 44 |
+
program myprogram
|
| 45 |
+
print *, 42
|
| 46 |
+
end program
|
| 47 |
+
|
| 48 |
+
"""
|
| 49 |
+
__slots__ = _fields = ('name', 'body')
|
| 50 |
+
_construct_name = String
|
| 51 |
+
_construct_body = staticmethod(lambda body: CodeBlock(*body))
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class use_rename(Token):
|
| 55 |
+
""" Represents a renaming in a use statement in Fortran.
|
| 56 |
+
|
| 57 |
+
Examples
|
| 58 |
+
========
|
| 59 |
+
|
| 60 |
+
>>> from sympy.codegen.fnodes import use_rename, use
|
| 61 |
+
>>> from sympy import fcode
|
| 62 |
+
>>> ren = use_rename("thingy", "convolution2d")
|
| 63 |
+
>>> print(fcode(ren, source_format='free'))
|
| 64 |
+
thingy => convolution2d
|
| 65 |
+
>>> full = use('signallib', only=['snr', ren])
|
| 66 |
+
>>> print(fcode(full, source_format='free'))
|
| 67 |
+
use signallib, only: snr, thingy => convolution2d
|
| 68 |
+
|
| 69 |
+
"""
|
| 70 |
+
__slots__ = _fields = ('local', 'original')
|
| 71 |
+
_construct_local = String
|
| 72 |
+
_construct_original = String
|
| 73 |
+
|
| 74 |
+
def _name(arg):
|
| 75 |
+
if hasattr(arg, 'name'):
|
| 76 |
+
return arg.name
|
| 77 |
+
else:
|
| 78 |
+
return String(arg)
|
| 79 |
+
|
| 80 |
+
class use(Token):
|
| 81 |
+
""" Represents a use statement in Fortran.
|
| 82 |
+
|
| 83 |
+
Examples
|
| 84 |
+
========
|
| 85 |
+
|
| 86 |
+
>>> from sympy.codegen.fnodes import use
|
| 87 |
+
>>> from sympy import fcode
|
| 88 |
+
>>> fcode(use('signallib'), source_format='free')
|
| 89 |
+
'use signallib'
|
| 90 |
+
>>> fcode(use('signallib', [('metric', 'snr')]), source_format='free')
|
| 91 |
+
'use signallib, metric => snr'
|
| 92 |
+
>>> fcode(use('signallib', only=['snr', 'convolution2d']), source_format='free')
|
| 93 |
+
'use signallib, only: snr, convolution2d'
|
| 94 |
+
|
| 95 |
+
"""
|
| 96 |
+
__slots__ = _fields = ('namespace', 'rename', 'only')
|
| 97 |
+
defaults = {'rename': none, 'only': none}
|
| 98 |
+
_construct_namespace = staticmethod(_name)
|
| 99 |
+
_construct_rename = staticmethod(lambda args: Tuple(*[arg if isinstance(arg, use_rename) else use_rename(*arg) for arg in args]))
|
| 100 |
+
_construct_only = staticmethod(lambda args: Tuple(*[arg if isinstance(arg, use_rename) else _name(arg) for arg in args]))
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class Module(Token):
|
| 104 |
+
""" Represents a module in Fortran.
|
| 105 |
+
|
| 106 |
+
Examples
|
| 107 |
+
========
|
| 108 |
+
|
| 109 |
+
>>> from sympy.codegen.fnodes import Module
|
| 110 |
+
>>> from sympy import fcode
|
| 111 |
+
>>> print(fcode(Module('signallib', ['implicit none'], []), source_format='free'))
|
| 112 |
+
module signallib
|
| 113 |
+
implicit none
|
| 114 |
+
<BLANKLINE>
|
| 115 |
+
contains
|
| 116 |
+
<BLANKLINE>
|
| 117 |
+
<BLANKLINE>
|
| 118 |
+
end module
|
| 119 |
+
|
| 120 |
+
"""
|
| 121 |
+
__slots__ = _fields = ('name', 'declarations', 'definitions')
|
| 122 |
+
defaults = {'declarations': Tuple()}
|
| 123 |
+
_construct_name = String
|
| 124 |
+
|
| 125 |
+
@classmethod
|
| 126 |
+
def _construct_declarations(cls, args):
|
| 127 |
+
args = [Str(arg) if isinstance(arg, str) else arg for arg in args]
|
| 128 |
+
return CodeBlock(*args)
|
| 129 |
+
|
| 130 |
+
_construct_definitions = staticmethod(lambda arg: CodeBlock(*arg))
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
class Subroutine(Node):
|
| 134 |
+
""" Represents a subroutine in Fortran.
|
| 135 |
+
|
| 136 |
+
Examples
|
| 137 |
+
========
|
| 138 |
+
|
| 139 |
+
>>> from sympy import fcode, symbols
|
| 140 |
+
>>> from sympy.codegen.ast import Print
|
| 141 |
+
>>> from sympy.codegen.fnodes import Subroutine
|
| 142 |
+
>>> x, y = symbols('x y', real=True)
|
| 143 |
+
>>> sub = Subroutine('mysub', [x, y], [Print([x**2 + y**2, x*y])])
|
| 144 |
+
>>> print(fcode(sub, source_format='free', standard=2003))
|
| 145 |
+
subroutine mysub(x, y)
|
| 146 |
+
real*8 :: x
|
| 147 |
+
real*8 :: y
|
| 148 |
+
print *, x**2 + y**2, x*y
|
| 149 |
+
end subroutine
|
| 150 |
+
|
| 151 |
+
"""
|
| 152 |
+
__slots__ = ('name', 'parameters', 'body')
|
| 153 |
+
_fields = __slots__ + Node._fields
|
| 154 |
+
_construct_name = String
|
| 155 |
+
_construct_parameters = staticmethod(lambda params: Tuple(*map(Variable.deduced, params)))
|
| 156 |
+
|
| 157 |
+
@classmethod
|
| 158 |
+
def _construct_body(cls, itr):
|
| 159 |
+
if isinstance(itr, CodeBlock):
|
| 160 |
+
return itr
|
| 161 |
+
else:
|
| 162 |
+
return CodeBlock(*itr)
|
| 163 |
+
|
| 164 |
+
class SubroutineCall(Token):
|
| 165 |
+
""" Represents a call to a subroutine in Fortran.
|
| 166 |
+
|
| 167 |
+
Examples
|
| 168 |
+
========
|
| 169 |
+
|
| 170 |
+
>>> from sympy.codegen.fnodes import SubroutineCall
|
| 171 |
+
>>> from sympy import fcode
|
| 172 |
+
>>> fcode(SubroutineCall('mysub', 'x y'.split()))
|
| 173 |
+
' call mysub(x, y)'
|
| 174 |
+
|
| 175 |
+
"""
|
| 176 |
+
__slots__ = _fields = ('name', 'subroutine_args')
|
| 177 |
+
_construct_name = staticmethod(_name)
|
| 178 |
+
_construct_subroutine_args = staticmethod(_mk_Tuple)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
class Do(Token):
|
| 182 |
+
""" Represents a Do loop in in Fortran.
|
| 183 |
+
|
| 184 |
+
Examples
|
| 185 |
+
========
|
| 186 |
+
|
| 187 |
+
>>> from sympy import fcode, symbols
|
| 188 |
+
>>> from sympy.codegen.ast import aug_assign, Print
|
| 189 |
+
>>> from sympy.codegen.fnodes import Do
|
| 190 |
+
>>> i, n = symbols('i n', integer=True)
|
| 191 |
+
>>> r = symbols('r', real=True)
|
| 192 |
+
>>> body = [aug_assign(r, '+', 1/i), Print([i, r])]
|
| 193 |
+
>>> do1 = Do(body, i, 1, n)
|
| 194 |
+
>>> print(fcode(do1, source_format='free'))
|
| 195 |
+
do i = 1, n
|
| 196 |
+
r = r + 1d0/i
|
| 197 |
+
print *, i, r
|
| 198 |
+
end do
|
| 199 |
+
>>> do2 = Do(body, i, 1, n, 2)
|
| 200 |
+
>>> print(fcode(do2, source_format='free'))
|
| 201 |
+
do i = 1, n, 2
|
| 202 |
+
r = r + 1d0/i
|
| 203 |
+
print *, i, r
|
| 204 |
+
end do
|
| 205 |
+
|
| 206 |
+
"""
|
| 207 |
+
|
| 208 |
+
__slots__ = _fields = ('body', 'counter', 'first', 'last', 'step', 'concurrent')
|
| 209 |
+
defaults = {'step': Integer(1), 'concurrent': false}
|
| 210 |
+
_construct_body = staticmethod(lambda body: CodeBlock(*body))
|
| 211 |
+
_construct_counter = staticmethod(sympify)
|
| 212 |
+
_construct_first = staticmethod(sympify)
|
| 213 |
+
_construct_last = staticmethod(sympify)
|
| 214 |
+
_construct_step = staticmethod(sympify)
|
| 215 |
+
_construct_concurrent = staticmethod(lambda arg: true if arg else false)
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
class ArrayConstructor(Token):
|
| 219 |
+
""" Represents an array constructor.
|
| 220 |
+
|
| 221 |
+
Examples
|
| 222 |
+
========
|
| 223 |
+
|
| 224 |
+
>>> from sympy import fcode
|
| 225 |
+
>>> from sympy.codegen.fnodes import ArrayConstructor
|
| 226 |
+
>>> ac = ArrayConstructor([1, 2, 3])
|
| 227 |
+
>>> fcode(ac, standard=95, source_format='free')
|
| 228 |
+
'(/1, 2, 3/)'
|
| 229 |
+
>>> fcode(ac, standard=2003, source_format='free')
|
| 230 |
+
'[1, 2, 3]'
|
| 231 |
+
|
| 232 |
+
"""
|
| 233 |
+
__slots__ = _fields = ('elements',)
|
| 234 |
+
_construct_elements = staticmethod(_mk_Tuple)
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
class ImpliedDoLoop(Token):
|
| 238 |
+
""" Represents an implied do loop in Fortran.
|
| 239 |
+
|
| 240 |
+
Examples
|
| 241 |
+
========
|
| 242 |
+
|
| 243 |
+
>>> from sympy import Symbol, fcode
|
| 244 |
+
>>> from sympy.codegen.fnodes import ImpliedDoLoop, ArrayConstructor
|
| 245 |
+
>>> i = Symbol('i', integer=True)
|
| 246 |
+
>>> idl = ImpliedDoLoop(i**3, i, -3, 3, 2) # -27, -1, 1, 27
|
| 247 |
+
>>> ac = ArrayConstructor([-28, idl, 28]) # -28, -27, -1, 1, 27, 28
|
| 248 |
+
>>> fcode(ac, standard=2003, source_format='free')
|
| 249 |
+
'[-28, (i**3, i = -3, 3, 2), 28]'
|
| 250 |
+
|
| 251 |
+
"""
|
| 252 |
+
__slots__ = _fields = ('expr', 'counter', 'first', 'last', 'step')
|
| 253 |
+
defaults = {'step': Integer(1)}
|
| 254 |
+
_construct_expr = staticmethod(sympify)
|
| 255 |
+
_construct_counter = staticmethod(sympify)
|
| 256 |
+
_construct_first = staticmethod(sympify)
|
| 257 |
+
_construct_last = staticmethod(sympify)
|
| 258 |
+
_construct_step = staticmethod(sympify)
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
class Extent(Basic):
|
| 262 |
+
""" Represents a dimension extent.
|
| 263 |
+
|
| 264 |
+
Examples
|
| 265 |
+
========
|
| 266 |
+
|
| 267 |
+
>>> from sympy.codegen.fnodes import Extent
|
| 268 |
+
>>> e = Extent(-3, 3) # -3, -2, -1, 0, 1, 2, 3
|
| 269 |
+
>>> from sympy import fcode
|
| 270 |
+
>>> fcode(e, source_format='free')
|
| 271 |
+
'-3:3'
|
| 272 |
+
>>> from sympy.codegen.ast import Variable, real
|
| 273 |
+
>>> from sympy.codegen.fnodes import dimension, intent_out
|
| 274 |
+
>>> dim = dimension(e, e)
|
| 275 |
+
>>> arr = Variable('x', real, attrs=[dim, intent_out])
|
| 276 |
+
>>> fcode(arr.as_Declaration(), source_format='free', standard=2003)
|
| 277 |
+
'real*8, dimension(-3:3, -3:3), intent(out) :: x'
|
| 278 |
+
|
| 279 |
+
"""
|
| 280 |
+
def __new__(cls, *args):
|
| 281 |
+
if len(args) == 2:
|
| 282 |
+
low, high = args
|
| 283 |
+
return Basic.__new__(cls, sympify(low), sympify(high))
|
| 284 |
+
elif len(args) == 0 or (len(args) == 1 and args[0] in (':', None)):
|
| 285 |
+
return Basic.__new__(cls) # assumed shape
|
| 286 |
+
else:
|
| 287 |
+
raise ValueError("Expected 0 or 2 args (or one argument == None or ':')")
|
| 288 |
+
|
| 289 |
+
def _sympystr(self, printer):
|
| 290 |
+
if len(self.args) == 0:
|
| 291 |
+
return ':'
|
| 292 |
+
return ":".join(str(arg) for arg in self.args)
|
| 293 |
+
|
| 294 |
+
assumed_extent = Extent() # or Extent(':'), Extent(None)
|
| 295 |
+
|
| 296 |
+
|
| 297 |
+
def dimension(*args):
|
| 298 |
+
""" Creates a 'dimension' Attribute with (up to 7) extents.
|
| 299 |
+
|
| 300 |
+
Examples
|
| 301 |
+
========
|
| 302 |
+
|
| 303 |
+
>>> from sympy import fcode
|
| 304 |
+
>>> from sympy.codegen.fnodes import dimension, intent_in
|
| 305 |
+
>>> dim = dimension('2', ':') # 2 rows, runtime determined number of columns
|
| 306 |
+
>>> from sympy.codegen.ast import Variable, integer
|
| 307 |
+
>>> arr = Variable('a', integer, attrs=[dim, intent_in])
|
| 308 |
+
>>> fcode(arr.as_Declaration(), source_format='free', standard=2003)
|
| 309 |
+
'integer*4, dimension(2, :), intent(in) :: a'
|
| 310 |
+
|
| 311 |
+
"""
|
| 312 |
+
if len(args) > 7:
|
| 313 |
+
raise ValueError("Fortran only supports up to 7 dimensional arrays")
|
| 314 |
+
parameters = []
|
| 315 |
+
for arg in args:
|
| 316 |
+
if isinstance(arg, Extent):
|
| 317 |
+
parameters.append(arg)
|
| 318 |
+
elif isinstance(arg, str):
|
| 319 |
+
if arg == ':':
|
| 320 |
+
parameters.append(Extent())
|
| 321 |
+
else:
|
| 322 |
+
parameters.append(String(arg))
|
| 323 |
+
elif iterable(arg):
|
| 324 |
+
parameters.append(Extent(*arg))
|
| 325 |
+
else:
|
| 326 |
+
parameters.append(sympify(arg))
|
| 327 |
+
if len(args) == 0:
|
| 328 |
+
raise ValueError("Need at least one dimension")
|
| 329 |
+
return Attribute('dimension', parameters)
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
assumed_size = dimension('*')
|
| 333 |
+
|
| 334 |
+
def array(symbol, dim, intent=None, *, attrs=(), value=None, type=None):
|
| 335 |
+
""" Convenience function for creating a Variable instance for a Fortran array.
|
| 336 |
+
|
| 337 |
+
Parameters
|
| 338 |
+
==========
|
| 339 |
+
|
| 340 |
+
symbol : symbol
|
| 341 |
+
dim : Attribute or iterable
|
| 342 |
+
If dim is an ``Attribute`` it need to have the name 'dimension'. If it is
|
| 343 |
+
not an ``Attribute``, then it is passed to :func:`dimension` as ``*dim``
|
| 344 |
+
intent : str
|
| 345 |
+
One of: 'in', 'out', 'inout' or None
|
| 346 |
+
\\*\\*kwargs:
|
| 347 |
+
Keyword arguments for ``Variable`` ('type' & 'value')
|
| 348 |
+
|
| 349 |
+
Examples
|
| 350 |
+
========
|
| 351 |
+
|
| 352 |
+
>>> from sympy import fcode
|
| 353 |
+
>>> from sympy.codegen.ast import integer, real
|
| 354 |
+
>>> from sympy.codegen.fnodes import array
|
| 355 |
+
>>> arr = array('a', '*', 'in', type=integer)
|
| 356 |
+
>>> print(fcode(arr.as_Declaration(), source_format='free', standard=2003))
|
| 357 |
+
integer*4, dimension(*), intent(in) :: a
|
| 358 |
+
>>> x = array('x', [3, ':', ':'], intent='out', type=real)
|
| 359 |
+
>>> print(fcode(x.as_Declaration(value=1), source_format='free', standard=2003))
|
| 360 |
+
real*8, dimension(3, :, :), intent(out) :: x = 1
|
| 361 |
+
|
| 362 |
+
"""
|
| 363 |
+
if isinstance(dim, Attribute):
|
| 364 |
+
if str(dim.name) != 'dimension':
|
| 365 |
+
raise ValueError("Got an unexpected Attribute argument as dim: %s" % str(dim))
|
| 366 |
+
else:
|
| 367 |
+
dim = dimension(*dim)
|
| 368 |
+
|
| 369 |
+
attrs = list(attrs) + [dim]
|
| 370 |
+
if intent is not None:
|
| 371 |
+
if intent not in (intent_in, intent_out, intent_inout):
|
| 372 |
+
intent = {'in': intent_in, 'out': intent_out, 'inout': intent_inout}[intent]
|
| 373 |
+
attrs.append(intent)
|
| 374 |
+
if type is None:
|
| 375 |
+
return Variable.deduced(symbol, value=value, attrs=attrs)
|
| 376 |
+
else:
|
| 377 |
+
return Variable(symbol, type, value=value, attrs=attrs)
|
| 378 |
+
|
| 379 |
+
def _printable(arg):
|
| 380 |
+
return String(arg) if isinstance(arg, str) else sympify(arg)
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
def allocated(array):
|
| 384 |
+
""" Creates an AST node for a function call to Fortran's "allocated(...)"
|
| 385 |
+
|
| 386 |
+
Examples
|
| 387 |
+
========
|
| 388 |
+
|
| 389 |
+
>>> from sympy import fcode
|
| 390 |
+
>>> from sympy.codegen.fnodes import allocated
|
| 391 |
+
>>> alloc = allocated('x')
|
| 392 |
+
>>> fcode(alloc, source_format='free')
|
| 393 |
+
'allocated(x)'
|
| 394 |
+
|
| 395 |
+
"""
|
| 396 |
+
return FunctionCall('allocated', [_printable(array)])
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
def lbound(array, dim=None, kind=None):
|
| 400 |
+
""" Creates an AST node for a function call to Fortran's "lbound(...)"
|
| 401 |
+
|
| 402 |
+
Parameters
|
| 403 |
+
==========
|
| 404 |
+
|
| 405 |
+
array : Symbol or String
|
| 406 |
+
dim : expr
|
| 407 |
+
kind : expr
|
| 408 |
+
|
| 409 |
+
Examples
|
| 410 |
+
========
|
| 411 |
+
|
| 412 |
+
>>> from sympy import fcode
|
| 413 |
+
>>> from sympy.codegen.fnodes import lbound
|
| 414 |
+
>>> lb = lbound('arr', dim=2)
|
| 415 |
+
>>> fcode(lb, source_format='free')
|
| 416 |
+
'lbound(arr, 2)'
|
| 417 |
+
|
| 418 |
+
"""
|
| 419 |
+
return FunctionCall(
|
| 420 |
+
'lbound',
|
| 421 |
+
[_printable(array)] +
|
| 422 |
+
([_printable(dim)] if dim else []) +
|
| 423 |
+
([_printable(kind)] if kind else [])
|
| 424 |
+
)
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
def ubound(array, dim=None, kind=None):
|
| 428 |
+
return FunctionCall(
|
| 429 |
+
'ubound',
|
| 430 |
+
[_printable(array)] +
|
| 431 |
+
([_printable(dim)] if dim else []) +
|
| 432 |
+
([_printable(kind)] if kind else [])
|
| 433 |
+
)
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
def shape(source, kind=None):
|
| 437 |
+
""" Creates an AST node for a function call to Fortran's "shape(...)"
|
| 438 |
+
|
| 439 |
+
Parameters
|
| 440 |
+
==========
|
| 441 |
+
|
| 442 |
+
source : Symbol or String
|
| 443 |
+
kind : expr
|
| 444 |
+
|
| 445 |
+
Examples
|
| 446 |
+
========
|
| 447 |
+
|
| 448 |
+
>>> from sympy import fcode
|
| 449 |
+
>>> from sympy.codegen.fnodes import shape
|
| 450 |
+
>>> shp = shape('x')
|
| 451 |
+
>>> fcode(shp, source_format='free')
|
| 452 |
+
'shape(x)'
|
| 453 |
+
|
| 454 |
+
"""
|
| 455 |
+
return FunctionCall(
|
| 456 |
+
'shape',
|
| 457 |
+
[_printable(source)] +
|
| 458 |
+
([_printable(kind)] if kind else [])
|
| 459 |
+
)
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
def size(array, dim=None, kind=None):
|
| 463 |
+
""" Creates an AST node for a function call to Fortran's "size(...)"
|
| 464 |
+
|
| 465 |
+
Examples
|
| 466 |
+
========
|
| 467 |
+
|
| 468 |
+
>>> from sympy import fcode, Symbol
|
| 469 |
+
>>> from sympy.codegen.ast import FunctionDefinition, real, Return
|
| 470 |
+
>>> from sympy.codegen.fnodes import array, sum_, size
|
| 471 |
+
>>> a = Symbol('a', real=True)
|
| 472 |
+
>>> body = [Return((sum_(a**2)/size(a))**.5)]
|
| 473 |
+
>>> arr = array(a, dim=[':'], intent='in')
|
| 474 |
+
>>> fd = FunctionDefinition(real, 'rms', [arr], body)
|
| 475 |
+
>>> print(fcode(fd, source_format='free', standard=2003))
|
| 476 |
+
real*8 function rms(a)
|
| 477 |
+
real*8, dimension(:), intent(in) :: a
|
| 478 |
+
rms = sqrt(sum(a**2)*1d0/size(a))
|
| 479 |
+
end function
|
| 480 |
+
|
| 481 |
+
"""
|
| 482 |
+
return FunctionCall(
|
| 483 |
+
'size',
|
| 484 |
+
[_printable(array)] +
|
| 485 |
+
([_printable(dim)] if dim else []) +
|
| 486 |
+
([_printable(kind)] if kind else [])
|
| 487 |
+
)
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
def reshape(source, shape, pad=None, order=None):
|
| 491 |
+
""" Creates an AST node for a function call to Fortran's "reshape(...)"
|
| 492 |
+
|
| 493 |
+
Parameters
|
| 494 |
+
==========
|
| 495 |
+
|
| 496 |
+
source : Symbol or String
|
| 497 |
+
shape : ArrayExpr
|
| 498 |
+
|
| 499 |
+
"""
|
| 500 |
+
return FunctionCall(
|
| 501 |
+
'reshape',
|
| 502 |
+
[_printable(source), _printable(shape)] +
|
| 503 |
+
([_printable(pad)] if pad else []) +
|
| 504 |
+
([_printable(order)] if pad else [])
|
| 505 |
+
)
|
| 506 |
+
|
| 507 |
+
|
| 508 |
+
def bind_C(name=None):
|
| 509 |
+
""" Creates an Attribute ``bind_C`` with a name.
|
| 510 |
+
|
| 511 |
+
Parameters
|
| 512 |
+
==========
|
| 513 |
+
|
| 514 |
+
name : str
|
| 515 |
+
|
| 516 |
+
Examples
|
| 517 |
+
========
|
| 518 |
+
|
| 519 |
+
>>> from sympy import fcode, Symbol
|
| 520 |
+
>>> from sympy.codegen.ast import FunctionDefinition, real, Return
|
| 521 |
+
>>> from sympy.codegen.fnodes import array, sum_, bind_C
|
| 522 |
+
>>> a = Symbol('a', real=True)
|
| 523 |
+
>>> s = Symbol('s', integer=True)
|
| 524 |
+
>>> arr = array(a, dim=[s], intent='in')
|
| 525 |
+
>>> body = [Return((sum_(a**2)/s)**.5)]
|
| 526 |
+
>>> fd = FunctionDefinition(real, 'rms', [arr, s], body, attrs=[bind_C('rms')])
|
| 527 |
+
>>> print(fcode(fd, source_format='free', standard=2003))
|
| 528 |
+
real*8 function rms(a, s) bind(C, name="rms")
|
| 529 |
+
real*8, dimension(s), intent(in) :: a
|
| 530 |
+
integer*4 :: s
|
| 531 |
+
rms = sqrt(sum(a**2)/s)
|
| 532 |
+
end function
|
| 533 |
+
|
| 534 |
+
"""
|
| 535 |
+
return Attribute('bind_C', [String(name)] if name else [])
|
| 536 |
+
|
| 537 |
+
class GoTo(Token):
|
| 538 |
+
""" Represents a goto statement in Fortran
|
| 539 |
+
|
| 540 |
+
Examples
|
| 541 |
+
========
|
| 542 |
+
|
| 543 |
+
>>> from sympy.codegen.fnodes import GoTo
|
| 544 |
+
>>> go = GoTo([10, 20, 30], 'i')
|
| 545 |
+
>>> from sympy import fcode
|
| 546 |
+
>>> fcode(go, source_format='free')
|
| 547 |
+
'go to (10, 20, 30), i'
|
| 548 |
+
|
| 549 |
+
"""
|
| 550 |
+
__slots__ = _fields = ('labels', 'expr')
|
| 551 |
+
defaults = {'expr': none}
|
| 552 |
+
_construct_labels = staticmethod(_mk_Tuple)
|
| 553 |
+
_construct_expr = staticmethod(sympify)
|
| 554 |
+
|
| 555 |
+
|
| 556 |
+
class FortranReturn(Token):
|
| 557 |
+
""" AST node explicitly mapped to a fortran "return".
|
| 558 |
+
|
| 559 |
+
Explanation
|
| 560 |
+
===========
|
| 561 |
+
|
| 562 |
+
Because a return statement in fortran is different from C, and
|
| 563 |
+
in order to aid reuse of our codegen ASTs the ordinary
|
| 564 |
+
``.codegen.ast.Return`` is interpreted as assignment to
|
| 565 |
+
the result variable of the function. If one for some reason needs
|
| 566 |
+
to generate a fortran RETURN statement, this node should be used.
|
| 567 |
+
|
| 568 |
+
Examples
|
| 569 |
+
========
|
| 570 |
+
|
| 571 |
+
>>> from sympy.codegen.fnodes import FortranReturn
|
| 572 |
+
>>> from sympy import fcode
|
| 573 |
+
>>> fcode(FortranReturn('x'))
|
| 574 |
+
' return x'
|
| 575 |
+
|
| 576 |
+
"""
|
| 577 |
+
__slots__ = _fields = ('return_value',)
|
| 578 |
+
defaults = {'return_value': none}
|
| 579 |
+
_construct_return_value = staticmethod(sympify)
|
| 580 |
+
|
| 581 |
+
|
| 582 |
+
class FFunction(Function):
|
| 583 |
+
_required_standard = 77
|
| 584 |
+
|
| 585 |
+
def _fcode(self, printer):
|
| 586 |
+
name = self.__class__.__name__
|
| 587 |
+
if printer._settings['standard'] < self._required_standard:
|
| 588 |
+
raise NotImplementedError("%s requires Fortran %d or newer" %
|
| 589 |
+
(name, self._required_standard))
|
| 590 |
+
return '{}({})'.format(name, ', '.join(map(printer._print, self.args)))
|
| 591 |
+
|
| 592 |
+
|
| 593 |
+
class F95Function(FFunction):
|
| 594 |
+
_required_standard = 95
|
| 595 |
+
|
| 596 |
+
|
| 597 |
+
class isign(FFunction):
|
| 598 |
+
""" Fortran sign intrinsic for integer arguments. """
|
| 599 |
+
nargs = 2
|
| 600 |
+
|
| 601 |
+
|
| 602 |
+
class dsign(FFunction):
|
| 603 |
+
""" Fortran sign intrinsic for double precision arguments. """
|
| 604 |
+
nargs = 2
|
| 605 |
+
|
| 606 |
+
|
| 607 |
+
class cmplx(FFunction):
|
| 608 |
+
""" Fortran complex conversion function. """
|
| 609 |
+
nargs = 2 # may be extended to (2, 3) at a later point
|
| 610 |
+
|
| 611 |
+
|
| 612 |
+
class kind(FFunction):
|
| 613 |
+
""" Fortran kind function. """
|
| 614 |
+
nargs = 1
|
| 615 |
+
|
| 616 |
+
|
| 617 |
+
class merge(F95Function):
|
| 618 |
+
""" Fortran merge function """
|
| 619 |
+
nargs = 3
|
| 620 |
+
|
| 621 |
+
|
| 622 |
+
class _literal(Float):
|
| 623 |
+
_token = None # type: str
|
| 624 |
+
_decimals = None # type: int
|
| 625 |
+
|
| 626 |
+
def _fcode(self, printer, *args, **kwargs):
|
| 627 |
+
mantissa, sgnd_ex = ('%.{}e'.format(self._decimals) % self).split('e')
|
| 628 |
+
mantissa = mantissa.strip('0').rstrip('.')
|
| 629 |
+
ex_sgn, ex_num = sgnd_ex[0], sgnd_ex[1:].lstrip('0')
|
| 630 |
+
ex_sgn = '' if ex_sgn == '+' else ex_sgn
|
| 631 |
+
return (mantissa or '0') + self._token + ex_sgn + (ex_num or '0')
|
| 632 |
+
|
| 633 |
+
|
| 634 |
+
class literal_sp(_literal):
|
| 635 |
+
""" Fortran single precision real literal """
|
| 636 |
+
_token = 'e'
|
| 637 |
+
_decimals = 9
|
| 638 |
+
|
| 639 |
+
|
| 640 |
+
class literal_dp(_literal):
|
| 641 |
+
""" Fortran double precision real literal """
|
| 642 |
+
_token = 'd'
|
| 643 |
+
_decimals = 17
|
| 644 |
+
|
| 645 |
+
|
| 646 |
+
class sum_(Token, Expr):
|
| 647 |
+
__slots__ = _fields = ('array', 'dim', 'mask')
|
| 648 |
+
defaults = {'dim': none, 'mask': none}
|
| 649 |
+
_construct_array = staticmethod(sympify)
|
| 650 |
+
_construct_dim = staticmethod(sympify)
|
| 651 |
+
|
| 652 |
+
|
| 653 |
+
class product_(Token, Expr):
|
| 654 |
+
__slots__ = _fields = ('array', 'dim', 'mask')
|
| 655 |
+
defaults = {'dim': none, 'mask': none}
|
| 656 |
+
_construct_array = staticmethod(sympify)
|
| 657 |
+
_construct_dim = staticmethod(sympify)
|
evalkit_tf446/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))
|
evalkit_tf446/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)
|
evalkit_tf446/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)
|
evalkit_tf446/lib/python3.10/site-packages/sympy/functions/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (5.82 kB). View file
|
|
|
evalkit_tf446/lib/python3.10/site-packages/sympy/functions/combinatorial/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
# Stub __init__.py for sympy.functions.combinatorial
|
evalkit_tf446/lib/python3.10/site-packages/sympy/functions/combinatorial/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (188 Bytes). View file
|
|
|
evalkit_tf446/lib/python3.10/site-packages/sympy/functions/combinatorial/__pycache__/numbers.cpython-310.pyc
ADDED
|
Binary file (92.7 kB). View file
|
|
|
evalkit_tf446/lib/python3.10/site-packages/sympy/functions/combinatorial/factorials.py
ADDED
|
@@ -0,0 +1,1133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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.core.function import Function, ArgumentIndexError, PoleError
|
| 7 |
+
from sympy.core.logic import fuzzy_and
|
| 8 |
+
from sympy.core.numbers import Integer, pi, I
|
| 9 |
+
from sympy.core.relational import Eq
|
| 10 |
+
from sympy.external.gmpy import gmpy as _gmpy
|
| 11 |
+
from sympy.ntheory import sieve
|
| 12 |
+
from sympy.ntheory.residue_ntheory import binomial_mod
|
| 13 |
+
from sympy.polys.polytools import Poly
|
| 14 |
+
|
| 15 |
+
from math import factorial as _factorial, prod, sqrt as _sqrt
|
| 16 |
+
|
| 17 |
+
class CombinatorialFunction(Function):
|
| 18 |
+
"""Base class for combinatorial functions. """
|
| 19 |
+
|
| 20 |
+
def _eval_simplify(self, **kwargs):
|
| 21 |
+
from sympy.simplify.combsimp import combsimp
|
| 22 |
+
# combinatorial function with non-integer arguments is
|
| 23 |
+
# automatically passed to gammasimp
|
| 24 |
+
expr = combsimp(self)
|
| 25 |
+
measure = kwargs['measure']
|
| 26 |
+
if measure(expr) <= kwargs['ratio']*measure(self):
|
| 27 |
+
return expr
|
| 28 |
+
return self
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
###############################################################################
|
| 32 |
+
######################## FACTORIAL and MULTI-FACTORIAL ########################
|
| 33 |
+
###############################################################################
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class factorial(CombinatorialFunction):
|
| 37 |
+
r"""Implementation of factorial function over nonnegative integers.
|
| 38 |
+
By convention (consistent with the gamma function and the binomial
|
| 39 |
+
coefficients), factorial of a negative integer is complex infinity.
|
| 40 |
+
|
| 41 |
+
The factorial is very important in combinatorics where it gives
|
| 42 |
+
the number of ways in which `n` objects can be permuted. It also
|
| 43 |
+
arises in calculus, probability, number theory, etc.
|
| 44 |
+
|
| 45 |
+
There is strict relation of factorial with gamma function. In
|
| 46 |
+
fact `n! = gamma(n+1)` for nonnegative integers. Rewrite of this
|
| 47 |
+
kind is very useful in case of combinatorial simplification.
|
| 48 |
+
|
| 49 |
+
Computation of the factorial is done using two algorithms. For
|
| 50 |
+
small arguments a precomputed look up table is used. However for bigger
|
| 51 |
+
input algorithm Prime-Swing is used. It is the fastest algorithm
|
| 52 |
+
known and computes `n!` via prime factorization of special class
|
| 53 |
+
of numbers, called here the 'Swing Numbers'.
|
| 54 |
+
|
| 55 |
+
Examples
|
| 56 |
+
========
|
| 57 |
+
|
| 58 |
+
>>> from sympy import Symbol, factorial, S
|
| 59 |
+
>>> n = Symbol('n', integer=True)
|
| 60 |
+
|
| 61 |
+
>>> factorial(0)
|
| 62 |
+
1
|
| 63 |
+
|
| 64 |
+
>>> factorial(7)
|
| 65 |
+
5040
|
| 66 |
+
|
| 67 |
+
>>> factorial(-2)
|
| 68 |
+
zoo
|
| 69 |
+
|
| 70 |
+
>>> factorial(n)
|
| 71 |
+
factorial(n)
|
| 72 |
+
|
| 73 |
+
>>> factorial(2*n)
|
| 74 |
+
factorial(2*n)
|
| 75 |
+
|
| 76 |
+
>>> factorial(S(1)/2)
|
| 77 |
+
factorial(1/2)
|
| 78 |
+
|
| 79 |
+
See Also
|
| 80 |
+
========
|
| 81 |
+
|
| 82 |
+
factorial2, RisingFactorial, FallingFactorial
|
| 83 |
+
"""
|
| 84 |
+
|
| 85 |
+
def fdiff(self, argindex=1):
|
| 86 |
+
from sympy.functions.special.gamma_functions import (gamma, polygamma)
|
| 87 |
+
if argindex == 1:
|
| 88 |
+
return gamma(self.args[0] + 1)*polygamma(0, self.args[0] + 1)
|
| 89 |
+
else:
|
| 90 |
+
raise ArgumentIndexError(self, argindex)
|
| 91 |
+
|
| 92 |
+
_small_swing = [
|
| 93 |
+
1, 1, 1, 3, 3, 15, 5, 35, 35, 315, 63, 693, 231, 3003, 429, 6435, 6435, 109395,
|
| 94 |
+
12155, 230945, 46189, 969969, 88179, 2028117, 676039, 16900975, 1300075,
|
| 95 |
+
35102025, 5014575, 145422675, 9694845, 300540195, 300540195
|
| 96 |
+
]
|
| 97 |
+
|
| 98 |
+
_small_factorials: list[int] = []
|
| 99 |
+
|
| 100 |
+
@classmethod
|
| 101 |
+
def _swing(cls, n):
|
| 102 |
+
if n < 33:
|
| 103 |
+
return cls._small_swing[n]
|
| 104 |
+
else:
|
| 105 |
+
N, primes = int(_sqrt(n)), []
|
| 106 |
+
|
| 107 |
+
for prime in sieve.primerange(3, N + 1):
|
| 108 |
+
p, q = 1, n
|
| 109 |
+
|
| 110 |
+
while True:
|
| 111 |
+
q //= prime
|
| 112 |
+
|
| 113 |
+
if q > 0:
|
| 114 |
+
if q & 1 == 1:
|
| 115 |
+
p *= prime
|
| 116 |
+
else:
|
| 117 |
+
break
|
| 118 |
+
|
| 119 |
+
if p > 1:
|
| 120 |
+
primes.append(p)
|
| 121 |
+
|
| 122 |
+
for prime in sieve.primerange(N + 1, n//3 + 1):
|
| 123 |
+
if (n // prime) & 1 == 1:
|
| 124 |
+
primes.append(prime)
|
| 125 |
+
|
| 126 |
+
L_product = prod(sieve.primerange(n//2 + 1, n + 1))
|
| 127 |
+
R_product = prod(primes)
|
| 128 |
+
|
| 129 |
+
return L_product*R_product
|
| 130 |
+
|
| 131 |
+
@classmethod
|
| 132 |
+
def _recursive(cls, n):
|
| 133 |
+
if n < 2:
|
| 134 |
+
return 1
|
| 135 |
+
else:
|
| 136 |
+
return (cls._recursive(n//2)**2)*cls._swing(n)
|
| 137 |
+
|
| 138 |
+
@classmethod
|
| 139 |
+
def eval(cls, n):
|
| 140 |
+
n = sympify(n)
|
| 141 |
+
|
| 142 |
+
if n.is_Number:
|
| 143 |
+
if n.is_zero:
|
| 144 |
+
return S.One
|
| 145 |
+
elif n is S.Infinity:
|
| 146 |
+
return S.Infinity
|
| 147 |
+
elif n.is_Integer:
|
| 148 |
+
if n.is_negative:
|
| 149 |
+
return S.ComplexInfinity
|
| 150 |
+
else:
|
| 151 |
+
n = n.p
|
| 152 |
+
|
| 153 |
+
if n < 20:
|
| 154 |
+
if not cls._small_factorials:
|
| 155 |
+
result = 1
|
| 156 |
+
for i in range(1, 20):
|
| 157 |
+
result *= i
|
| 158 |
+
cls._small_factorials.append(result)
|
| 159 |
+
result = cls._small_factorials[n-1]
|
| 160 |
+
|
| 161 |
+
# GMPY factorial is faster, use it when available
|
| 162 |
+
#
|
| 163 |
+
# XXX: There is a sympy.external.gmpy.factorial function
|
| 164 |
+
# which provides gmpy.fac if available or the flint version
|
| 165 |
+
# if flint is used. It could be used here to avoid the
|
| 166 |
+
# conditional logic but it needs to be checked whether the
|
| 167 |
+
# pure Python fallback used there is as fast as the
|
| 168 |
+
# fallback used here (perhaps the fallback here should be
|
| 169 |
+
# moved to sympy.external.ntheory).
|
| 170 |
+
elif _gmpy is not None:
|
| 171 |
+
result = _gmpy.fac(n)
|
| 172 |
+
|
| 173 |
+
else:
|
| 174 |
+
bits = bin(n).count('1')
|
| 175 |
+
result = cls._recursive(n)*2**(n - bits)
|
| 176 |
+
|
| 177 |
+
return Integer(result)
|
| 178 |
+
|
| 179 |
+
def _facmod(self, n, q):
|
| 180 |
+
res, N = 1, int(_sqrt(n))
|
| 181 |
+
|
| 182 |
+
# Exponent of prime p in n! is e_p(n) = [n/p] + [n/p**2] + ...
|
| 183 |
+
# for p > sqrt(n), e_p(n) < sqrt(n), the primes with [n/p] = m,
|
| 184 |
+
# occur consecutively and are grouped together in pw[m] for
|
| 185 |
+
# simultaneous exponentiation at a later stage
|
| 186 |
+
pw = [1]*N
|
| 187 |
+
|
| 188 |
+
m = 2 # to initialize the if condition below
|
| 189 |
+
for prime in sieve.primerange(2, n + 1):
|
| 190 |
+
if m > 1:
|
| 191 |
+
m, y = 0, n // prime
|
| 192 |
+
while y:
|
| 193 |
+
m += y
|
| 194 |
+
y //= prime
|
| 195 |
+
if m < N:
|
| 196 |
+
pw[m] = pw[m]*prime % q
|
| 197 |
+
else:
|
| 198 |
+
res = res*pow(prime, m, q) % q
|
| 199 |
+
|
| 200 |
+
for ex, bs in enumerate(pw):
|
| 201 |
+
if ex == 0 or bs == 1:
|
| 202 |
+
continue
|
| 203 |
+
if bs == 0:
|
| 204 |
+
return 0
|
| 205 |
+
res = res*pow(bs, ex, q) % q
|
| 206 |
+
|
| 207 |
+
return res
|
| 208 |
+
|
| 209 |
+
def _eval_Mod(self, q):
|
| 210 |
+
n = self.args[0]
|
| 211 |
+
if n.is_integer and n.is_nonnegative and q.is_integer:
|
| 212 |
+
aq = abs(q)
|
| 213 |
+
d = aq - n
|
| 214 |
+
if d.is_nonpositive:
|
| 215 |
+
return S.Zero
|
| 216 |
+
else:
|
| 217 |
+
isprime = aq.is_prime
|
| 218 |
+
if d == 1:
|
| 219 |
+
# Apply Wilson's theorem (if a natural number n > 1
|
| 220 |
+
# is a prime number, then (n-1)! = -1 mod n) and
|
| 221 |
+
# its inverse (if n > 4 is a composite number, then
|
| 222 |
+
# (n-1)! = 0 mod n)
|
| 223 |
+
if isprime:
|
| 224 |
+
return -1 % q
|
| 225 |
+
elif isprime is False and (aq - 6).is_nonnegative:
|
| 226 |
+
return S.Zero
|
| 227 |
+
elif n.is_Integer and q.is_Integer:
|
| 228 |
+
n, d, aq = map(int, (n, d, aq))
|
| 229 |
+
if isprime and (d - 1 < n):
|
| 230 |
+
fc = self._facmod(d - 1, aq)
|
| 231 |
+
fc = pow(fc, aq - 2, aq)
|
| 232 |
+
if d%2:
|
| 233 |
+
fc = -fc
|
| 234 |
+
else:
|
| 235 |
+
fc = self._facmod(n, aq)
|
| 236 |
+
|
| 237 |
+
return fc % q
|
| 238 |
+
|
| 239 |
+
def _eval_rewrite_as_gamma(self, n, piecewise=True, **kwargs):
|
| 240 |
+
from sympy.functions.special.gamma_functions import gamma
|
| 241 |
+
return gamma(n + 1)
|
| 242 |
+
|
| 243 |
+
def _eval_rewrite_as_Product(self, n, **kwargs):
|
| 244 |
+
from sympy.concrete.products import Product
|
| 245 |
+
if n.is_nonnegative and n.is_integer:
|
| 246 |
+
i = Dummy('i', integer=True)
|
| 247 |
+
return Product(i, (i, 1, n))
|
| 248 |
+
|
| 249 |
+
def _eval_is_integer(self):
|
| 250 |
+
if self.args[0].is_integer and self.args[0].is_nonnegative:
|
| 251 |
+
return True
|
| 252 |
+
|
| 253 |
+
def _eval_is_positive(self):
|
| 254 |
+
if self.args[0].is_integer and self.args[0].is_nonnegative:
|
| 255 |
+
return True
|
| 256 |
+
|
| 257 |
+
def _eval_is_even(self):
|
| 258 |
+
x = self.args[0]
|
| 259 |
+
if x.is_integer and x.is_nonnegative:
|
| 260 |
+
return (x - 2).is_nonnegative
|
| 261 |
+
|
| 262 |
+
def _eval_is_composite(self):
|
| 263 |
+
x = self.args[0]
|
| 264 |
+
if x.is_integer and x.is_nonnegative:
|
| 265 |
+
return (x - 3).is_nonnegative
|
| 266 |
+
|
| 267 |
+
def _eval_is_real(self):
|
| 268 |
+
x = self.args[0]
|
| 269 |
+
if x.is_nonnegative or x.is_noninteger:
|
| 270 |
+
return True
|
| 271 |
+
|
| 272 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0):
|
| 273 |
+
arg = self.args[0].as_leading_term(x)
|
| 274 |
+
arg0 = arg.subs(x, 0)
|
| 275 |
+
if arg0.is_zero:
|
| 276 |
+
return S.One
|
| 277 |
+
elif not arg0.is_infinite:
|
| 278 |
+
return self.func(arg)
|
| 279 |
+
raise PoleError("Cannot expand %s around 0" % (self))
|
| 280 |
+
|
| 281 |
+
class MultiFactorial(CombinatorialFunction):
|
| 282 |
+
pass
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
class subfactorial(CombinatorialFunction):
|
| 286 |
+
r"""The subfactorial counts the derangements of $n$ items and is
|
| 287 |
+
defined for non-negative integers as:
|
| 288 |
+
|
| 289 |
+
.. math:: !n = \begin{cases} 1 & n = 0 \\ 0 & n = 1 \\
|
| 290 |
+
(n-1)(!(n-1) + !(n-2)) & n > 1 \end{cases}
|
| 291 |
+
|
| 292 |
+
It can also be written as ``int(round(n!/exp(1)))`` but the
|
| 293 |
+
recursive definition with caching is implemented for this function.
|
| 294 |
+
|
| 295 |
+
An interesting analytic expression is the following [2]_
|
| 296 |
+
|
| 297 |
+
.. math:: !x = \Gamma(x + 1, -1)/e
|
| 298 |
+
|
| 299 |
+
which is valid for non-negative integers `x`. The above formula
|
| 300 |
+
is not very useful in case of non-integers. `\Gamma(x + 1, -1)` is
|
| 301 |
+
single-valued only for integral arguments `x`, elsewhere on the positive
|
| 302 |
+
real axis it has an infinite number of branches none of which are real.
|
| 303 |
+
|
| 304 |
+
References
|
| 305 |
+
==========
|
| 306 |
+
|
| 307 |
+
.. [1] https://en.wikipedia.org/wiki/Subfactorial
|
| 308 |
+
.. [2] https://mathworld.wolfram.com/Subfactorial.html
|
| 309 |
+
|
| 310 |
+
Examples
|
| 311 |
+
========
|
| 312 |
+
|
| 313 |
+
>>> from sympy import subfactorial
|
| 314 |
+
>>> from sympy.abc import n
|
| 315 |
+
>>> subfactorial(n + 1)
|
| 316 |
+
subfactorial(n + 1)
|
| 317 |
+
>>> subfactorial(5)
|
| 318 |
+
44
|
| 319 |
+
|
| 320 |
+
See Also
|
| 321 |
+
========
|
| 322 |
+
|
| 323 |
+
factorial, uppergamma,
|
| 324 |
+
sympy.utilities.iterables.generate_derangements
|
| 325 |
+
"""
|
| 326 |
+
|
| 327 |
+
@classmethod
|
| 328 |
+
@cacheit
|
| 329 |
+
def _eval(self, n):
|
| 330 |
+
if not n:
|
| 331 |
+
return S.One
|
| 332 |
+
elif n == 1:
|
| 333 |
+
return S.Zero
|
| 334 |
+
else:
|
| 335 |
+
z1, z2 = 1, 0
|
| 336 |
+
for i in range(2, n + 1):
|
| 337 |
+
z1, z2 = z2, (i - 1)*(z2 + z1)
|
| 338 |
+
return z2
|
| 339 |
+
|
| 340 |
+
@classmethod
|
| 341 |
+
def eval(cls, arg):
|
| 342 |
+
if arg.is_Number:
|
| 343 |
+
if arg.is_Integer and arg.is_nonnegative:
|
| 344 |
+
return cls._eval(arg)
|
| 345 |
+
elif arg is S.NaN:
|
| 346 |
+
return S.NaN
|
| 347 |
+
elif arg is S.Infinity:
|
| 348 |
+
return S.Infinity
|
| 349 |
+
|
| 350 |
+
def _eval_is_even(self):
|
| 351 |
+
if self.args[0].is_odd and self.args[0].is_nonnegative:
|
| 352 |
+
return True
|
| 353 |
+
|
| 354 |
+
def _eval_is_integer(self):
|
| 355 |
+
if self.args[0].is_integer and self.args[0].is_nonnegative:
|
| 356 |
+
return True
|
| 357 |
+
|
| 358 |
+
def _eval_rewrite_as_factorial(self, arg, **kwargs):
|
| 359 |
+
from sympy.concrete.summations import summation
|
| 360 |
+
i = Dummy('i')
|
| 361 |
+
f = S.NegativeOne**i / factorial(i)
|
| 362 |
+
return factorial(arg) * summation(f, (i, 0, arg))
|
| 363 |
+
|
| 364 |
+
def _eval_rewrite_as_gamma(self, arg, piecewise=True, **kwargs):
|
| 365 |
+
from sympy.functions.elementary.exponential import exp
|
| 366 |
+
from sympy.functions.special.gamma_functions import (gamma, lowergamma)
|
| 367 |
+
return (S.NegativeOne**(arg + 1)*exp(-I*pi*arg)*lowergamma(arg + 1, -1)
|
| 368 |
+
+ gamma(arg + 1))*exp(-1)
|
| 369 |
+
|
| 370 |
+
def _eval_rewrite_as_uppergamma(self, arg, **kwargs):
|
| 371 |
+
from sympy.functions.special.gamma_functions import uppergamma
|
| 372 |
+
return uppergamma(arg + 1, -1)/S.Exp1
|
| 373 |
+
|
| 374 |
+
def _eval_is_nonnegative(self):
|
| 375 |
+
if self.args[0].is_integer and self.args[0].is_nonnegative:
|
| 376 |
+
return True
|
| 377 |
+
|
| 378 |
+
def _eval_is_odd(self):
|
| 379 |
+
if self.args[0].is_even and self.args[0].is_nonnegative:
|
| 380 |
+
return True
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
class factorial2(CombinatorialFunction):
|
| 384 |
+
r"""The double factorial `n!!`, not to be confused with `(n!)!`
|
| 385 |
+
|
| 386 |
+
The double factorial is defined for nonnegative integers and for odd
|
| 387 |
+
negative integers as:
|
| 388 |
+
|
| 389 |
+
.. math:: n!! = \begin{cases} 1 & n = 0 \\
|
| 390 |
+
n(n-2)(n-4) \cdots 1 & n\ \text{positive odd} \\
|
| 391 |
+
n(n-2)(n-4) \cdots 2 & n\ \text{positive even} \\
|
| 392 |
+
(n+2)!!/(n+2) & n\ \text{negative odd} \end{cases}
|
| 393 |
+
|
| 394 |
+
References
|
| 395 |
+
==========
|
| 396 |
+
|
| 397 |
+
.. [1] https://en.wikipedia.org/wiki/Double_factorial
|
| 398 |
+
|
| 399 |
+
Examples
|
| 400 |
+
========
|
| 401 |
+
|
| 402 |
+
>>> from sympy import factorial2, var
|
| 403 |
+
>>> n = var('n')
|
| 404 |
+
>>> n
|
| 405 |
+
n
|
| 406 |
+
>>> factorial2(n + 1)
|
| 407 |
+
factorial2(n + 1)
|
| 408 |
+
>>> factorial2(5)
|
| 409 |
+
15
|
| 410 |
+
>>> factorial2(-1)
|
| 411 |
+
1
|
| 412 |
+
>>> factorial2(-5)
|
| 413 |
+
1/3
|
| 414 |
+
|
| 415 |
+
See Also
|
| 416 |
+
========
|
| 417 |
+
|
| 418 |
+
factorial, RisingFactorial, FallingFactorial
|
| 419 |
+
"""
|
| 420 |
+
|
| 421 |
+
@classmethod
|
| 422 |
+
def eval(cls, arg):
|
| 423 |
+
# TODO: extend this to complex numbers?
|
| 424 |
+
|
| 425 |
+
if arg.is_Number:
|
| 426 |
+
if not arg.is_Integer:
|
| 427 |
+
raise ValueError("argument must be nonnegative integer "
|
| 428 |
+
"or negative odd integer")
|
| 429 |
+
|
| 430 |
+
# This implementation is faster than the recursive one
|
| 431 |
+
# It also avoids "maximum recursion depth exceeded" runtime error
|
| 432 |
+
if arg.is_nonnegative:
|
| 433 |
+
if arg.is_even:
|
| 434 |
+
k = arg / 2
|
| 435 |
+
return 2**k * factorial(k)
|
| 436 |
+
return factorial(arg) / factorial2(arg - 1)
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
if arg.is_odd:
|
| 440 |
+
return arg*(S.NegativeOne)**((1 - arg)/2) / factorial2(-arg)
|
| 441 |
+
raise ValueError("argument must be nonnegative integer "
|
| 442 |
+
"or negative odd integer")
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
def _eval_is_even(self):
|
| 446 |
+
# Double factorial is even for every positive even input
|
| 447 |
+
n = self.args[0]
|
| 448 |
+
if n.is_integer:
|
| 449 |
+
if n.is_odd:
|
| 450 |
+
return False
|
| 451 |
+
if n.is_even:
|
| 452 |
+
if n.is_positive:
|
| 453 |
+
return True
|
| 454 |
+
if n.is_zero:
|
| 455 |
+
return False
|
| 456 |
+
|
| 457 |
+
def _eval_is_integer(self):
|
| 458 |
+
# Double factorial is an integer for every nonnegative input, and for
|
| 459 |
+
# -1 and -3
|
| 460 |
+
n = self.args[0]
|
| 461 |
+
if n.is_integer:
|
| 462 |
+
if (n + 1).is_nonnegative:
|
| 463 |
+
return True
|
| 464 |
+
if n.is_odd:
|
| 465 |
+
return (n + 3).is_nonnegative
|
| 466 |
+
|
| 467 |
+
def _eval_is_odd(self):
|
| 468 |
+
# Double factorial is odd for every odd input not smaller than -3, and
|
| 469 |
+
# for 0
|
| 470 |
+
n = self.args[0]
|
| 471 |
+
if n.is_odd:
|
| 472 |
+
return (n + 3).is_nonnegative
|
| 473 |
+
if n.is_even:
|
| 474 |
+
if n.is_positive:
|
| 475 |
+
return False
|
| 476 |
+
if n.is_zero:
|
| 477 |
+
return True
|
| 478 |
+
|
| 479 |
+
def _eval_is_positive(self):
|
| 480 |
+
# Double factorial is positive for every nonnegative input, and for
|
| 481 |
+
# every odd negative input which is of the form -1-4k for an
|
| 482 |
+
# nonnegative integer k
|
| 483 |
+
n = self.args[0]
|
| 484 |
+
if n.is_integer:
|
| 485 |
+
if (n + 1).is_nonnegative:
|
| 486 |
+
return True
|
| 487 |
+
if n.is_odd:
|
| 488 |
+
return ((n + 1) / 2).is_even
|
| 489 |
+
|
| 490 |
+
def _eval_rewrite_as_gamma(self, n, piecewise=True, **kwargs):
|
| 491 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 492 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
| 493 |
+
from sympy.functions.special.gamma_functions import gamma
|
| 494 |
+
return 2**(n/2)*gamma(n/2 + 1) * Piecewise((1, Eq(Mod(n, 2), 0)),
|
| 495 |
+
(sqrt(2/pi), Eq(Mod(n, 2), 1)))
|
| 496 |
+
|
| 497 |
+
|
| 498 |
+
###############################################################################
|
| 499 |
+
######################## RISING and FALLING FACTORIALS ########################
|
| 500 |
+
###############################################################################
|
| 501 |
+
|
| 502 |
+
|
| 503 |
+
class RisingFactorial(CombinatorialFunction):
|
| 504 |
+
r"""
|
| 505 |
+
Rising factorial (also called Pochhammer symbol [1]_) is a double valued
|
| 506 |
+
function arising in concrete mathematics, hypergeometric functions
|
| 507 |
+
and series expansions. It is defined by:
|
| 508 |
+
|
| 509 |
+
.. math:: \texttt{rf(y, k)} = (x)^k = x \cdot (x+1) \cdots (x+k-1)
|
| 510 |
+
|
| 511 |
+
where `x` can be arbitrary expression and `k` is an integer. For
|
| 512 |
+
more information check "Concrete mathematics" by Graham, pp. 66
|
| 513 |
+
or visit https://mathworld.wolfram.com/RisingFactorial.html page.
|
| 514 |
+
|
| 515 |
+
When `x` is a `~.Poly` instance of degree $\ge 1$ with a single variable,
|
| 516 |
+
`(x)^k = x(y) \cdot x(y+1) \cdots x(y+k-1)`, where `y` is the
|
| 517 |
+
variable of `x`. This is as described in [2]_.
|
| 518 |
+
|
| 519 |
+
Examples
|
| 520 |
+
========
|
| 521 |
+
|
| 522 |
+
>>> from sympy import rf, Poly
|
| 523 |
+
>>> from sympy.abc import x
|
| 524 |
+
>>> rf(x, 0)
|
| 525 |
+
1
|
| 526 |
+
>>> rf(1, 5)
|
| 527 |
+
120
|
| 528 |
+
>>> rf(x, 5) == x*(1 + x)*(2 + x)*(3 + x)*(4 + x)
|
| 529 |
+
True
|
| 530 |
+
>>> rf(Poly(x**3, x), 2)
|
| 531 |
+
Poly(x**6 + 3*x**5 + 3*x**4 + x**3, x, domain='ZZ')
|
| 532 |
+
|
| 533 |
+
Rewriting is complicated unless the relationship between
|
| 534 |
+
the arguments is known, but rising factorial can
|
| 535 |
+
be rewritten in terms of gamma, factorial, binomial,
|
| 536 |
+
and falling factorial.
|
| 537 |
+
|
| 538 |
+
>>> from sympy import Symbol, factorial, ff, binomial, gamma
|
| 539 |
+
>>> n = Symbol('n', integer=True, positive=True)
|
| 540 |
+
>>> R = rf(n, n + 2)
|
| 541 |
+
>>> for i in (rf, ff, factorial, binomial, gamma):
|
| 542 |
+
... R.rewrite(i)
|
| 543 |
+
...
|
| 544 |
+
RisingFactorial(n, n + 2)
|
| 545 |
+
FallingFactorial(2*n + 1, n + 2)
|
| 546 |
+
factorial(2*n + 1)/factorial(n - 1)
|
| 547 |
+
binomial(2*n + 1, n + 2)*factorial(n + 2)
|
| 548 |
+
gamma(2*n + 2)/gamma(n)
|
| 549 |
+
|
| 550 |
+
See Also
|
| 551 |
+
========
|
| 552 |
+
|
| 553 |
+
factorial, factorial2, FallingFactorial
|
| 554 |
+
|
| 555 |
+
References
|
| 556 |
+
==========
|
| 557 |
+
|
| 558 |
+
.. [1] https://en.wikipedia.org/wiki/Pochhammer_symbol
|
| 559 |
+
.. [2] Peter Paule, "Greatest Factorial Factorization and Symbolic
|
| 560 |
+
Summation", Journal of Symbolic Computation, vol. 20, pp. 235-268,
|
| 561 |
+
1995.
|
| 562 |
+
|
| 563 |
+
"""
|
| 564 |
+
|
| 565 |
+
@classmethod
|
| 566 |
+
def eval(cls, x, k):
|
| 567 |
+
x = sympify(x)
|
| 568 |
+
k = sympify(k)
|
| 569 |
+
|
| 570 |
+
if x is S.NaN or k is S.NaN:
|
| 571 |
+
return S.NaN
|
| 572 |
+
elif x is S.One:
|
| 573 |
+
return factorial(k)
|
| 574 |
+
elif k.is_Integer:
|
| 575 |
+
if k.is_zero:
|
| 576 |
+
return S.One
|
| 577 |
+
else:
|
| 578 |
+
if k.is_positive:
|
| 579 |
+
if x is S.Infinity:
|
| 580 |
+
return S.Infinity
|
| 581 |
+
elif x is S.NegativeInfinity:
|
| 582 |
+
if k.is_odd:
|
| 583 |
+
return S.NegativeInfinity
|
| 584 |
+
else:
|
| 585 |
+
return S.Infinity
|
| 586 |
+
else:
|
| 587 |
+
if isinstance(x, Poly):
|
| 588 |
+
gens = x.gens
|
| 589 |
+
if len(gens)!= 1:
|
| 590 |
+
raise ValueError("rf only defined for "
|
| 591 |
+
"polynomials on one generator")
|
| 592 |
+
else:
|
| 593 |
+
return reduce(lambda r, i:
|
| 594 |
+
r*(x.shift(i)),
|
| 595 |
+
range(int(k)), 1)
|
| 596 |
+
else:
|
| 597 |
+
return reduce(lambda r, i: r*(x + i),
|
| 598 |
+
range(int(k)), 1)
|
| 599 |
+
|
| 600 |
+
else:
|
| 601 |
+
if x is S.Infinity:
|
| 602 |
+
return S.Infinity
|
| 603 |
+
elif x is S.NegativeInfinity:
|
| 604 |
+
return S.Infinity
|
| 605 |
+
else:
|
| 606 |
+
if isinstance(x, Poly):
|
| 607 |
+
gens = x.gens
|
| 608 |
+
if len(gens)!= 1:
|
| 609 |
+
raise ValueError("rf only defined for "
|
| 610 |
+
"polynomials on one generator")
|
| 611 |
+
else:
|
| 612 |
+
return 1/reduce(lambda r, i:
|
| 613 |
+
r*(x.shift(-i)),
|
| 614 |
+
range(1, abs(int(k)) + 1), 1)
|
| 615 |
+
else:
|
| 616 |
+
return 1/reduce(lambda r, i:
|
| 617 |
+
r*(x - i),
|
| 618 |
+
range(1, abs(int(k)) + 1), 1)
|
| 619 |
+
|
| 620 |
+
if k.is_integer == False:
|
| 621 |
+
if x.is_integer and x.is_negative:
|
| 622 |
+
return S.Zero
|
| 623 |
+
|
| 624 |
+
def _eval_rewrite_as_gamma(self, x, k, piecewise=True, **kwargs):
|
| 625 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
| 626 |
+
from sympy.functions.special.gamma_functions import gamma
|
| 627 |
+
if not piecewise:
|
| 628 |
+
if (x <= 0) == True:
|
| 629 |
+
return S.NegativeOne**k*gamma(1 - x) / gamma(-k - x + 1)
|
| 630 |
+
return gamma(x + k) / gamma(x)
|
| 631 |
+
return Piecewise(
|
| 632 |
+
(gamma(x + k) / gamma(x), x > 0),
|
| 633 |
+
(S.NegativeOne**k*gamma(1 - x) / gamma(-k - x + 1), True))
|
| 634 |
+
|
| 635 |
+
def _eval_rewrite_as_FallingFactorial(self, x, k, **kwargs):
|
| 636 |
+
return FallingFactorial(x + k - 1, k)
|
| 637 |
+
|
| 638 |
+
def _eval_rewrite_as_factorial(self, x, k, **kwargs):
|
| 639 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
| 640 |
+
if x.is_integer and k.is_integer:
|
| 641 |
+
return Piecewise(
|
| 642 |
+
(factorial(k + x - 1)/factorial(x - 1), x > 0),
|
| 643 |
+
(S.NegativeOne**k*factorial(-x)/factorial(-k - x), True))
|
| 644 |
+
|
| 645 |
+
def _eval_rewrite_as_binomial(self, x, k, **kwargs):
|
| 646 |
+
if k.is_integer:
|
| 647 |
+
return factorial(k) * binomial(x + k - 1, k)
|
| 648 |
+
|
| 649 |
+
def _eval_rewrite_as_tractable(self, x, k, limitvar=None, **kwargs):
|
| 650 |
+
from sympy.functions.special.gamma_functions import gamma
|
| 651 |
+
if limitvar:
|
| 652 |
+
k_lim = k.subs(limitvar, S.Infinity)
|
| 653 |
+
if k_lim is S.Infinity:
|
| 654 |
+
return (gamma(x + k).rewrite('tractable', deep=True) / gamma(x))
|
| 655 |
+
elif k_lim is S.NegativeInfinity:
|
| 656 |
+
return (S.NegativeOne**k*gamma(1 - x) / gamma(-k - x + 1).rewrite('tractable', deep=True))
|
| 657 |
+
return self.rewrite(gamma).rewrite('tractable', deep=True)
|
| 658 |
+
|
| 659 |
+
def _eval_is_integer(self):
|
| 660 |
+
return fuzzy_and((self.args[0].is_integer, self.args[1].is_integer,
|
| 661 |
+
self.args[1].is_nonnegative))
|
| 662 |
+
|
| 663 |
+
|
| 664 |
+
class FallingFactorial(CombinatorialFunction):
|
| 665 |
+
r"""
|
| 666 |
+
Falling factorial (related to rising factorial) is a double valued
|
| 667 |
+
function arising in concrete mathematics, hypergeometric functions
|
| 668 |
+
and series expansions. It is defined by
|
| 669 |
+
|
| 670 |
+
.. math:: \texttt{ff(x, k)} = (x)_k = x \cdot (x-1) \cdots (x-k+1)
|
| 671 |
+
|
| 672 |
+
where `x` can be arbitrary expression and `k` is an integer. For
|
| 673 |
+
more information check "Concrete mathematics" by Graham, pp. 66
|
| 674 |
+
or [1]_.
|
| 675 |
+
|
| 676 |
+
When `x` is a `~.Poly` instance of degree $\ge 1$ with single variable,
|
| 677 |
+
`(x)_k = x(y) \cdot x(y-1) \cdots x(y-k+1)`, where `y` is the
|
| 678 |
+
variable of `x`. This is as described in
|
| 679 |
+
|
| 680 |
+
>>> from sympy import ff, Poly, Symbol
|
| 681 |
+
>>> from sympy.abc import x
|
| 682 |
+
>>> n = Symbol('n', integer=True)
|
| 683 |
+
|
| 684 |
+
>>> ff(x, 0)
|
| 685 |
+
1
|
| 686 |
+
>>> ff(5, 5)
|
| 687 |
+
120
|
| 688 |
+
>>> ff(x, 5) == x*(x - 1)*(x - 2)*(x - 3)*(x - 4)
|
| 689 |
+
True
|
| 690 |
+
>>> ff(Poly(x**2, x), 2)
|
| 691 |
+
Poly(x**4 - 2*x**3 + x**2, x, domain='ZZ')
|
| 692 |
+
>>> ff(n, n)
|
| 693 |
+
factorial(n)
|
| 694 |
+
|
| 695 |
+
Rewriting is complicated unless the relationship between
|
| 696 |
+
the arguments is known, but falling factorial can
|
| 697 |
+
be rewritten in terms of gamma, factorial and binomial
|
| 698 |
+
and rising factorial.
|
| 699 |
+
|
| 700 |
+
>>> from sympy import factorial, rf, gamma, binomial, Symbol
|
| 701 |
+
>>> n = Symbol('n', integer=True, positive=True)
|
| 702 |
+
>>> F = ff(n, n - 2)
|
| 703 |
+
>>> for i in (rf, ff, factorial, binomial, gamma):
|
| 704 |
+
... F.rewrite(i)
|
| 705 |
+
...
|
| 706 |
+
RisingFactorial(3, n - 2)
|
| 707 |
+
FallingFactorial(n, n - 2)
|
| 708 |
+
factorial(n)/2
|
| 709 |
+
binomial(n, n - 2)*factorial(n - 2)
|
| 710 |
+
gamma(n + 1)/2
|
| 711 |
+
|
| 712 |
+
See Also
|
| 713 |
+
========
|
| 714 |
+
|
| 715 |
+
factorial, factorial2, RisingFactorial
|
| 716 |
+
|
| 717 |
+
References
|
| 718 |
+
==========
|
| 719 |
+
|
| 720 |
+
.. [1] https://mathworld.wolfram.com/FallingFactorial.html
|
| 721 |
+
.. [2] Peter Paule, "Greatest Factorial Factorization and Symbolic
|
| 722 |
+
Summation", Journal of Symbolic Computation, vol. 20, pp. 235-268,
|
| 723 |
+
1995.
|
| 724 |
+
|
| 725 |
+
"""
|
| 726 |
+
|
| 727 |
+
@classmethod
|
| 728 |
+
def eval(cls, x, k):
|
| 729 |
+
x = sympify(x)
|
| 730 |
+
k = sympify(k)
|
| 731 |
+
|
| 732 |
+
if x is S.NaN or k is S.NaN:
|
| 733 |
+
return S.NaN
|
| 734 |
+
elif k.is_integer and x == k:
|
| 735 |
+
return factorial(x)
|
| 736 |
+
elif k.is_Integer:
|
| 737 |
+
if k.is_zero:
|
| 738 |
+
return S.One
|
| 739 |
+
else:
|
| 740 |
+
if k.is_positive:
|
| 741 |
+
if x is S.Infinity:
|
| 742 |
+
return S.Infinity
|
| 743 |
+
elif x is S.NegativeInfinity:
|
| 744 |
+
if k.is_odd:
|
| 745 |
+
return S.NegativeInfinity
|
| 746 |
+
else:
|
| 747 |
+
return S.Infinity
|
| 748 |
+
else:
|
| 749 |
+
if isinstance(x, Poly):
|
| 750 |
+
gens = x.gens
|
| 751 |
+
if len(gens)!= 1:
|
| 752 |
+
raise ValueError("ff only defined for "
|
| 753 |
+
"polynomials on one generator")
|
| 754 |
+
else:
|
| 755 |
+
return reduce(lambda r, i:
|
| 756 |
+
r*(x.shift(-i)),
|
| 757 |
+
range(int(k)), 1)
|
| 758 |
+
else:
|
| 759 |
+
return reduce(lambda r, i: r*(x - i),
|
| 760 |
+
range(int(k)), 1)
|
| 761 |
+
else:
|
| 762 |
+
if x is S.Infinity:
|
| 763 |
+
return S.Infinity
|
| 764 |
+
elif x is S.NegativeInfinity:
|
| 765 |
+
return S.Infinity
|
| 766 |
+
else:
|
| 767 |
+
if isinstance(x, Poly):
|
| 768 |
+
gens = x.gens
|
| 769 |
+
if len(gens)!= 1:
|
| 770 |
+
raise ValueError("rf only defined for "
|
| 771 |
+
"polynomials on one generator")
|
| 772 |
+
else:
|
| 773 |
+
return 1/reduce(lambda r, i:
|
| 774 |
+
r*(x.shift(i)),
|
| 775 |
+
range(1, abs(int(k)) + 1), 1)
|
| 776 |
+
else:
|
| 777 |
+
return 1/reduce(lambda r, i: r*(x + i),
|
| 778 |
+
range(1, abs(int(k)) + 1), 1)
|
| 779 |
+
|
| 780 |
+
def _eval_rewrite_as_gamma(self, x, k, piecewise=True, **kwargs):
|
| 781 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
| 782 |
+
from sympy.functions.special.gamma_functions import gamma
|
| 783 |
+
if not piecewise:
|
| 784 |
+
if (x < 0) == True:
|
| 785 |
+
return S.NegativeOne**k*gamma(k - x) / gamma(-x)
|
| 786 |
+
return gamma(x + 1) / gamma(x - k + 1)
|
| 787 |
+
return Piecewise(
|
| 788 |
+
(gamma(x + 1) / gamma(x - k + 1), x >= 0),
|
| 789 |
+
(S.NegativeOne**k*gamma(k - x) / gamma(-x), True))
|
| 790 |
+
|
| 791 |
+
def _eval_rewrite_as_RisingFactorial(self, x, k, **kwargs):
|
| 792 |
+
return rf(x - k + 1, k)
|
| 793 |
+
|
| 794 |
+
def _eval_rewrite_as_binomial(self, x, k, **kwargs):
|
| 795 |
+
if k.is_integer:
|
| 796 |
+
return factorial(k) * binomial(x, k)
|
| 797 |
+
|
| 798 |
+
def _eval_rewrite_as_factorial(self, x, k, **kwargs):
|
| 799 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
| 800 |
+
if x.is_integer and k.is_integer:
|
| 801 |
+
return Piecewise(
|
| 802 |
+
(factorial(x)/factorial(-k + x), x >= 0),
|
| 803 |
+
(S.NegativeOne**k*factorial(k - x - 1)/factorial(-x - 1), True))
|
| 804 |
+
|
| 805 |
+
def _eval_rewrite_as_tractable(self, x, k, limitvar=None, **kwargs):
|
| 806 |
+
from sympy.functions.special.gamma_functions import gamma
|
| 807 |
+
if limitvar:
|
| 808 |
+
k_lim = k.subs(limitvar, S.Infinity)
|
| 809 |
+
if k_lim is S.Infinity:
|
| 810 |
+
return (S.NegativeOne**k*gamma(k - x).rewrite('tractable', deep=True) / gamma(-x))
|
| 811 |
+
elif k_lim is S.NegativeInfinity:
|
| 812 |
+
return (gamma(x + 1) / gamma(x - k + 1).rewrite('tractable', deep=True))
|
| 813 |
+
return self.rewrite(gamma).rewrite('tractable', deep=True)
|
| 814 |
+
|
| 815 |
+
def _eval_is_integer(self):
|
| 816 |
+
return fuzzy_and((self.args[0].is_integer, self.args[1].is_integer,
|
| 817 |
+
self.args[1].is_nonnegative))
|
| 818 |
+
|
| 819 |
+
|
| 820 |
+
rf = RisingFactorial
|
| 821 |
+
ff = FallingFactorial
|
| 822 |
+
|
| 823 |
+
###############################################################################
|
| 824 |
+
########################### BINOMIAL COEFFICIENTS #############################
|
| 825 |
+
###############################################################################
|
| 826 |
+
|
| 827 |
+
|
| 828 |
+
class binomial(CombinatorialFunction):
|
| 829 |
+
r"""Implementation of the binomial coefficient. It can be defined
|
| 830 |
+
in two ways depending on its desired interpretation:
|
| 831 |
+
|
| 832 |
+
.. math:: \binom{n}{k} = \frac{n!}{k!(n-k)!}\ \text{or}\
|
| 833 |
+
\binom{n}{k} = \frac{(n)_k}{k!}
|
| 834 |
+
|
| 835 |
+
First, in a strict combinatorial sense it defines the
|
| 836 |
+
number of ways we can choose `k` elements from a set of
|
| 837 |
+
`n` elements. In this case both arguments are nonnegative
|
| 838 |
+
integers and binomial is computed using an efficient
|
| 839 |
+
algorithm based on prime factorization.
|
| 840 |
+
|
| 841 |
+
The other definition is generalization for arbitrary `n`,
|
| 842 |
+
however `k` must also be nonnegative. This case is very
|
| 843 |
+
useful when evaluating summations.
|
| 844 |
+
|
| 845 |
+
For the sake of convenience, for negative integer `k` this function
|
| 846 |
+
will return zero no matter the other argument.
|
| 847 |
+
|
| 848 |
+
To expand the binomial when `n` is a symbol, use either
|
| 849 |
+
``expand_func()`` or ``expand(func=True)``. The former will keep
|
| 850 |
+
the polynomial in factored form while the latter will expand the
|
| 851 |
+
polynomial itself. See examples for details.
|
| 852 |
+
|
| 853 |
+
Examples
|
| 854 |
+
========
|
| 855 |
+
|
| 856 |
+
>>> from sympy import Symbol, Rational, binomial, expand_func
|
| 857 |
+
>>> n = Symbol('n', integer=True, positive=True)
|
| 858 |
+
|
| 859 |
+
>>> binomial(15, 8)
|
| 860 |
+
6435
|
| 861 |
+
|
| 862 |
+
>>> binomial(n, -1)
|
| 863 |
+
0
|
| 864 |
+
|
| 865 |
+
Rows of Pascal's triangle can be generated with the binomial function:
|
| 866 |
+
|
| 867 |
+
>>> for N in range(8):
|
| 868 |
+
... print([binomial(N, i) for i in range(N + 1)])
|
| 869 |
+
...
|
| 870 |
+
[1]
|
| 871 |
+
[1, 1]
|
| 872 |
+
[1, 2, 1]
|
| 873 |
+
[1, 3, 3, 1]
|
| 874 |
+
[1, 4, 6, 4, 1]
|
| 875 |
+
[1, 5, 10, 10, 5, 1]
|
| 876 |
+
[1, 6, 15, 20, 15, 6, 1]
|
| 877 |
+
[1, 7, 21, 35, 35, 21, 7, 1]
|
| 878 |
+
|
| 879 |
+
As can a given diagonal, e.g. the 4th diagonal:
|
| 880 |
+
|
| 881 |
+
>>> N = -4
|
| 882 |
+
>>> [binomial(N, i) for i in range(1 - N)]
|
| 883 |
+
[1, -4, 10, -20, 35]
|
| 884 |
+
|
| 885 |
+
>>> binomial(Rational(5, 4), 3)
|
| 886 |
+
-5/128
|
| 887 |
+
>>> binomial(Rational(-5, 4), 3)
|
| 888 |
+
-195/128
|
| 889 |
+
|
| 890 |
+
>>> binomial(n, 3)
|
| 891 |
+
binomial(n, 3)
|
| 892 |
+
|
| 893 |
+
>>> binomial(n, 3).expand(func=True)
|
| 894 |
+
n**3/6 - n**2/2 + n/3
|
| 895 |
+
|
| 896 |
+
>>> expand_func(binomial(n, 3))
|
| 897 |
+
n*(n - 2)*(n - 1)/6
|
| 898 |
+
|
| 899 |
+
In many cases, we can also compute binomial coefficients modulo a
|
| 900 |
+
prime p quickly using Lucas' Theorem [2]_, though we need to include
|
| 901 |
+
`evaluate=False` to postpone evaluation:
|
| 902 |
+
|
| 903 |
+
>>> from sympy import Mod
|
| 904 |
+
>>> Mod(binomial(156675, 4433, evaluate=False), 10**5 + 3)
|
| 905 |
+
28625
|
| 906 |
+
|
| 907 |
+
Using a generalisation of Lucas's Theorem given by Granville [3]_,
|
| 908 |
+
we can extend this to arbitrary n:
|
| 909 |
+
|
| 910 |
+
>>> Mod(binomial(10**18, 10**12, evaluate=False), (10**5 + 3)**2)
|
| 911 |
+
3744312326
|
| 912 |
+
|
| 913 |
+
References
|
| 914 |
+
==========
|
| 915 |
+
|
| 916 |
+
.. [1] https://www.johndcook.com/blog/binomial_coefficients/
|
| 917 |
+
.. [2] https://en.wikipedia.org/wiki/Lucas%27s_theorem
|
| 918 |
+
.. [3] Binomial coefficients modulo prime powers, Andrew Granville,
|
| 919 |
+
Available: https://web.archive.org/web/20170202003812/http://www.dms.umontreal.ca/~andrew/PDF/BinCoeff.pdf
|
| 920 |
+
"""
|
| 921 |
+
|
| 922 |
+
def fdiff(self, argindex=1):
|
| 923 |
+
from sympy.functions.special.gamma_functions import polygamma
|
| 924 |
+
if argindex == 1:
|
| 925 |
+
# https://functions.wolfram.com/GammaBetaErf/Binomial/20/01/01/
|
| 926 |
+
n, k = self.args
|
| 927 |
+
return binomial(n, k)*(polygamma(0, n + 1) - \
|
| 928 |
+
polygamma(0, n - k + 1))
|
| 929 |
+
elif argindex == 2:
|
| 930 |
+
# https://functions.wolfram.com/GammaBetaErf/Binomial/20/01/02/
|
| 931 |
+
n, k = self.args
|
| 932 |
+
return binomial(n, k)*(polygamma(0, n - k + 1) - \
|
| 933 |
+
polygamma(0, k + 1))
|
| 934 |
+
else:
|
| 935 |
+
raise ArgumentIndexError(self, argindex)
|
| 936 |
+
|
| 937 |
+
@classmethod
|
| 938 |
+
def _eval(self, n, k):
|
| 939 |
+
# n.is_Number and k.is_Integer and k != 1 and n != k
|
| 940 |
+
|
| 941 |
+
if k.is_Integer:
|
| 942 |
+
if n.is_Integer and n >= 0:
|
| 943 |
+
n, k = int(n), int(k)
|
| 944 |
+
|
| 945 |
+
if k > n:
|
| 946 |
+
return S.Zero
|
| 947 |
+
elif k > n // 2:
|
| 948 |
+
k = n - k
|
| 949 |
+
|
| 950 |
+
# XXX: This conditional logic should be moved to
|
| 951 |
+
# sympy.external.gmpy and the pure Python version of bincoef
|
| 952 |
+
# should be moved to sympy.external.ntheory.
|
| 953 |
+
if _gmpy is not None:
|
| 954 |
+
return Integer(_gmpy.bincoef(n, k))
|
| 955 |
+
|
| 956 |
+
d, result = n - k, 1
|
| 957 |
+
for i in range(1, k + 1):
|
| 958 |
+
d += 1
|
| 959 |
+
result = result * d // i
|
| 960 |
+
return Integer(result)
|
| 961 |
+
else:
|
| 962 |
+
d, result = n - k, 1
|
| 963 |
+
for i in range(1, k + 1):
|
| 964 |
+
d += 1
|
| 965 |
+
result *= d
|
| 966 |
+
return result / _factorial(k)
|
| 967 |
+
|
| 968 |
+
@classmethod
|
| 969 |
+
def eval(cls, n, k):
|
| 970 |
+
n, k = map(sympify, (n, k))
|
| 971 |
+
d = n - k
|
| 972 |
+
n_nonneg, n_isint = n.is_nonnegative, n.is_integer
|
| 973 |
+
if k.is_zero or ((n_nonneg or n_isint is False)
|
| 974 |
+
and d.is_zero):
|
| 975 |
+
return S.One
|
| 976 |
+
if (k - 1).is_zero or ((n_nonneg or n_isint is False)
|
| 977 |
+
and (d - 1).is_zero):
|
| 978 |
+
return n
|
| 979 |
+
if k.is_integer:
|
| 980 |
+
if k.is_negative or (n_nonneg and n_isint and d.is_negative):
|
| 981 |
+
return S.Zero
|
| 982 |
+
elif n.is_number:
|
| 983 |
+
res = cls._eval(n, k)
|
| 984 |
+
return res.expand(basic=True) if res else res
|
| 985 |
+
elif n_nonneg is False and n_isint:
|
| 986 |
+
# a special case when binomial evaluates to complex infinity
|
| 987 |
+
return S.ComplexInfinity
|
| 988 |
+
elif k.is_number:
|
| 989 |
+
from sympy.functions.special.gamma_functions import gamma
|
| 990 |
+
return gamma(n + 1)/(gamma(k + 1)*gamma(n - k + 1))
|
| 991 |
+
|
| 992 |
+
def _eval_Mod(self, q):
|
| 993 |
+
n, k = self.args
|
| 994 |
+
|
| 995 |
+
if any(x.is_integer is False for x in (n, k, q)):
|
| 996 |
+
raise ValueError("Integers expected for binomial Mod")
|
| 997 |
+
|
| 998 |
+
if all(x.is_Integer for x in (n, k, q)):
|
| 999 |
+
n, k = map(int, (n, k))
|
| 1000 |
+
aq, res = abs(q), 1
|
| 1001 |
+
|
| 1002 |
+
# handle negative integers k or n
|
| 1003 |
+
if k < 0:
|
| 1004 |
+
return S.Zero
|
| 1005 |
+
if n < 0:
|
| 1006 |
+
n = -n + k - 1
|
| 1007 |
+
res = -1 if k%2 else 1
|
| 1008 |
+
|
| 1009 |
+
# non negative integers k and n
|
| 1010 |
+
if k > n:
|
| 1011 |
+
return S.Zero
|
| 1012 |
+
|
| 1013 |
+
isprime = aq.is_prime
|
| 1014 |
+
aq = int(aq)
|
| 1015 |
+
if isprime:
|
| 1016 |
+
if aq < n:
|
| 1017 |
+
# use Lucas Theorem
|
| 1018 |
+
N, K = n, k
|
| 1019 |
+
while N or K:
|
| 1020 |
+
res = res*binomial(N % aq, K % aq) % aq
|
| 1021 |
+
N, K = N // aq, K // aq
|
| 1022 |
+
|
| 1023 |
+
else:
|
| 1024 |
+
# use Factorial Modulo
|
| 1025 |
+
d = n - k
|
| 1026 |
+
if k > d:
|
| 1027 |
+
k, d = d, k
|
| 1028 |
+
kf = 1
|
| 1029 |
+
for i in range(2, k + 1):
|
| 1030 |
+
kf = kf*i % aq
|
| 1031 |
+
df = kf
|
| 1032 |
+
for i in range(k + 1, d + 1):
|
| 1033 |
+
df = df*i % aq
|
| 1034 |
+
res *= df
|
| 1035 |
+
for i in range(d + 1, n + 1):
|
| 1036 |
+
res = res*i % aq
|
| 1037 |
+
|
| 1038 |
+
res *= pow(kf*df % aq, aq - 2, aq)
|
| 1039 |
+
res %= aq
|
| 1040 |
+
|
| 1041 |
+
elif _sqrt(q) < k and q != 1:
|
| 1042 |
+
res = binomial_mod(n, k, q)
|
| 1043 |
+
|
| 1044 |
+
else:
|
| 1045 |
+
# Binomial Factorization is performed by calculating the
|
| 1046 |
+
# exponents of primes <= n in `n! /(k! (n - k)!)`,
|
| 1047 |
+
# for non-negative integers n and k. As the exponent of
|
| 1048 |
+
# prime in n! is e_p(n) = [n/p] + [n/p**2] + ...
|
| 1049 |
+
# the exponent of prime in binomial(n, k) would be
|
| 1050 |
+
# e_p(n) - e_p(k) - e_p(n - k)
|
| 1051 |
+
M = int(_sqrt(n))
|
| 1052 |
+
for prime in sieve.primerange(2, n + 1):
|
| 1053 |
+
if prime > n - k:
|
| 1054 |
+
res = res*prime % aq
|
| 1055 |
+
elif prime > n // 2:
|
| 1056 |
+
continue
|
| 1057 |
+
elif prime > M:
|
| 1058 |
+
if n % prime < k % prime:
|
| 1059 |
+
res = res*prime % aq
|
| 1060 |
+
else:
|
| 1061 |
+
N, K = n, k
|
| 1062 |
+
exp = a = 0
|
| 1063 |
+
|
| 1064 |
+
while N > 0:
|
| 1065 |
+
a = int((N % prime) < (K % prime + a))
|
| 1066 |
+
N, K = N // prime, K // prime
|
| 1067 |
+
exp += a
|
| 1068 |
+
|
| 1069 |
+
if exp > 0:
|
| 1070 |
+
res *= pow(prime, exp, aq)
|
| 1071 |
+
res %= aq
|
| 1072 |
+
|
| 1073 |
+
return S(res % q)
|
| 1074 |
+
|
| 1075 |
+
def _eval_expand_func(self, **hints):
|
| 1076 |
+
"""
|
| 1077 |
+
Function to expand binomial(n, k) when m is positive integer
|
| 1078 |
+
Also,
|
| 1079 |
+
n is self.args[0] and k is self.args[1] while using binomial(n, k)
|
| 1080 |
+
"""
|
| 1081 |
+
n = self.args[0]
|
| 1082 |
+
if n.is_Number:
|
| 1083 |
+
return binomial(*self.args)
|
| 1084 |
+
|
| 1085 |
+
k = self.args[1]
|
| 1086 |
+
if (n-k).is_Integer:
|
| 1087 |
+
k = n - k
|
| 1088 |
+
|
| 1089 |
+
if k.is_Integer:
|
| 1090 |
+
if k.is_zero:
|
| 1091 |
+
return S.One
|
| 1092 |
+
elif k.is_negative:
|
| 1093 |
+
return S.Zero
|
| 1094 |
+
else:
|
| 1095 |
+
n, result = self.args[0], 1
|
| 1096 |
+
for i in range(1, k + 1):
|
| 1097 |
+
result *= n - k + i
|
| 1098 |
+
return result / _factorial(k)
|
| 1099 |
+
else:
|
| 1100 |
+
return binomial(*self.args)
|
| 1101 |
+
|
| 1102 |
+
def _eval_rewrite_as_factorial(self, n, k, **kwargs):
|
| 1103 |
+
return factorial(n)/(factorial(k)*factorial(n - k))
|
| 1104 |
+
|
| 1105 |
+
def _eval_rewrite_as_gamma(self, n, k, piecewise=True, **kwargs):
|
| 1106 |
+
from sympy.functions.special.gamma_functions import gamma
|
| 1107 |
+
return gamma(n + 1)/(gamma(k + 1)*gamma(n - k + 1))
|
| 1108 |
+
|
| 1109 |
+
def _eval_rewrite_as_tractable(self, n, k, limitvar=None, **kwargs):
|
| 1110 |
+
return self._eval_rewrite_as_gamma(n, k).rewrite('tractable')
|
| 1111 |
+
|
| 1112 |
+
def _eval_rewrite_as_FallingFactorial(self, n, k, **kwargs):
|
| 1113 |
+
if k.is_integer:
|
| 1114 |
+
return ff(n, k) / factorial(k)
|
| 1115 |
+
|
| 1116 |
+
def _eval_is_integer(self):
|
| 1117 |
+
n, k = self.args
|
| 1118 |
+
if n.is_integer and k.is_integer:
|
| 1119 |
+
return True
|
| 1120 |
+
elif k.is_integer is False:
|
| 1121 |
+
return False
|
| 1122 |
+
|
| 1123 |
+
def _eval_is_nonnegative(self):
|
| 1124 |
+
n, k = self.args
|
| 1125 |
+
if n.is_integer and k.is_integer:
|
| 1126 |
+
if n.is_nonnegative or k.is_negative or k.is_even:
|
| 1127 |
+
return True
|
| 1128 |
+
elif k.is_even is False:
|
| 1129 |
+
return False
|
| 1130 |
+
|
| 1131 |
+
def _eval_as_leading_term(self, x, logx=None, cdir=0):
|
| 1132 |
+
from sympy.functions.special.gamma_functions import gamma
|
| 1133 |
+
return self.rewrite(gamma)._eval_as_leading_term(x, logx=logx, cdir=cdir)
|
evalkit_tf446/lib/python3.10/site-packages/sympy/functions/combinatorial/numbers.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
evalkit_tf446/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/__init__.py
ADDED
|
File without changes
|
evalkit_tf446/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (194 Bytes). View file
|
|
|
evalkit_tf446/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/__pycache__/test_comb_factorials.cpython-310.pyc
ADDED
|
Binary file (22.1 kB). View file
|
|
|
evalkit_tf446/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/__pycache__/test_comb_numbers.cpython-310.pyc
ADDED
|
Binary file (50.4 kB). View file
|
|
|
evalkit_tf446/lib/python3.10/site-packages/sympy/functions/combinatorial/tests/test_comb_factorials.py
ADDED
|
@@ -0,0 +1,653 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.concrete.products import Product
|
| 2 |
+
from sympy.core.function import expand_func
|
| 3 |
+
from sympy.core.mod import Mod
|
| 4 |
+
from sympy.core.mul import Mul
|
| 5 |
+
from sympy.core import EulerGamma
|
| 6 |
+
from sympy.core.numbers import (Float, I, Rational, nan, oo, pi, zoo)
|
| 7 |
+
from sympy.core.relational import Eq
|
| 8 |
+
from sympy.core.singleton import S
|
| 9 |
+
from sympy.core.symbol import (Dummy, Symbol, symbols)
|
| 10 |
+
from sympy.functions.combinatorial.factorials import (ff, rf, binomial, factorial, factorial2)
|
| 11 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 12 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
| 13 |
+
from sympy.functions.special.gamma_functions import (gamma, polygamma)
|
| 14 |
+
from sympy.polys.polytools import Poly
|
| 15 |
+
from sympy.series.order import O
|
| 16 |
+
from sympy.simplify.simplify import simplify
|
| 17 |
+
from sympy.core.expr import unchanged
|
| 18 |
+
from sympy.core.function import ArgumentIndexError
|
| 19 |
+
from sympy.functions.combinatorial.factorials import subfactorial
|
| 20 |
+
from sympy.functions.special.gamma_functions import uppergamma
|
| 21 |
+
from sympy.testing.pytest import XFAIL, raises, slow
|
| 22 |
+
|
| 23 |
+
#Solves and Fixes Issue #10388 - This is the updated test for the same solved issue
|
| 24 |
+
|
| 25 |
+
def test_rf_eval_apply():
|
| 26 |
+
x, y = symbols('x,y')
|
| 27 |
+
n, k = symbols('n k', integer=True)
|
| 28 |
+
m = Symbol('m', integer=True, nonnegative=True)
|
| 29 |
+
|
| 30 |
+
assert rf(nan, y) is nan
|
| 31 |
+
assert rf(x, nan) is nan
|
| 32 |
+
|
| 33 |
+
assert unchanged(rf, x, y)
|
| 34 |
+
|
| 35 |
+
assert rf(oo, 0) == 1
|
| 36 |
+
assert rf(-oo, 0) == 1
|
| 37 |
+
|
| 38 |
+
assert rf(oo, 6) is oo
|
| 39 |
+
assert rf(-oo, 7) is -oo
|
| 40 |
+
assert rf(-oo, 6) is oo
|
| 41 |
+
|
| 42 |
+
assert rf(oo, -6) is oo
|
| 43 |
+
assert rf(-oo, -7) is oo
|
| 44 |
+
|
| 45 |
+
assert rf(-1, pi) == 0
|
| 46 |
+
assert rf(-5, 1 + I) == 0
|
| 47 |
+
|
| 48 |
+
assert unchanged(rf, -3, k)
|
| 49 |
+
assert unchanged(rf, x, Symbol('k', integer=False))
|
| 50 |
+
assert rf(-3, Symbol('k', integer=False)) == 0
|
| 51 |
+
assert rf(Symbol('x', negative=True, integer=True), Symbol('k', integer=False)) == 0
|
| 52 |
+
|
| 53 |
+
assert rf(x, 0) == 1
|
| 54 |
+
assert rf(x, 1) == x
|
| 55 |
+
assert rf(x, 2) == x*(x + 1)
|
| 56 |
+
assert rf(x, 3) == x*(x + 1)*(x + 2)
|
| 57 |
+
assert rf(x, 5) == x*(x + 1)*(x + 2)*(x + 3)*(x + 4)
|
| 58 |
+
|
| 59 |
+
assert rf(x, -1) == 1/(x - 1)
|
| 60 |
+
assert rf(x, -2) == 1/((x - 1)*(x - 2))
|
| 61 |
+
assert rf(x, -3) == 1/((x - 1)*(x - 2)*(x - 3))
|
| 62 |
+
|
| 63 |
+
assert rf(1, 100) == factorial(100)
|
| 64 |
+
|
| 65 |
+
assert rf(x**2 + 3*x, 2) == (x**2 + 3*x)*(x**2 + 3*x + 1)
|
| 66 |
+
assert isinstance(rf(x**2 + 3*x, 2), Mul)
|
| 67 |
+
assert rf(x**3 + x, -2) == 1/((x**3 + x - 1)*(x**3 + x - 2))
|
| 68 |
+
|
| 69 |
+
assert rf(Poly(x**2 + 3*x, x), 2) == Poly(x**4 + 8*x**3 + 19*x**2 + 12*x, x)
|
| 70 |
+
assert isinstance(rf(Poly(x**2 + 3*x, x), 2), Poly)
|
| 71 |
+
raises(ValueError, lambda: rf(Poly(x**2 + 3*x, x, y), 2))
|
| 72 |
+
assert rf(Poly(x**3 + x, x), -2) == 1/(x**6 - 9*x**5 + 35*x**4 - 75*x**3 + 94*x**2 - 66*x + 20)
|
| 73 |
+
raises(ValueError, lambda: rf(Poly(x**3 + x, x, y), -2))
|
| 74 |
+
|
| 75 |
+
assert rf(x, m).is_integer is None
|
| 76 |
+
assert rf(n, k).is_integer is None
|
| 77 |
+
assert rf(n, m).is_integer is True
|
| 78 |
+
assert rf(n, k + pi).is_integer is False
|
| 79 |
+
assert rf(n, m + pi).is_integer is False
|
| 80 |
+
assert rf(pi, m).is_integer is False
|
| 81 |
+
|
| 82 |
+
def check(x, k, o, n):
|
| 83 |
+
a, b = Dummy(), Dummy()
|
| 84 |
+
r = lambda x, k: o(a, b).rewrite(n).subs({a:x,b:k})
|
| 85 |
+
for i in range(-5,5):
|
| 86 |
+
for j in range(-5,5):
|
| 87 |
+
assert o(i, j) == r(i, j), (o, n, i, j)
|
| 88 |
+
check(x, k, rf, ff)
|
| 89 |
+
check(x, k, rf, binomial)
|
| 90 |
+
check(n, k, rf, factorial)
|
| 91 |
+
check(x, y, rf, factorial)
|
| 92 |
+
check(x, y, rf, binomial)
|
| 93 |
+
|
| 94 |
+
assert rf(x, k).rewrite(ff) == ff(x + k - 1, k)
|
| 95 |
+
assert rf(x, k).rewrite(gamma) == Piecewise(
|
| 96 |
+
(gamma(k + x)/gamma(x), x > 0),
|
| 97 |
+
((-1)**k*gamma(1 - x)/gamma(-k - x + 1), True))
|
| 98 |
+
assert rf(5, k).rewrite(gamma) == gamma(k + 5)/24
|
| 99 |
+
assert rf(x, k).rewrite(binomial) == factorial(k)*binomial(x + k - 1, k)
|
| 100 |
+
assert rf(n, k).rewrite(factorial) == Piecewise(
|
| 101 |
+
(factorial(k + n - 1)/factorial(n - 1), n > 0),
|
| 102 |
+
((-1)**k*factorial(-n)/factorial(-k - n), True))
|
| 103 |
+
assert rf(5, k).rewrite(factorial) == factorial(k + 4)/24
|
| 104 |
+
assert rf(x, y).rewrite(factorial) == rf(x, y)
|
| 105 |
+
assert rf(x, y).rewrite(binomial) == rf(x, y)
|
| 106 |
+
|
| 107 |
+
import random
|
| 108 |
+
from mpmath import rf as mpmath_rf
|
| 109 |
+
for i in range(100):
|
| 110 |
+
x = -500 + 500 * random.random()
|
| 111 |
+
k = -500 + 500 * random.random()
|
| 112 |
+
assert (abs(mpmath_rf(x, k) - rf(x, k)) < 10**(-15))
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def test_ff_eval_apply():
|
| 116 |
+
x, y = symbols('x,y')
|
| 117 |
+
n, k = symbols('n k', integer=True)
|
| 118 |
+
m = Symbol('m', integer=True, nonnegative=True)
|
| 119 |
+
|
| 120 |
+
assert ff(nan, y) is nan
|
| 121 |
+
assert ff(x, nan) is nan
|
| 122 |
+
|
| 123 |
+
assert unchanged(ff, x, y)
|
| 124 |
+
|
| 125 |
+
assert ff(oo, 0) == 1
|
| 126 |
+
assert ff(-oo, 0) == 1
|
| 127 |
+
|
| 128 |
+
assert ff(oo, 6) is oo
|
| 129 |
+
assert ff(-oo, 7) is -oo
|
| 130 |
+
assert ff(-oo, 6) is oo
|
| 131 |
+
|
| 132 |
+
assert ff(oo, -6) is oo
|
| 133 |
+
assert ff(-oo, -7) is oo
|
| 134 |
+
|
| 135 |
+
assert ff(x, 0) == 1
|
| 136 |
+
assert ff(x, 1) == x
|
| 137 |
+
assert ff(x, 2) == x*(x - 1)
|
| 138 |
+
assert ff(x, 3) == x*(x - 1)*(x - 2)
|
| 139 |
+
assert ff(x, 5) == x*(x - 1)*(x - 2)*(x - 3)*(x - 4)
|
| 140 |
+
|
| 141 |
+
assert ff(x, -1) == 1/(x + 1)
|
| 142 |
+
assert ff(x, -2) == 1/((x + 1)*(x + 2))
|
| 143 |
+
assert ff(x, -3) == 1/((x + 1)*(x + 2)*(x + 3))
|
| 144 |
+
|
| 145 |
+
assert ff(100, 100) == factorial(100)
|
| 146 |
+
|
| 147 |
+
assert ff(2*x**2 - 5*x, 2) == (2*x**2 - 5*x)*(2*x**2 - 5*x - 1)
|
| 148 |
+
assert isinstance(ff(2*x**2 - 5*x, 2), Mul)
|
| 149 |
+
assert ff(x**2 + 3*x, -2) == 1/((x**2 + 3*x + 1)*(x**2 + 3*x + 2))
|
| 150 |
+
|
| 151 |
+
assert ff(Poly(2*x**2 - 5*x, x), 2) == Poly(4*x**4 - 28*x**3 + 59*x**2 - 35*x, x)
|
| 152 |
+
assert isinstance(ff(Poly(2*x**2 - 5*x, x), 2), Poly)
|
| 153 |
+
raises(ValueError, lambda: ff(Poly(2*x**2 - 5*x, x, y), 2))
|
| 154 |
+
assert ff(Poly(x**2 + 3*x, x), -2) == 1/(x**4 + 12*x**3 + 49*x**2 + 78*x + 40)
|
| 155 |
+
raises(ValueError, lambda: ff(Poly(x**2 + 3*x, x, y), -2))
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
assert ff(x, m).is_integer is None
|
| 159 |
+
assert ff(n, k).is_integer is None
|
| 160 |
+
assert ff(n, m).is_integer is True
|
| 161 |
+
assert ff(n, k + pi).is_integer is False
|
| 162 |
+
assert ff(n, m + pi).is_integer is False
|
| 163 |
+
assert ff(pi, m).is_integer is False
|
| 164 |
+
|
| 165 |
+
assert isinstance(ff(x, x), ff)
|
| 166 |
+
assert ff(n, n) == factorial(n)
|
| 167 |
+
|
| 168 |
+
def check(x, k, o, n):
|
| 169 |
+
a, b = Dummy(), Dummy()
|
| 170 |
+
r = lambda x, k: o(a, b).rewrite(n).subs({a:x,b:k})
|
| 171 |
+
for i in range(-5,5):
|
| 172 |
+
for j in range(-5,5):
|
| 173 |
+
assert o(i, j) == r(i, j), (o, n)
|
| 174 |
+
check(x, k, ff, rf)
|
| 175 |
+
check(x, k, ff, gamma)
|
| 176 |
+
check(n, k, ff, factorial)
|
| 177 |
+
check(x, k, ff, binomial)
|
| 178 |
+
check(x, y, ff, factorial)
|
| 179 |
+
check(x, y, ff, binomial)
|
| 180 |
+
|
| 181 |
+
assert ff(x, k).rewrite(rf) == rf(x - k + 1, k)
|
| 182 |
+
assert ff(x, k).rewrite(gamma) == Piecewise(
|
| 183 |
+
(gamma(x + 1)/gamma(-k + x + 1), x >= 0),
|
| 184 |
+
((-1)**k*gamma(k - x)/gamma(-x), True))
|
| 185 |
+
assert ff(5, k).rewrite(gamma) == 120/gamma(6 - k)
|
| 186 |
+
assert ff(n, k).rewrite(factorial) == Piecewise(
|
| 187 |
+
(factorial(n)/factorial(-k + n), n >= 0),
|
| 188 |
+
((-1)**k*factorial(k - n - 1)/factorial(-n - 1), True))
|
| 189 |
+
assert ff(5, k).rewrite(factorial) == 120/factorial(5 - k)
|
| 190 |
+
assert ff(x, k).rewrite(binomial) == factorial(k) * binomial(x, k)
|
| 191 |
+
assert ff(x, y).rewrite(factorial) == ff(x, y)
|
| 192 |
+
assert ff(x, y).rewrite(binomial) == ff(x, y)
|
| 193 |
+
|
| 194 |
+
import random
|
| 195 |
+
from mpmath import ff as mpmath_ff
|
| 196 |
+
for i in range(100):
|
| 197 |
+
x = -500 + 500 * random.random()
|
| 198 |
+
k = -500 + 500 * random.random()
|
| 199 |
+
a = mpmath_ff(x, k)
|
| 200 |
+
b = ff(x, k)
|
| 201 |
+
assert (abs(a - b) < abs(a) * 10**(-15))
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def test_rf_ff_eval_hiprec():
|
| 205 |
+
maple = Float('6.9109401292234329956525265438452')
|
| 206 |
+
us = ff(18, Rational(2, 3)).evalf(32)
|
| 207 |
+
assert abs(us - maple)/us < 1e-31
|
| 208 |
+
|
| 209 |
+
maple = Float('6.8261540131125511557924466355367')
|
| 210 |
+
us = rf(18, Rational(2, 3)).evalf(32)
|
| 211 |
+
assert abs(us - maple)/us < 1e-31
|
| 212 |
+
|
| 213 |
+
maple = Float('34.007346127440197150854651814225')
|
| 214 |
+
us = rf(Float('4.4', 32), Float('2.2', 32));
|
| 215 |
+
assert abs(us - maple)/us < 1e-31
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def test_rf_lambdify_mpmath():
|
| 219 |
+
from sympy.utilities.lambdify import lambdify
|
| 220 |
+
x, y = symbols('x,y')
|
| 221 |
+
f = lambdify((x,y), rf(x, y), 'mpmath')
|
| 222 |
+
maple = Float('34.007346127440197')
|
| 223 |
+
us = f(4.4, 2.2)
|
| 224 |
+
assert abs(us - maple)/us < 1e-15
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def test_factorial():
|
| 228 |
+
x = Symbol('x')
|
| 229 |
+
n = Symbol('n', integer=True)
|
| 230 |
+
k = Symbol('k', integer=True, nonnegative=True)
|
| 231 |
+
r = Symbol('r', integer=False)
|
| 232 |
+
s = Symbol('s', integer=False, negative=True)
|
| 233 |
+
t = Symbol('t', nonnegative=True)
|
| 234 |
+
u = Symbol('u', noninteger=True)
|
| 235 |
+
|
| 236 |
+
assert factorial(-2) is zoo
|
| 237 |
+
assert factorial(0) == 1
|
| 238 |
+
assert factorial(7) == 5040
|
| 239 |
+
assert factorial(19) == 121645100408832000
|
| 240 |
+
assert factorial(31) == 8222838654177922817725562880000000
|
| 241 |
+
assert factorial(n).func == factorial
|
| 242 |
+
assert factorial(2*n).func == factorial
|
| 243 |
+
|
| 244 |
+
assert factorial(x).is_integer is None
|
| 245 |
+
assert factorial(n).is_integer is None
|
| 246 |
+
assert factorial(k).is_integer
|
| 247 |
+
assert factorial(r).is_integer is None
|
| 248 |
+
|
| 249 |
+
assert factorial(n).is_positive is None
|
| 250 |
+
assert factorial(k).is_positive
|
| 251 |
+
|
| 252 |
+
assert factorial(x).is_real is None
|
| 253 |
+
assert factorial(n).is_real is None
|
| 254 |
+
assert factorial(k).is_real is True
|
| 255 |
+
assert factorial(r).is_real is None
|
| 256 |
+
assert factorial(s).is_real is True
|
| 257 |
+
assert factorial(t).is_real is True
|
| 258 |
+
assert factorial(u).is_real is True
|
| 259 |
+
|
| 260 |
+
assert factorial(x).is_composite is None
|
| 261 |
+
assert factorial(n).is_composite is None
|
| 262 |
+
assert factorial(k).is_composite is None
|
| 263 |
+
assert factorial(k + 3).is_composite is True
|
| 264 |
+
assert factorial(r).is_composite is None
|
| 265 |
+
assert factorial(s).is_composite is None
|
| 266 |
+
assert factorial(t).is_composite is None
|
| 267 |
+
assert factorial(u).is_composite is None
|
| 268 |
+
|
| 269 |
+
assert factorial(oo) is oo
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def test_factorial_Mod():
|
| 273 |
+
pr = Symbol('pr', prime=True)
|
| 274 |
+
p, q = 10**9 + 9, 10**9 + 33 # prime modulo
|
| 275 |
+
r, s = 10**7 + 5, 33333333 # composite modulo
|
| 276 |
+
assert Mod(factorial(pr - 1), pr) == pr - 1
|
| 277 |
+
assert Mod(factorial(pr - 1), -pr) == -1
|
| 278 |
+
assert Mod(factorial(r - 1, evaluate=False), r) == 0
|
| 279 |
+
assert Mod(factorial(s - 1, evaluate=False), s) == 0
|
| 280 |
+
assert Mod(factorial(p - 1, evaluate=False), p) == p - 1
|
| 281 |
+
assert Mod(factorial(q - 1, evaluate=False), q) == q - 1
|
| 282 |
+
assert Mod(factorial(p - 50, evaluate=False), p) == 854928834
|
| 283 |
+
assert Mod(factorial(q - 1800, evaluate=False), q) == 905504050
|
| 284 |
+
assert Mod(factorial(153, evaluate=False), r) == Mod(factorial(153), r)
|
| 285 |
+
assert Mod(factorial(255, evaluate=False), s) == Mod(factorial(255), s)
|
| 286 |
+
assert Mod(factorial(4, evaluate=False), 3) == S.Zero
|
| 287 |
+
assert Mod(factorial(5, evaluate=False), 6) == S.Zero
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
def test_factorial_diff():
|
| 291 |
+
n = Symbol('n', integer=True)
|
| 292 |
+
|
| 293 |
+
assert factorial(n).diff(n) == \
|
| 294 |
+
gamma(1 + n)*polygamma(0, 1 + n)
|
| 295 |
+
assert factorial(n**2).diff(n) == \
|
| 296 |
+
2*n*gamma(1 + n**2)*polygamma(0, 1 + n**2)
|
| 297 |
+
raises(ArgumentIndexError, lambda: factorial(n**2).fdiff(2))
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def test_factorial_series():
|
| 301 |
+
n = Symbol('n', integer=True)
|
| 302 |
+
|
| 303 |
+
assert factorial(n).series(n, 0, 3) == \
|
| 304 |
+
1 - n*EulerGamma + n**2*(EulerGamma**2/2 + pi**2/12) + O(n**3)
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
def test_factorial_rewrite():
|
| 308 |
+
n = Symbol('n', integer=True)
|
| 309 |
+
k = Symbol('k', integer=True, nonnegative=True)
|
| 310 |
+
|
| 311 |
+
assert factorial(n).rewrite(gamma) == gamma(n + 1)
|
| 312 |
+
_i = Dummy('i')
|
| 313 |
+
assert factorial(k).rewrite(Product).dummy_eq(Product(_i, (_i, 1, k)))
|
| 314 |
+
assert factorial(n).rewrite(Product) == factorial(n)
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
def test_factorial2():
|
| 318 |
+
n = Symbol('n', integer=True)
|
| 319 |
+
|
| 320 |
+
assert factorial2(-1) == 1
|
| 321 |
+
assert factorial2(0) == 1
|
| 322 |
+
assert factorial2(7) == 105
|
| 323 |
+
assert factorial2(8) == 384
|
| 324 |
+
|
| 325 |
+
# The following is exhaustive
|
| 326 |
+
tt = Symbol('tt', integer=True, nonnegative=True)
|
| 327 |
+
tte = Symbol('tte', even=True, nonnegative=True)
|
| 328 |
+
tpe = Symbol('tpe', even=True, positive=True)
|
| 329 |
+
tto = Symbol('tto', odd=True, nonnegative=True)
|
| 330 |
+
tf = Symbol('tf', integer=True, nonnegative=False)
|
| 331 |
+
tfe = Symbol('tfe', even=True, nonnegative=False)
|
| 332 |
+
tfo = Symbol('tfo', odd=True, nonnegative=False)
|
| 333 |
+
ft = Symbol('ft', integer=False, nonnegative=True)
|
| 334 |
+
ff = Symbol('ff', integer=False, nonnegative=False)
|
| 335 |
+
fn = Symbol('fn', integer=False)
|
| 336 |
+
nt = Symbol('nt', nonnegative=True)
|
| 337 |
+
nf = Symbol('nf', nonnegative=False)
|
| 338 |
+
nn = Symbol('nn')
|
| 339 |
+
z = Symbol('z', zero=True)
|
| 340 |
+
#Solves and Fixes Issue #10388 - This is the updated test for the same solved issue
|
| 341 |
+
raises(ValueError, lambda: factorial2(oo))
|
| 342 |
+
raises(ValueError, lambda: factorial2(Rational(5, 2)))
|
| 343 |
+
raises(ValueError, lambda: factorial2(-4))
|
| 344 |
+
assert factorial2(n).is_integer is None
|
| 345 |
+
assert factorial2(tt - 1).is_integer
|
| 346 |
+
assert factorial2(tte - 1).is_integer
|
| 347 |
+
assert factorial2(tpe - 3).is_integer
|
| 348 |
+
assert factorial2(tto - 4).is_integer
|
| 349 |
+
assert factorial2(tto - 2).is_integer
|
| 350 |
+
assert factorial2(tf).is_integer is None
|
| 351 |
+
assert factorial2(tfe).is_integer is None
|
| 352 |
+
assert factorial2(tfo).is_integer is None
|
| 353 |
+
assert factorial2(ft).is_integer is None
|
| 354 |
+
assert factorial2(ff).is_integer is None
|
| 355 |
+
assert factorial2(fn).is_integer is None
|
| 356 |
+
assert factorial2(nt).is_integer is None
|
| 357 |
+
assert factorial2(nf).is_integer is None
|
| 358 |
+
assert factorial2(nn).is_integer is None
|
| 359 |
+
|
| 360 |
+
assert factorial2(n).is_positive is None
|
| 361 |
+
assert factorial2(tt - 1).is_positive is True
|
| 362 |
+
assert factorial2(tte - 1).is_positive is True
|
| 363 |
+
assert factorial2(tpe - 3).is_positive is True
|
| 364 |
+
assert factorial2(tpe - 1).is_positive is True
|
| 365 |
+
assert factorial2(tto - 2).is_positive is True
|
| 366 |
+
assert factorial2(tto - 1).is_positive is True
|
| 367 |
+
assert factorial2(tf).is_positive is None
|
| 368 |
+
assert factorial2(tfe).is_positive is None
|
| 369 |
+
assert factorial2(tfo).is_positive is None
|
| 370 |
+
assert factorial2(ft).is_positive is None
|
| 371 |
+
assert factorial2(ff).is_positive is None
|
| 372 |
+
assert factorial2(fn).is_positive is None
|
| 373 |
+
assert factorial2(nt).is_positive is None
|
| 374 |
+
assert factorial2(nf).is_positive is None
|
| 375 |
+
assert factorial2(nn).is_positive is None
|
| 376 |
+
|
| 377 |
+
assert factorial2(tt).is_even is None
|
| 378 |
+
assert factorial2(tt).is_odd is None
|
| 379 |
+
assert factorial2(tte).is_even is None
|
| 380 |
+
assert factorial2(tte).is_odd is None
|
| 381 |
+
assert factorial2(tte + 2).is_even is True
|
| 382 |
+
assert factorial2(tpe).is_even is True
|
| 383 |
+
assert factorial2(tpe).is_odd is False
|
| 384 |
+
assert factorial2(tto).is_odd is True
|
| 385 |
+
assert factorial2(tf).is_even is None
|
| 386 |
+
assert factorial2(tf).is_odd is None
|
| 387 |
+
assert factorial2(tfe).is_even is None
|
| 388 |
+
assert factorial2(tfe).is_odd is None
|
| 389 |
+
assert factorial2(tfo).is_even is False
|
| 390 |
+
assert factorial2(tfo).is_odd is None
|
| 391 |
+
assert factorial2(z).is_even is False
|
| 392 |
+
assert factorial2(z).is_odd is True
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
def test_factorial2_rewrite():
|
| 396 |
+
n = Symbol('n', integer=True)
|
| 397 |
+
assert factorial2(n).rewrite(gamma) == \
|
| 398 |
+
2**(n/2)*Piecewise((1, Eq(Mod(n, 2), 0)), (sqrt(2)/sqrt(pi), Eq(Mod(n, 2), 1)))*gamma(n/2 + 1)
|
| 399 |
+
assert factorial2(2*n).rewrite(gamma) == 2**n*gamma(n + 1)
|
| 400 |
+
assert factorial2(2*n + 1).rewrite(gamma) == \
|
| 401 |
+
sqrt(2)*2**(n + S.Half)*gamma(n + Rational(3, 2))/sqrt(pi)
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
def test_binomial():
|
| 405 |
+
x = Symbol('x')
|
| 406 |
+
n = Symbol('n', integer=True)
|
| 407 |
+
nz = Symbol('nz', integer=True, nonzero=True)
|
| 408 |
+
k = Symbol('k', integer=True)
|
| 409 |
+
kp = Symbol('kp', integer=True, positive=True)
|
| 410 |
+
kn = Symbol('kn', integer=True, negative=True)
|
| 411 |
+
u = Symbol('u', negative=True)
|
| 412 |
+
v = Symbol('v', nonnegative=True)
|
| 413 |
+
p = Symbol('p', positive=True)
|
| 414 |
+
z = Symbol('z', zero=True)
|
| 415 |
+
nt = Symbol('nt', integer=False)
|
| 416 |
+
kt = Symbol('kt', integer=False)
|
| 417 |
+
a = Symbol('a', integer=True, nonnegative=True)
|
| 418 |
+
b = Symbol('b', integer=True, nonnegative=True)
|
| 419 |
+
|
| 420 |
+
assert binomial(0, 0) == 1
|
| 421 |
+
assert binomial(1, 1) == 1
|
| 422 |
+
assert binomial(10, 10) == 1
|
| 423 |
+
assert binomial(n, z) == 1
|
| 424 |
+
assert binomial(1, 2) == 0
|
| 425 |
+
assert binomial(-1, 2) == 1
|
| 426 |
+
assert binomial(1, -1) == 0
|
| 427 |
+
assert binomial(-1, 1) == -1
|
| 428 |
+
assert binomial(-1, -1) == 0
|
| 429 |
+
assert binomial(S.Half, S.Half) == 1
|
| 430 |
+
assert binomial(-10, 1) == -10
|
| 431 |
+
assert binomial(-10, 7) == -11440
|
| 432 |
+
assert binomial(n, -1) == 0 # holds for all integers (negative, zero, positive)
|
| 433 |
+
assert binomial(kp, -1) == 0
|
| 434 |
+
assert binomial(nz, 0) == 1
|
| 435 |
+
assert expand_func(binomial(n, 1)) == n
|
| 436 |
+
assert expand_func(binomial(n, 2)) == n*(n - 1)/2
|
| 437 |
+
assert expand_func(binomial(n, n - 2)) == n*(n - 1)/2
|
| 438 |
+
assert expand_func(binomial(n, n - 1)) == n
|
| 439 |
+
assert binomial(n, 3).func == binomial
|
| 440 |
+
assert binomial(n, 3).expand(func=True) == n**3/6 - n**2/2 + n/3
|
| 441 |
+
assert expand_func(binomial(n, 3)) == n*(n - 2)*(n - 1)/6
|
| 442 |
+
assert binomial(n, n).func == binomial # e.g. (-1, -1) == 0, (2, 2) == 1
|
| 443 |
+
assert binomial(n, n + 1).func == binomial # e.g. (-1, 0) == 1
|
| 444 |
+
assert binomial(kp, kp + 1) == 0
|
| 445 |
+
assert binomial(kn, kn) == 0 # issue #14529
|
| 446 |
+
assert binomial(n, u).func == binomial
|
| 447 |
+
assert binomial(kp, u).func == binomial
|
| 448 |
+
assert binomial(n, p).func == binomial
|
| 449 |
+
assert binomial(n, k).func == binomial
|
| 450 |
+
assert binomial(n, n + p).func == binomial
|
| 451 |
+
assert binomial(kp, kp + p).func == binomial
|
| 452 |
+
|
| 453 |
+
assert expand_func(binomial(n, n - 3)) == n*(n - 2)*(n - 1)/6
|
| 454 |
+
|
| 455 |
+
assert binomial(n, k).is_integer
|
| 456 |
+
assert binomial(nt, k).is_integer is None
|
| 457 |
+
assert binomial(x, nt).is_integer is False
|
| 458 |
+
|
| 459 |
+
assert binomial(gamma(25), 6) == 79232165267303928292058750056084441948572511312165380965440075720159859792344339983120618959044048198214221915637090855535036339620413440000
|
| 460 |
+
assert binomial(1324, 47) == 906266255662694632984994480774946083064699457235920708992926525848438478406790323869952
|
| 461 |
+
assert binomial(1735, 43) == 190910140420204130794758005450919715396159959034348676124678207874195064798202216379800
|
| 462 |
+
assert binomial(2512, 53) == 213894469313832631145798303740098720367984955243020898718979538096223399813295457822575338958939834177325304000
|
| 463 |
+
assert binomial(3383, 52) == 27922807788818096863529701501764372757272890613101645521813434902890007725667814813832027795881839396839287659777235
|
| 464 |
+
assert binomial(4321, 51) == 124595639629264868916081001263541480185227731958274383287107643816863897851139048158022599533438936036467601690983780576
|
| 465 |
+
|
| 466 |
+
assert binomial(a, b).is_nonnegative is True
|
| 467 |
+
assert binomial(-1, 2, evaluate=False).is_nonnegative is True
|
| 468 |
+
assert binomial(10, 5, evaluate=False).is_nonnegative is True
|
| 469 |
+
assert binomial(10, -3, evaluate=False).is_nonnegative is True
|
| 470 |
+
assert binomial(-10, -3, evaluate=False).is_nonnegative is True
|
| 471 |
+
assert binomial(-10, 2, evaluate=False).is_nonnegative is True
|
| 472 |
+
assert binomial(-10, 1, evaluate=False).is_nonnegative is False
|
| 473 |
+
assert binomial(-10, 7, evaluate=False).is_nonnegative is False
|
| 474 |
+
|
| 475 |
+
# issue #14625
|
| 476 |
+
for _ in (pi, -pi, nt, v, a):
|
| 477 |
+
assert binomial(_, _) == 1
|
| 478 |
+
assert binomial(_, _ - 1) == _
|
| 479 |
+
assert isinstance(binomial(u, u), binomial)
|
| 480 |
+
assert isinstance(binomial(u, u - 1), binomial)
|
| 481 |
+
assert isinstance(binomial(x, x), binomial)
|
| 482 |
+
assert isinstance(binomial(x, x - 1), binomial)
|
| 483 |
+
|
| 484 |
+
#issue #18802
|
| 485 |
+
assert expand_func(binomial(x + 1, x)) == x + 1
|
| 486 |
+
assert expand_func(binomial(x, x - 1)) == x
|
| 487 |
+
assert expand_func(binomial(x + 1, x - 1)) == x*(x + 1)/2
|
| 488 |
+
assert expand_func(binomial(x**2 + 1, x**2)) == x**2 + 1
|
| 489 |
+
|
| 490 |
+
# issue #13980 and #13981
|
| 491 |
+
assert binomial(-7, -5) == 0
|
| 492 |
+
assert binomial(-23, -12) == 0
|
| 493 |
+
assert binomial(Rational(13, 2), -10) == 0
|
| 494 |
+
assert binomial(-49, -51) == 0
|
| 495 |
+
|
| 496 |
+
assert binomial(19, Rational(-7, 2)) == S(-68719476736)/(911337863661225*pi)
|
| 497 |
+
assert binomial(0, Rational(3, 2)) == S(-2)/(3*pi)
|
| 498 |
+
assert binomial(-3, Rational(-7, 2)) is zoo
|
| 499 |
+
assert binomial(kn, kt) is zoo
|
| 500 |
+
|
| 501 |
+
assert binomial(nt, kt).func == binomial
|
| 502 |
+
assert binomial(nt, Rational(15, 6)) == 8*gamma(nt + 1)/(15*sqrt(pi)*gamma(nt - Rational(3, 2)))
|
| 503 |
+
assert binomial(Rational(20, 3), Rational(-10, 8)) == gamma(Rational(23, 3))/(gamma(Rational(-1, 4))*gamma(Rational(107, 12)))
|
| 504 |
+
assert binomial(Rational(19, 2), Rational(-7, 2)) == Rational(-1615, 8388608)
|
| 505 |
+
assert binomial(Rational(-13, 5), Rational(-7, 8)) == gamma(Rational(-8, 5))/(gamma(Rational(-29, 40))*gamma(Rational(1, 8)))
|
| 506 |
+
assert binomial(Rational(-19, 8), Rational(-13, 5)) == gamma(Rational(-11, 8))/(gamma(Rational(-8, 5))*gamma(Rational(49, 40)))
|
| 507 |
+
|
| 508 |
+
# binomial for complexes
|
| 509 |
+
assert binomial(I, Rational(-89, 8)) == gamma(1 + I)/(gamma(Rational(-81, 8))*gamma(Rational(97, 8) + I))
|
| 510 |
+
assert binomial(I, 2*I) == gamma(1 + I)/(gamma(1 - I)*gamma(1 + 2*I))
|
| 511 |
+
assert binomial(-7, I) is zoo
|
| 512 |
+
assert binomial(Rational(-7, 6), I) == gamma(Rational(-1, 6))/(gamma(Rational(-1, 6) - I)*gamma(1 + I))
|
| 513 |
+
assert binomial((1+2*I), (1+3*I)) == gamma(2 + 2*I)/(gamma(1 - I)*gamma(2 + 3*I))
|
| 514 |
+
assert binomial(I, 5) == Rational(1, 3) - I/S(12)
|
| 515 |
+
assert binomial((2*I + 3), 7) == -13*I/S(63)
|
| 516 |
+
assert isinstance(binomial(I, n), binomial)
|
| 517 |
+
assert expand_func(binomial(3, 2, evaluate=False)) == 3
|
| 518 |
+
assert expand_func(binomial(n, 0, evaluate=False)) == 1
|
| 519 |
+
assert expand_func(binomial(n, -2, evaluate=False)) == 0
|
| 520 |
+
assert expand_func(binomial(n, k)) == binomial(n, k)
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
def test_binomial_Mod():
|
| 524 |
+
p, q = 10**5 + 3, 10**9 + 33 # prime modulo
|
| 525 |
+
r = 10**7 + 5 # composite modulo
|
| 526 |
+
|
| 527 |
+
# A few tests to get coverage
|
| 528 |
+
# Lucas Theorem
|
| 529 |
+
assert Mod(binomial(156675, 4433, evaluate=False), p) == Mod(binomial(156675, 4433), p)
|
| 530 |
+
|
| 531 |
+
# factorial Mod
|
| 532 |
+
assert Mod(binomial(1234, 432, evaluate=False), q) == Mod(binomial(1234, 432), q)
|
| 533 |
+
|
| 534 |
+
# binomial factorize
|
| 535 |
+
assert Mod(binomial(253, 113, evaluate=False), r) == Mod(binomial(253, 113), r)
|
| 536 |
+
|
| 537 |
+
# using Granville's generalisation of Lucas' Theorem
|
| 538 |
+
assert Mod(binomial(10**18, 10**12, evaluate=False), p*p) == 3744312326
|
| 539 |
+
|
| 540 |
+
|
| 541 |
+
@slow
|
| 542 |
+
def test_binomial_Mod_slow():
|
| 543 |
+
p, q = 10**5 + 3, 10**9 + 33 # prime modulo
|
| 544 |
+
r, s = 10**7 + 5, 33333333 # composite modulo
|
| 545 |
+
|
| 546 |
+
n, k, m = symbols('n k m')
|
| 547 |
+
assert (binomial(n, k) % q).subs({n: s, k: p}) == Mod(binomial(s, p), q)
|
| 548 |
+
assert (binomial(n, k) % m).subs({n: 8, k: 5, m: 13}) == 4
|
| 549 |
+
assert (binomial(9, k) % 7).subs(k, 2) == 1
|
| 550 |
+
|
| 551 |
+
# Lucas Theorem
|
| 552 |
+
assert Mod(binomial(123456, 43253, evaluate=False), p) == Mod(binomial(123456, 43253), p)
|
| 553 |
+
assert Mod(binomial(-178911, 237, evaluate=False), p) == Mod(-binomial(178911 + 237 - 1, 237), p)
|
| 554 |
+
assert Mod(binomial(-178911, 238, evaluate=False), p) == Mod(binomial(178911 + 238 - 1, 238), p)
|
| 555 |
+
|
| 556 |
+
# factorial Mod
|
| 557 |
+
assert Mod(binomial(9734, 451, evaluate=False), q) == Mod(binomial(9734, 451), q)
|
| 558 |
+
assert Mod(binomial(-10733, 4459, evaluate=False), q) == Mod(binomial(-10733, 4459), q)
|
| 559 |
+
assert Mod(binomial(-15733, 4458, evaluate=False), q) == Mod(binomial(-15733, 4458), q)
|
| 560 |
+
assert Mod(binomial(23, -38, evaluate=False), q) is S.Zero
|
| 561 |
+
assert Mod(binomial(23, 38, evaluate=False), q) is S.Zero
|
| 562 |
+
|
| 563 |
+
# binomial factorize
|
| 564 |
+
assert Mod(binomial(753, 119, evaluate=False), r) == Mod(binomial(753, 119), r)
|
| 565 |
+
assert Mod(binomial(3781, 948, evaluate=False), s) == Mod(binomial(3781, 948), s)
|
| 566 |
+
assert Mod(binomial(25773, 1793, evaluate=False), s) == Mod(binomial(25773, 1793), s)
|
| 567 |
+
assert Mod(binomial(-753, 118, evaluate=False), r) == Mod(binomial(-753, 118), r)
|
| 568 |
+
assert Mod(binomial(-25773, 1793, evaluate=False), s) == Mod(binomial(-25773, 1793), s)
|
| 569 |
+
|
| 570 |
+
|
| 571 |
+
def test_binomial_diff():
|
| 572 |
+
n = Symbol('n', integer=True)
|
| 573 |
+
k = Symbol('k', integer=True)
|
| 574 |
+
|
| 575 |
+
assert binomial(n, k).diff(n) == \
|
| 576 |
+
(-polygamma(0, 1 + n - k) + polygamma(0, 1 + n))*binomial(n, k)
|
| 577 |
+
assert binomial(n**2, k**3).diff(n) == \
|
| 578 |
+
2*n*(-polygamma(
|
| 579 |
+
0, 1 + n**2 - k**3) + polygamma(0, 1 + n**2))*binomial(n**2, k**3)
|
| 580 |
+
|
| 581 |
+
assert binomial(n, k).diff(k) == \
|
| 582 |
+
(-polygamma(0, 1 + k) + polygamma(0, 1 + n - k))*binomial(n, k)
|
| 583 |
+
assert binomial(n**2, k**3).diff(k) == \
|
| 584 |
+
3*k**2*(-polygamma(
|
| 585 |
+
0, 1 + k**3) + polygamma(0, 1 + n**2 - k**3))*binomial(n**2, k**3)
|
| 586 |
+
raises(ArgumentIndexError, lambda: binomial(n, k).fdiff(3))
|
| 587 |
+
|
| 588 |
+
|
| 589 |
+
def test_binomial_rewrite():
|
| 590 |
+
n = Symbol('n', integer=True)
|
| 591 |
+
k = Symbol('k', integer=True)
|
| 592 |
+
x = Symbol('x')
|
| 593 |
+
|
| 594 |
+
assert binomial(n, k).rewrite(
|
| 595 |
+
factorial) == factorial(n)/(factorial(k)*factorial(n - k))
|
| 596 |
+
assert binomial(
|
| 597 |
+
n, k).rewrite(gamma) == gamma(n + 1)/(gamma(k + 1)*gamma(n - k + 1))
|
| 598 |
+
assert binomial(n, k).rewrite(ff) == ff(n, k) / factorial(k)
|
| 599 |
+
assert binomial(n, x).rewrite(ff) == binomial(n, x)
|
| 600 |
+
|
| 601 |
+
|
| 602 |
+
@XFAIL
|
| 603 |
+
def test_factorial_simplify_fail():
|
| 604 |
+
# simplify(factorial(x + 1).diff(x) - ((x + 1)*factorial(x)).diff(x))) == 0
|
| 605 |
+
from sympy.abc import x
|
| 606 |
+
assert simplify(x*polygamma(0, x + 1) - x*polygamma(0, x + 2) +
|
| 607 |
+
polygamma(0, x + 1) - polygamma(0, x + 2) + 1) == 0
|
| 608 |
+
|
| 609 |
+
|
| 610 |
+
def test_subfactorial():
|
| 611 |
+
assert all(subfactorial(i) == ans for i, ans in enumerate(
|
| 612 |
+
[1, 0, 1, 2, 9, 44, 265, 1854, 14833, 133496]))
|
| 613 |
+
assert subfactorial(oo) is oo
|
| 614 |
+
assert subfactorial(nan) is nan
|
| 615 |
+
assert subfactorial(23) == 9510425471055777937262
|
| 616 |
+
assert unchanged(subfactorial, 2.2)
|
| 617 |
+
|
| 618 |
+
x = Symbol('x')
|
| 619 |
+
assert subfactorial(x).rewrite(uppergamma) == uppergamma(x + 1, -1)/S.Exp1
|
| 620 |
+
|
| 621 |
+
tt = Symbol('tt', integer=True, nonnegative=True)
|
| 622 |
+
tf = Symbol('tf', integer=True, nonnegative=False)
|
| 623 |
+
tn = Symbol('tf', integer=True)
|
| 624 |
+
ft = Symbol('ft', integer=False, nonnegative=True)
|
| 625 |
+
ff = Symbol('ff', integer=False, nonnegative=False)
|
| 626 |
+
fn = Symbol('ff', integer=False)
|
| 627 |
+
nt = Symbol('nt', nonnegative=True)
|
| 628 |
+
nf = Symbol('nf', nonnegative=False)
|
| 629 |
+
nn = Symbol('nf')
|
| 630 |
+
te = Symbol('te', even=True, nonnegative=True)
|
| 631 |
+
to = Symbol('to', odd=True, nonnegative=True)
|
| 632 |
+
assert subfactorial(tt).is_integer
|
| 633 |
+
assert subfactorial(tf).is_integer is None
|
| 634 |
+
assert subfactorial(tn).is_integer is None
|
| 635 |
+
assert subfactorial(ft).is_integer is None
|
| 636 |
+
assert subfactorial(ff).is_integer is None
|
| 637 |
+
assert subfactorial(fn).is_integer is None
|
| 638 |
+
assert subfactorial(nt).is_integer is None
|
| 639 |
+
assert subfactorial(nf).is_integer is None
|
| 640 |
+
assert subfactorial(nn).is_integer is None
|
| 641 |
+
assert subfactorial(tt).is_nonnegative
|
| 642 |
+
assert subfactorial(tf).is_nonnegative is None
|
| 643 |
+
assert subfactorial(tn).is_nonnegative is None
|
| 644 |
+
assert subfactorial(ft).is_nonnegative is None
|
| 645 |
+
assert subfactorial(ff).is_nonnegative is None
|
| 646 |
+
assert subfactorial(fn).is_nonnegative is None
|
| 647 |
+
assert subfactorial(nt).is_nonnegative is None
|
| 648 |
+
assert subfactorial(nf).is_nonnegative is None
|
| 649 |
+
assert subfactorial(nn).is_nonnegative is None
|
| 650 |
+
assert subfactorial(tt).is_even is None
|
| 651 |
+
assert subfactorial(tt).is_odd is None
|
| 652 |
+
assert subfactorial(te).is_odd is True
|
| 653 |
+
assert subfactorial(to).is_even is True
|