Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/__init__.py +75 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/bivariate.py +509 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/decompogen.py +126 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/deutils.py +273 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/diophantine/__init__.py +5 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/diophantine/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/diophantine/diophantine.py +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/diophantine/tests/__init__.py +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/diophantine/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/diophantine/tests/__pycache__/test_diophantine.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/diophantine/tests/test_diophantine.py +1051 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/inequalities.py +986 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/pde.py +971 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/polysys.py +437 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/recurr.py +843 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/simplex.py +1141 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/solvers.py +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/solveset.py +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/tests/__init__.py +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/test_constantsimp.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/test_inequalities.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/test_numeric.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/test_pde.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/test_simplex.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/tests/test_constantsimp.py +179 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/tests/test_decompogen.py +59 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/tests/test_inequalities.py +500 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/tests/test_numeric.py +139 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/tests/test_pde.py +239 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/tests/test_polysys.py +178 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/tests/test_recurr.py +295 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/tests/test_simplex.py +254 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/tests/test_solvers.py +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/tests/test_solveset.py +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/tensor/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/tensor/__pycache__/index_methods.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/tensor/__pycache__/indexed.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/tensor/__pycache__/toperators.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/tensor/array/expressions/__pycache__/from_indexed_to_array.cpython-310.pyc +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/tensor/array/mutable_ndim_array.py +13 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/tensor/array/ndim_array.py +600 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/tensor/array/sparse_ndim_array.py +196 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/tensor/array/tests/__init__.py +0 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/tensor/array/tests/test_array_comprehension.py +78 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/tensor/array/tests/test_arrayop.py +361 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/tensor/array/tests/test_mutable_ndim_array.py +374 -0
- evalkit_internvl/lib/python3.10/site-packages/sympy/tensor/array/tests/test_ndim_array_conversions.py +22 -0
- evalkit_tf437/lib/python3.10/site-packages/accelerate/__pycache__/__init__.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/accelerate/__pycache__/big_modeling.cpython-310.pyc +0 -0
- evalkit_tf437/lib/python3.10/site-packages/accelerate/__pycache__/checkpointing.cpython-310.pyc +0 -0
evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/__init__.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""A module for solving all kinds of equations.
|
| 2 |
+
|
| 3 |
+
Examples
|
| 4 |
+
========
|
| 5 |
+
|
| 6 |
+
>>> from sympy.solvers import solve
|
| 7 |
+
>>> from sympy.abc import x
|
| 8 |
+
>>> solve(((x + 1)**5).expand(), x)
|
| 9 |
+
[-1]
|
| 10 |
+
"""
|
| 11 |
+
from sympy.core.assumptions import check_assumptions, failing_assumptions
|
| 12 |
+
|
| 13 |
+
from .solvers import solve, solve_linear_system, solve_linear_system_LU, \
|
| 14 |
+
solve_undetermined_coeffs, nsolve, solve_linear, checksol, \
|
| 15 |
+
det_quick, inv_quick
|
| 16 |
+
|
| 17 |
+
from .diophantine import diophantine
|
| 18 |
+
|
| 19 |
+
from .recurr import rsolve, rsolve_poly, rsolve_ratio, rsolve_hyper
|
| 20 |
+
|
| 21 |
+
from .ode import checkodesol, classify_ode, dsolve, \
|
| 22 |
+
homogeneous_order
|
| 23 |
+
|
| 24 |
+
from .polysys import solve_poly_system, solve_triangulated
|
| 25 |
+
|
| 26 |
+
from .pde import pde_separate, pde_separate_add, pde_separate_mul, \
|
| 27 |
+
pdsolve, classify_pde, checkpdesol
|
| 28 |
+
|
| 29 |
+
from .deutils import ode_order
|
| 30 |
+
|
| 31 |
+
from .inequalities import reduce_inequalities, reduce_abs_inequality, \
|
| 32 |
+
reduce_abs_inequalities, solve_poly_inequality, solve_rational_inequalities, solve_univariate_inequality
|
| 33 |
+
|
| 34 |
+
from .decompogen import decompogen
|
| 35 |
+
|
| 36 |
+
from .solveset import solveset, linsolve, linear_eq_to_matrix, nonlinsolve, substitution
|
| 37 |
+
|
| 38 |
+
from .simplex import lpmin, lpmax, linprog
|
| 39 |
+
|
| 40 |
+
# This is here instead of sympy/sets/__init__.py to avoid circular import issues
|
| 41 |
+
from ..core.singleton import S
|
| 42 |
+
Complexes = S.Complexes
|
| 43 |
+
|
| 44 |
+
__all__ = [
|
| 45 |
+
'solve', 'solve_linear_system', 'solve_linear_system_LU',
|
| 46 |
+
'solve_undetermined_coeffs', 'nsolve', 'solve_linear', 'checksol',
|
| 47 |
+
'det_quick', 'inv_quick', 'check_assumptions', 'failing_assumptions',
|
| 48 |
+
|
| 49 |
+
'diophantine',
|
| 50 |
+
|
| 51 |
+
'rsolve', 'rsolve_poly', 'rsolve_ratio', 'rsolve_hyper',
|
| 52 |
+
|
| 53 |
+
'checkodesol', 'classify_ode', 'dsolve', 'homogeneous_order',
|
| 54 |
+
|
| 55 |
+
'solve_poly_system', 'solve_triangulated',
|
| 56 |
+
|
| 57 |
+
'pde_separate', 'pde_separate_add', 'pde_separate_mul', 'pdsolve',
|
| 58 |
+
'classify_pde', 'checkpdesol',
|
| 59 |
+
|
| 60 |
+
'ode_order',
|
| 61 |
+
|
| 62 |
+
'reduce_inequalities', 'reduce_abs_inequality', 'reduce_abs_inequalities',
|
| 63 |
+
'solve_poly_inequality', 'solve_rational_inequalities',
|
| 64 |
+
'solve_univariate_inequality',
|
| 65 |
+
|
| 66 |
+
'decompogen',
|
| 67 |
+
|
| 68 |
+
'solveset', 'linsolve', 'linear_eq_to_matrix', 'nonlinsolve',
|
| 69 |
+
'substitution',
|
| 70 |
+
|
| 71 |
+
# This is here instead of sympy/sets/__init__.py to avoid circular import issues
|
| 72 |
+
'Complexes',
|
| 73 |
+
|
| 74 |
+
'lpmin', 'lpmax', 'linprog'
|
| 75 |
+
]
|
evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/bivariate.py
ADDED
|
@@ -0,0 +1,509 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.add import Add
|
| 2 |
+
from sympy.core.exprtools import factor_terms
|
| 3 |
+
from sympy.core.function import expand_log, _mexpand
|
| 4 |
+
from sympy.core.power import Pow
|
| 5 |
+
from sympy.core.singleton import S
|
| 6 |
+
from sympy.core.sorting import ordered
|
| 7 |
+
from sympy.core.symbol import Dummy
|
| 8 |
+
from sympy.functions.elementary.exponential import (LambertW, exp, log)
|
| 9 |
+
from sympy.functions.elementary.miscellaneous import root
|
| 10 |
+
from sympy.polys.polyroots import roots
|
| 11 |
+
from sympy.polys.polytools import Poly, factor
|
| 12 |
+
from sympy.simplify.simplify import separatevars
|
| 13 |
+
from sympy.simplify.radsimp import collect
|
| 14 |
+
from sympy.simplify.simplify import powsimp
|
| 15 |
+
from sympy.solvers.solvers import solve, _invert
|
| 16 |
+
from sympy.utilities.iterables import uniq
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _filtered_gens(poly, symbol):
|
| 20 |
+
"""process the generators of ``poly``, returning the set of generators that
|
| 21 |
+
have ``symbol``. If there are two generators that are inverses of each other,
|
| 22 |
+
prefer the one that has no denominator.
|
| 23 |
+
|
| 24 |
+
Examples
|
| 25 |
+
========
|
| 26 |
+
|
| 27 |
+
>>> from sympy.solvers.bivariate import _filtered_gens
|
| 28 |
+
>>> from sympy import Poly, exp
|
| 29 |
+
>>> from sympy.abc import x
|
| 30 |
+
>>> _filtered_gens(Poly(x + 1/x + exp(x)), x)
|
| 31 |
+
{x, exp(x)}
|
| 32 |
+
|
| 33 |
+
"""
|
| 34 |
+
# TODO it would be good to pick the smallest divisible power
|
| 35 |
+
# instead of the base for something like x**4 + x**2 -->
|
| 36 |
+
# return x**2 not x
|
| 37 |
+
gens = {g for g in poly.gens if symbol in g.free_symbols}
|
| 38 |
+
for g in list(gens):
|
| 39 |
+
ag = 1/g
|
| 40 |
+
if g in gens and ag in gens:
|
| 41 |
+
if ag.as_numer_denom()[1] is not S.One:
|
| 42 |
+
g = ag
|
| 43 |
+
gens.remove(g)
|
| 44 |
+
return gens
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _mostfunc(lhs, func, X=None):
|
| 48 |
+
"""Returns the term in lhs which contains the most of the
|
| 49 |
+
func-type things e.g. log(log(x)) wins over log(x) if both terms appear.
|
| 50 |
+
|
| 51 |
+
``func`` can be a function (exp, log, etc...) or any other SymPy object,
|
| 52 |
+
like Pow.
|
| 53 |
+
|
| 54 |
+
If ``X`` is not ``None``, then the function returns the term composed with the
|
| 55 |
+
most ``func`` having the specified variable.
|
| 56 |
+
|
| 57 |
+
Examples
|
| 58 |
+
========
|
| 59 |
+
|
| 60 |
+
>>> from sympy.solvers.bivariate import _mostfunc
|
| 61 |
+
>>> from sympy import exp
|
| 62 |
+
>>> from sympy.abc import x, y
|
| 63 |
+
>>> _mostfunc(exp(x) + exp(exp(x) + 2), exp)
|
| 64 |
+
exp(exp(x) + 2)
|
| 65 |
+
>>> _mostfunc(exp(x) + exp(exp(y) + 2), exp)
|
| 66 |
+
exp(exp(y) + 2)
|
| 67 |
+
>>> _mostfunc(exp(x) + exp(exp(y) + 2), exp, x)
|
| 68 |
+
exp(x)
|
| 69 |
+
>>> _mostfunc(x, exp, x) is None
|
| 70 |
+
True
|
| 71 |
+
>>> _mostfunc(exp(x) + exp(x*y), exp, x)
|
| 72 |
+
exp(x)
|
| 73 |
+
"""
|
| 74 |
+
fterms = [tmp for tmp in lhs.atoms(func) if (not X or
|
| 75 |
+
X.is_Symbol and X in tmp.free_symbols or
|
| 76 |
+
not X.is_Symbol and tmp.has(X))]
|
| 77 |
+
if len(fterms) == 1:
|
| 78 |
+
return fterms[0]
|
| 79 |
+
elif fterms:
|
| 80 |
+
return max(list(ordered(fterms)), key=lambda x: x.count(func))
|
| 81 |
+
return None
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def _linab(arg, symbol):
|
| 85 |
+
"""Return ``a, b, X`` assuming ``arg`` can be written as ``a*X + b``
|
| 86 |
+
where ``X`` is a symbol-dependent factor and ``a`` and ``b`` are
|
| 87 |
+
independent of ``symbol``.
|
| 88 |
+
|
| 89 |
+
Examples
|
| 90 |
+
========
|
| 91 |
+
|
| 92 |
+
>>> from sympy.solvers.bivariate import _linab
|
| 93 |
+
>>> from sympy.abc import x, y
|
| 94 |
+
>>> from sympy import exp, S
|
| 95 |
+
>>> _linab(S(2), x)
|
| 96 |
+
(2, 0, 1)
|
| 97 |
+
>>> _linab(2*x, x)
|
| 98 |
+
(2, 0, x)
|
| 99 |
+
>>> _linab(y + y*x + 2*x, x)
|
| 100 |
+
(y + 2, y, x)
|
| 101 |
+
>>> _linab(3 + 2*exp(x), x)
|
| 102 |
+
(2, 3, exp(x))
|
| 103 |
+
"""
|
| 104 |
+
arg = factor_terms(arg.expand())
|
| 105 |
+
ind, dep = arg.as_independent(symbol)
|
| 106 |
+
if arg.is_Mul and dep.is_Add:
|
| 107 |
+
a, b, x = _linab(dep, symbol)
|
| 108 |
+
return ind*a, ind*b, x
|
| 109 |
+
if not arg.is_Add:
|
| 110 |
+
b = 0
|
| 111 |
+
a, x = ind, dep
|
| 112 |
+
else:
|
| 113 |
+
b = ind
|
| 114 |
+
a, x = separatevars(dep).as_independent(symbol, as_Add=False)
|
| 115 |
+
if x.could_extract_minus_sign():
|
| 116 |
+
a = -a
|
| 117 |
+
x = -x
|
| 118 |
+
return a, b, x
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def _lambert(eq, x):
|
| 122 |
+
"""
|
| 123 |
+
Given an expression assumed to be in the form
|
| 124 |
+
``F(X, a..f) = a*log(b*X + c) + d*X + f = 0``
|
| 125 |
+
where X = g(x) and x = g^-1(X), return the Lambert solution,
|
| 126 |
+
``x = g^-1(-c/b + (a/d)*W(d/(a*b)*exp(c*d/a/b)*exp(-f/a)))``.
|
| 127 |
+
"""
|
| 128 |
+
eq = _mexpand(expand_log(eq))
|
| 129 |
+
mainlog = _mostfunc(eq, log, x)
|
| 130 |
+
if not mainlog:
|
| 131 |
+
return [] # violated assumptions
|
| 132 |
+
other = eq.subs(mainlog, 0)
|
| 133 |
+
if isinstance(-other, log):
|
| 134 |
+
eq = (eq - other).subs(mainlog, mainlog.args[0])
|
| 135 |
+
mainlog = mainlog.args[0]
|
| 136 |
+
if not isinstance(mainlog, log):
|
| 137 |
+
return [] # violated assumptions
|
| 138 |
+
other = -(-other).args[0]
|
| 139 |
+
eq += other
|
| 140 |
+
if x not in other.free_symbols:
|
| 141 |
+
return [] # violated assumptions
|
| 142 |
+
d, f, X2 = _linab(other, x)
|
| 143 |
+
logterm = collect(eq - other, mainlog)
|
| 144 |
+
a = logterm.as_coefficient(mainlog)
|
| 145 |
+
if a is None or x in a.free_symbols:
|
| 146 |
+
return [] # violated assumptions
|
| 147 |
+
logarg = mainlog.args[0]
|
| 148 |
+
b, c, X1 = _linab(logarg, x)
|
| 149 |
+
if X1 != X2:
|
| 150 |
+
return [] # violated assumptions
|
| 151 |
+
|
| 152 |
+
# invert the generator X1 so we have x(u)
|
| 153 |
+
u = Dummy('rhs')
|
| 154 |
+
xusolns = solve(X1 - u, x)
|
| 155 |
+
|
| 156 |
+
# There are infinitely many branches for LambertW
|
| 157 |
+
# but only branches for k = -1 and 0 might be real. The k = 0
|
| 158 |
+
# branch is real and the k = -1 branch is real if the LambertW argumen
|
| 159 |
+
# in in range [-1/e, 0]. Since `solve` does not return infinite
|
| 160 |
+
# solutions we will only include the -1 branch if it tests as real.
|
| 161 |
+
# Otherwise, inclusion of any LambertW in the solution indicates to
|
| 162 |
+
# the user that there are imaginary solutions corresponding to
|
| 163 |
+
# different k values.
|
| 164 |
+
lambert_real_branches = [-1, 0]
|
| 165 |
+
sol = []
|
| 166 |
+
|
| 167 |
+
# solution of the given Lambert equation is like
|
| 168 |
+
# sol = -c/b + (a/d)*LambertW(arg, k),
|
| 169 |
+
# where arg = d/(a*b)*exp((c*d-b*f)/a/b) and k in lambert_real_branches.
|
| 170 |
+
# Instead of considering the single arg, `d/(a*b)*exp((c*d-b*f)/a/b)`,
|
| 171 |
+
# the individual `p` roots obtained when writing `exp((c*d-b*f)/a/b)`
|
| 172 |
+
# as `exp(A/p) = exp(A)**(1/p)`, where `p` is an Integer, are used.
|
| 173 |
+
|
| 174 |
+
# calculating args for LambertW
|
| 175 |
+
num, den = ((c*d-b*f)/a/b).as_numer_denom()
|
| 176 |
+
p, den = den.as_coeff_Mul()
|
| 177 |
+
e = exp(num/den)
|
| 178 |
+
t = Dummy('t')
|
| 179 |
+
args = [d/(a*b)*t for t in roots(t**p - e, t).keys()]
|
| 180 |
+
|
| 181 |
+
# calculating solutions from args
|
| 182 |
+
for arg in args:
|
| 183 |
+
for k in lambert_real_branches:
|
| 184 |
+
w = LambertW(arg, k)
|
| 185 |
+
if k and not w.is_real:
|
| 186 |
+
continue
|
| 187 |
+
rhs = -c/b + (a/d)*w
|
| 188 |
+
|
| 189 |
+
sol.extend(xu.subs(u, rhs) for xu in xusolns)
|
| 190 |
+
return sol
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def _solve_lambert(f, symbol, gens):
|
| 194 |
+
"""Return solution to ``f`` if it is a Lambert-type expression
|
| 195 |
+
else raise NotImplementedError.
|
| 196 |
+
|
| 197 |
+
For ``f(X, a..f) = a*log(b*X + c) + d*X - f = 0`` the solution
|
| 198 |
+
for ``X`` is ``X = -c/b + (a/d)*W(d/(a*b)*exp(c*d/a/b)*exp(f/a))``.
|
| 199 |
+
There are a variety of forms for `f(X, a..f)` as enumerated below:
|
| 200 |
+
|
| 201 |
+
1a1)
|
| 202 |
+
if B**B = R for R not in [0, 1] (since those cases would already
|
| 203 |
+
be solved before getting here) then log of both sides gives
|
| 204 |
+
log(B) + log(log(B)) = log(log(R)) and
|
| 205 |
+
X = log(B), a = 1, b = 1, c = 0, d = 1, f = log(log(R))
|
| 206 |
+
1a2)
|
| 207 |
+
if B*(b*log(B) + c)**a = R then log of both sides gives
|
| 208 |
+
log(B) + a*log(b*log(B) + c) = log(R) and
|
| 209 |
+
X = log(B), d=1, f=log(R)
|
| 210 |
+
1b)
|
| 211 |
+
if a*log(b*B + c) + d*B = R and
|
| 212 |
+
X = B, f = R
|
| 213 |
+
2a)
|
| 214 |
+
if (b*B + c)*exp(d*B + g) = R then log of both sides gives
|
| 215 |
+
log(b*B + c) + d*B + g = log(R) and
|
| 216 |
+
X = B, a = 1, f = log(R) - g
|
| 217 |
+
2b)
|
| 218 |
+
if g*exp(d*B + h) - b*B = c then the log form is
|
| 219 |
+
log(g) + d*B + h - log(b*B + c) = 0 and
|
| 220 |
+
X = B, a = -1, f = -h - log(g)
|
| 221 |
+
3)
|
| 222 |
+
if d*p**(a*B + g) - b*B = c then the log form is
|
| 223 |
+
log(d) + (a*B + g)*log(p) - log(b*B + c) = 0 and
|
| 224 |
+
X = B, a = -1, d = a*log(p), f = -log(d) - g*log(p)
|
| 225 |
+
"""
|
| 226 |
+
|
| 227 |
+
def _solve_even_degree_expr(expr, t, symbol):
|
| 228 |
+
"""Return the unique solutions of equations derived from
|
| 229 |
+
``expr`` by replacing ``t`` with ``+/- symbol``.
|
| 230 |
+
|
| 231 |
+
Parameters
|
| 232 |
+
==========
|
| 233 |
+
|
| 234 |
+
expr : Expr
|
| 235 |
+
The expression which includes a dummy variable t to be
|
| 236 |
+
replaced with +symbol and -symbol.
|
| 237 |
+
|
| 238 |
+
symbol : Symbol
|
| 239 |
+
The symbol for which a solution is being sought.
|
| 240 |
+
|
| 241 |
+
Returns
|
| 242 |
+
=======
|
| 243 |
+
|
| 244 |
+
List of unique solution of the two equations generated by
|
| 245 |
+
replacing ``t`` with positive and negative ``symbol``.
|
| 246 |
+
|
| 247 |
+
Notes
|
| 248 |
+
=====
|
| 249 |
+
|
| 250 |
+
If ``expr = 2*log(t) + x/2` then solutions for
|
| 251 |
+
``2*log(x) + x/2 = 0`` and ``2*log(-x) + x/2 = 0`` are
|
| 252 |
+
returned by this function. Though this may seem
|
| 253 |
+
counter-intuitive, one must note that the ``expr`` being
|
| 254 |
+
solved here has been derived from a different expression. For
|
| 255 |
+
an expression like ``eq = x**2*g(x) = 1``, if we take the
|
| 256 |
+
log of both sides we obtain ``log(x**2) + log(g(x)) = 0``. If
|
| 257 |
+
x is positive then this simplifies to
|
| 258 |
+
``2*log(x) + log(g(x)) = 0``; the Lambert-solving routines will
|
| 259 |
+
return solutions for this, but we must also consider the
|
| 260 |
+
solutions for ``2*log(-x) + log(g(x))`` since those must also
|
| 261 |
+
be a solution of ``eq`` which has the same value when the ``x``
|
| 262 |
+
in ``x**2`` is negated. If `g(x)` does not have even powers of
|
| 263 |
+
symbol then we do not want to replace the ``x`` there with
|
| 264 |
+
``-x``. So the role of the ``t`` in the expression received by
|
| 265 |
+
this function is to mark where ``+/-x`` should be inserted
|
| 266 |
+
before obtaining the Lambert solutions.
|
| 267 |
+
|
| 268 |
+
"""
|
| 269 |
+
nlhs, plhs = [
|
| 270 |
+
expr.xreplace({t: sgn*symbol}) for sgn in (-1, 1)]
|
| 271 |
+
sols = _solve_lambert(nlhs, symbol, gens)
|
| 272 |
+
if plhs != nlhs:
|
| 273 |
+
sols.extend(_solve_lambert(plhs, symbol, gens))
|
| 274 |
+
# uniq is needed for a case like
|
| 275 |
+
# 2*log(t) - log(-z**2) + log(z + log(x) + log(z))
|
| 276 |
+
# where substituting t with +/-x gives all the same solution;
|
| 277 |
+
# uniq, rather than list(set()), is used to maintain canonical
|
| 278 |
+
# order
|
| 279 |
+
return list(uniq(sols))
|
| 280 |
+
|
| 281 |
+
nrhs, lhs = f.as_independent(symbol, as_Add=True)
|
| 282 |
+
rhs = -nrhs
|
| 283 |
+
|
| 284 |
+
lamcheck = [tmp for tmp in gens
|
| 285 |
+
if (tmp.func in [exp, log] or
|
| 286 |
+
(tmp.is_Pow and symbol in tmp.exp.free_symbols))]
|
| 287 |
+
if not lamcheck:
|
| 288 |
+
raise NotImplementedError()
|
| 289 |
+
|
| 290 |
+
if lhs.is_Add or lhs.is_Mul:
|
| 291 |
+
# replacing all even_degrees of symbol with dummy variable t
|
| 292 |
+
# since these will need special handling; non-Add/Mul do not
|
| 293 |
+
# need this handling
|
| 294 |
+
t = Dummy('t', **symbol.assumptions0)
|
| 295 |
+
lhs = lhs.replace(
|
| 296 |
+
lambda i: # find symbol**even
|
| 297 |
+
i.is_Pow and i.base == symbol and i.exp.is_even,
|
| 298 |
+
lambda i: # replace t**even
|
| 299 |
+
t**i.exp)
|
| 300 |
+
|
| 301 |
+
if lhs.is_Add and lhs.has(t):
|
| 302 |
+
t_indep = lhs.subs(t, 0)
|
| 303 |
+
t_term = lhs - t_indep
|
| 304 |
+
_rhs = rhs - t_indep
|
| 305 |
+
if not t_term.is_Add and _rhs and not (
|
| 306 |
+
t_term.has(S.ComplexInfinity, S.NaN)):
|
| 307 |
+
eq = expand_log(log(t_term) - log(_rhs))
|
| 308 |
+
return _solve_even_degree_expr(eq, t, symbol)
|
| 309 |
+
elif lhs.is_Mul and rhs:
|
| 310 |
+
# this needs to happen whether t is present or not
|
| 311 |
+
lhs = expand_log(log(lhs), force=True)
|
| 312 |
+
rhs = log(rhs)
|
| 313 |
+
if lhs.has(t) and lhs.is_Add:
|
| 314 |
+
# it expanded from Mul to Add
|
| 315 |
+
eq = lhs - rhs
|
| 316 |
+
return _solve_even_degree_expr(eq, t, symbol)
|
| 317 |
+
|
| 318 |
+
# restore symbol in lhs
|
| 319 |
+
lhs = lhs.xreplace({t: symbol})
|
| 320 |
+
|
| 321 |
+
lhs = powsimp(factor(lhs, deep=True))
|
| 322 |
+
|
| 323 |
+
# make sure we have inverted as completely as possible
|
| 324 |
+
r = Dummy()
|
| 325 |
+
i, lhs = _invert(lhs - r, symbol)
|
| 326 |
+
rhs = i.xreplace({r: rhs})
|
| 327 |
+
|
| 328 |
+
# For the first forms:
|
| 329 |
+
#
|
| 330 |
+
# 1a1) B**B = R will arrive here as B*log(B) = log(R)
|
| 331 |
+
# lhs is Mul so take log of both sides:
|
| 332 |
+
# log(B) + log(log(B)) = log(log(R))
|
| 333 |
+
# 1a2) B*(b*log(B) + c)**a = R will arrive unchanged so
|
| 334 |
+
# lhs is Mul, so take log of both sides:
|
| 335 |
+
# log(B) + a*log(b*log(B) + c) = log(R)
|
| 336 |
+
# 1b) d*log(a*B + b) + c*B = R will arrive unchanged so
|
| 337 |
+
# lhs is Add, so isolate c*B and expand log of both sides:
|
| 338 |
+
# log(c) + log(B) = log(R - d*log(a*B + b))
|
| 339 |
+
|
| 340 |
+
soln = []
|
| 341 |
+
if not soln:
|
| 342 |
+
mainlog = _mostfunc(lhs, log, symbol)
|
| 343 |
+
if mainlog:
|
| 344 |
+
if lhs.is_Mul and rhs != 0:
|
| 345 |
+
soln = _lambert(log(lhs) - log(rhs), symbol)
|
| 346 |
+
elif lhs.is_Add:
|
| 347 |
+
other = lhs.subs(mainlog, 0)
|
| 348 |
+
if other and not other.is_Add and [
|
| 349 |
+
tmp for tmp in other.atoms(Pow)
|
| 350 |
+
if symbol in tmp.free_symbols]:
|
| 351 |
+
if not rhs:
|
| 352 |
+
diff = log(other) - log(other - lhs)
|
| 353 |
+
else:
|
| 354 |
+
diff = log(lhs - other) - log(rhs - other)
|
| 355 |
+
soln = _lambert(expand_log(diff), symbol)
|
| 356 |
+
else:
|
| 357 |
+
#it's ready to go
|
| 358 |
+
soln = _lambert(lhs - rhs, symbol)
|
| 359 |
+
|
| 360 |
+
# For the next forms,
|
| 361 |
+
#
|
| 362 |
+
# collect on main exp
|
| 363 |
+
# 2a) (b*B + c)*exp(d*B + g) = R
|
| 364 |
+
# lhs is mul, so take log of both sides:
|
| 365 |
+
# log(b*B + c) + d*B = log(R) - g
|
| 366 |
+
# 2b) g*exp(d*B + h) - b*B = R
|
| 367 |
+
# lhs is add, so add b*B to both sides,
|
| 368 |
+
# take the log of both sides and rearrange to give
|
| 369 |
+
# log(R + b*B) - d*B = log(g) + h
|
| 370 |
+
|
| 371 |
+
if not soln:
|
| 372 |
+
mainexp = _mostfunc(lhs, exp, symbol)
|
| 373 |
+
if mainexp:
|
| 374 |
+
lhs = collect(lhs, mainexp)
|
| 375 |
+
if lhs.is_Mul and rhs != 0:
|
| 376 |
+
soln = _lambert(expand_log(log(lhs) - log(rhs)), symbol)
|
| 377 |
+
elif lhs.is_Add:
|
| 378 |
+
# move all but mainexp-containing term to rhs
|
| 379 |
+
other = lhs.subs(mainexp, 0)
|
| 380 |
+
mainterm = lhs - other
|
| 381 |
+
rhs = rhs - other
|
| 382 |
+
if (mainterm.could_extract_minus_sign() and
|
| 383 |
+
rhs.could_extract_minus_sign()):
|
| 384 |
+
mainterm *= -1
|
| 385 |
+
rhs *= -1
|
| 386 |
+
diff = log(mainterm) - log(rhs)
|
| 387 |
+
soln = _lambert(expand_log(diff), symbol)
|
| 388 |
+
|
| 389 |
+
# For the last form:
|
| 390 |
+
#
|
| 391 |
+
# 3) d*p**(a*B + g) - b*B = c
|
| 392 |
+
# collect on main pow, add b*B to both sides,
|
| 393 |
+
# take log of both sides and rearrange to give
|
| 394 |
+
# a*B*log(p) - log(b*B + c) = -log(d) - g*log(p)
|
| 395 |
+
if not soln:
|
| 396 |
+
mainpow = _mostfunc(lhs, Pow, symbol)
|
| 397 |
+
if mainpow and symbol in mainpow.exp.free_symbols:
|
| 398 |
+
lhs = collect(lhs, mainpow)
|
| 399 |
+
if lhs.is_Mul and rhs != 0:
|
| 400 |
+
# b*B = 0
|
| 401 |
+
soln = _lambert(expand_log(log(lhs) - log(rhs)), symbol)
|
| 402 |
+
elif lhs.is_Add:
|
| 403 |
+
# move all but mainpow-containing term to rhs
|
| 404 |
+
other = lhs.subs(mainpow, 0)
|
| 405 |
+
mainterm = lhs - other
|
| 406 |
+
rhs = rhs - other
|
| 407 |
+
diff = log(mainterm) - log(rhs)
|
| 408 |
+
soln = _lambert(expand_log(diff), symbol)
|
| 409 |
+
|
| 410 |
+
if not soln:
|
| 411 |
+
raise NotImplementedError('%s does not appear to have a solution in '
|
| 412 |
+
'terms of LambertW' % f)
|
| 413 |
+
|
| 414 |
+
return list(ordered(soln))
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
def bivariate_type(f, x, y, *, first=True):
|
| 418 |
+
"""Given an expression, f, 3 tests will be done to see what type
|
| 419 |
+
of composite bivariate it might be, options for u(x, y) are::
|
| 420 |
+
|
| 421 |
+
x*y
|
| 422 |
+
x+y
|
| 423 |
+
x*y+x
|
| 424 |
+
x*y+y
|
| 425 |
+
|
| 426 |
+
If it matches one of these types, ``u(x, y)``, ``P(u)`` and dummy
|
| 427 |
+
variable ``u`` will be returned. Solving ``P(u)`` for ``u`` and
|
| 428 |
+
equating the solutions to ``u(x, y)`` and then solving for ``x`` or
|
| 429 |
+
``y`` is equivalent to solving the original expression for ``x`` or
|
| 430 |
+
``y``. If ``x`` and ``y`` represent two functions in the same
|
| 431 |
+
variable, e.g. ``x = g(t)`` and ``y = h(t)``, then if ``u(x, y) - p``
|
| 432 |
+
can be solved for ``t`` then these represent the solutions to
|
| 433 |
+
``P(u) = 0`` when ``p`` are the solutions of ``P(u) = 0``.
|
| 434 |
+
|
| 435 |
+
Only positive values of ``u`` are considered.
|
| 436 |
+
|
| 437 |
+
Examples
|
| 438 |
+
========
|
| 439 |
+
|
| 440 |
+
>>> from sympy import solve
|
| 441 |
+
>>> from sympy.solvers.bivariate import bivariate_type
|
| 442 |
+
>>> from sympy.abc import x, y
|
| 443 |
+
>>> eq = (x**2 - 3).subs(x, x + y)
|
| 444 |
+
>>> bivariate_type(eq, x, y)
|
| 445 |
+
(x + y, _u**2 - 3, _u)
|
| 446 |
+
>>> uxy, pu, u = _
|
| 447 |
+
>>> usol = solve(pu, u); usol
|
| 448 |
+
[sqrt(3)]
|
| 449 |
+
>>> [solve(uxy - s) for s in solve(pu, u)]
|
| 450 |
+
[[{x: -y + sqrt(3)}]]
|
| 451 |
+
>>> all(eq.subs(s).equals(0) for sol in _ for s in sol)
|
| 452 |
+
True
|
| 453 |
+
|
| 454 |
+
"""
|
| 455 |
+
|
| 456 |
+
u = Dummy('u', positive=True)
|
| 457 |
+
|
| 458 |
+
if first:
|
| 459 |
+
p = Poly(f, x, y)
|
| 460 |
+
f = p.as_expr()
|
| 461 |
+
_x = Dummy()
|
| 462 |
+
_y = Dummy()
|
| 463 |
+
rv = bivariate_type(Poly(f.subs({x: _x, y: _y}), _x, _y), _x, _y, first=False)
|
| 464 |
+
if rv:
|
| 465 |
+
reps = {_x: x, _y: y}
|
| 466 |
+
return rv[0].xreplace(reps), rv[1].xreplace(reps), rv[2]
|
| 467 |
+
return
|
| 468 |
+
|
| 469 |
+
p = f
|
| 470 |
+
f = p.as_expr()
|
| 471 |
+
|
| 472 |
+
# f(x*y)
|
| 473 |
+
args = Add.make_args(p.as_expr())
|
| 474 |
+
new = []
|
| 475 |
+
for a in args:
|
| 476 |
+
a = _mexpand(a.subs(x, u/y))
|
| 477 |
+
free = a.free_symbols
|
| 478 |
+
if x in free or y in free:
|
| 479 |
+
break
|
| 480 |
+
new.append(a)
|
| 481 |
+
else:
|
| 482 |
+
return x*y, Add(*new), u
|
| 483 |
+
|
| 484 |
+
def ok(f, v, c):
|
| 485 |
+
new = _mexpand(f.subs(v, c))
|
| 486 |
+
free = new.free_symbols
|
| 487 |
+
return None if (x in free or y in free) else new
|
| 488 |
+
|
| 489 |
+
# f(a*x + b*y)
|
| 490 |
+
new = []
|
| 491 |
+
d = p.degree(x)
|
| 492 |
+
if p.degree(y) == d:
|
| 493 |
+
a = root(p.coeff_monomial(x**d), d)
|
| 494 |
+
b = root(p.coeff_monomial(y**d), d)
|
| 495 |
+
new = ok(f, x, (u - b*y)/a)
|
| 496 |
+
if new is not None:
|
| 497 |
+
return a*x + b*y, new, u
|
| 498 |
+
|
| 499 |
+
# f(a*x*y + b*y)
|
| 500 |
+
new = []
|
| 501 |
+
d = p.degree(x)
|
| 502 |
+
if p.degree(y) == d:
|
| 503 |
+
for itry in range(2):
|
| 504 |
+
a = root(p.coeff_monomial(x**d*y**d), d)
|
| 505 |
+
b = root(p.coeff_monomial(y**d), d)
|
| 506 |
+
new = ok(f, x, (u - b*y)/a/y)
|
| 507 |
+
if new is not None:
|
| 508 |
+
return a*x*y + b*y, new, u
|
| 509 |
+
x, y = y, x
|
evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/decompogen.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core import (Function, Pow, sympify, Expr)
|
| 2 |
+
from sympy.core.relational import Relational
|
| 3 |
+
from sympy.core.singleton import S
|
| 4 |
+
from sympy.polys import Poly, decompose
|
| 5 |
+
from sympy.utilities.misc import func_name
|
| 6 |
+
from sympy.functions.elementary.miscellaneous import Min, Max
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def decompogen(f, symbol):
|
| 10 |
+
"""
|
| 11 |
+
Computes General functional decomposition of ``f``.
|
| 12 |
+
Given an expression ``f``, returns a list ``[f_1, f_2, ..., f_n]``,
|
| 13 |
+
where::
|
| 14 |
+
f = f_1 o f_2 o ... f_n = f_1(f_2(... f_n))
|
| 15 |
+
|
| 16 |
+
Note: This is a General decomposition function. It also decomposes
|
| 17 |
+
Polynomials. For only Polynomial decomposition see ``decompose`` in polys.
|
| 18 |
+
|
| 19 |
+
Examples
|
| 20 |
+
========
|
| 21 |
+
|
| 22 |
+
>>> from sympy.abc import x
|
| 23 |
+
>>> from sympy import decompogen, sqrt, sin, cos
|
| 24 |
+
>>> decompogen(sin(cos(x)), x)
|
| 25 |
+
[sin(x), cos(x)]
|
| 26 |
+
>>> decompogen(sin(x)**2 + sin(x) + 1, x)
|
| 27 |
+
[x**2 + x + 1, sin(x)]
|
| 28 |
+
>>> decompogen(sqrt(6*x**2 - 5), x)
|
| 29 |
+
[sqrt(x), 6*x**2 - 5]
|
| 30 |
+
>>> decompogen(sin(sqrt(cos(x**2 + 1))), x)
|
| 31 |
+
[sin(x), sqrt(x), cos(x), x**2 + 1]
|
| 32 |
+
>>> decompogen(x**4 + 2*x**3 - x - 1, x)
|
| 33 |
+
[x**2 - x - 1, x**2 + x]
|
| 34 |
+
|
| 35 |
+
"""
|
| 36 |
+
f = sympify(f)
|
| 37 |
+
if not isinstance(f, Expr) or isinstance(f, Relational):
|
| 38 |
+
raise TypeError('expecting Expr but got: `%s`' % func_name(f))
|
| 39 |
+
if symbol not in f.free_symbols:
|
| 40 |
+
return [f]
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
# ===== Simple Functions ===== #
|
| 44 |
+
if isinstance(f, (Function, Pow)):
|
| 45 |
+
if f.is_Pow and f.base == S.Exp1:
|
| 46 |
+
arg = f.exp
|
| 47 |
+
else:
|
| 48 |
+
arg = f.args[0]
|
| 49 |
+
if arg == symbol:
|
| 50 |
+
return [f]
|
| 51 |
+
return [f.subs(arg, symbol)] + decompogen(arg, symbol)
|
| 52 |
+
|
| 53 |
+
# ===== Min/Max Functions ===== #
|
| 54 |
+
if isinstance(f, (Min, Max)):
|
| 55 |
+
args = list(f.args)
|
| 56 |
+
d0 = None
|
| 57 |
+
for i, a in enumerate(args):
|
| 58 |
+
if not a.has_free(symbol):
|
| 59 |
+
continue
|
| 60 |
+
d = decompogen(a, symbol)
|
| 61 |
+
if len(d) == 1:
|
| 62 |
+
d = [symbol] + d
|
| 63 |
+
if d0 is None:
|
| 64 |
+
d0 = d[1:]
|
| 65 |
+
elif d[1:] != d0:
|
| 66 |
+
# decomposition is not the same for each arg:
|
| 67 |
+
# mark as having no decomposition
|
| 68 |
+
d = [symbol]
|
| 69 |
+
break
|
| 70 |
+
args[i] = d[0]
|
| 71 |
+
if d[0] == symbol:
|
| 72 |
+
return [f]
|
| 73 |
+
return [f.func(*args)] + d0
|
| 74 |
+
|
| 75 |
+
# ===== Convert to Polynomial ===== #
|
| 76 |
+
fp = Poly(f)
|
| 77 |
+
gens = list(filter(lambda x: symbol in x.free_symbols, fp.gens))
|
| 78 |
+
|
| 79 |
+
if len(gens) == 1 and gens[0] != symbol:
|
| 80 |
+
f1 = f.subs(gens[0], symbol)
|
| 81 |
+
f2 = gens[0]
|
| 82 |
+
return [f1] + decompogen(f2, symbol)
|
| 83 |
+
|
| 84 |
+
# ===== Polynomial decompose() ====== #
|
| 85 |
+
try:
|
| 86 |
+
return decompose(f)
|
| 87 |
+
except ValueError:
|
| 88 |
+
return [f]
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def compogen(g_s, symbol):
|
| 92 |
+
"""
|
| 93 |
+
Returns the composition of functions.
|
| 94 |
+
Given a list of functions ``g_s``, returns their composition ``f``,
|
| 95 |
+
where:
|
| 96 |
+
f = g_1 o g_2 o .. o g_n
|
| 97 |
+
|
| 98 |
+
Note: This is a General composition function. It also composes Polynomials.
|
| 99 |
+
For only Polynomial composition see ``compose`` in polys.
|
| 100 |
+
|
| 101 |
+
Examples
|
| 102 |
+
========
|
| 103 |
+
|
| 104 |
+
>>> from sympy.solvers.decompogen import compogen
|
| 105 |
+
>>> from sympy.abc import x
|
| 106 |
+
>>> from sympy import sqrt, sin, cos
|
| 107 |
+
>>> compogen([sin(x), cos(x)], x)
|
| 108 |
+
sin(cos(x))
|
| 109 |
+
>>> compogen([x**2 + x + 1, sin(x)], x)
|
| 110 |
+
sin(x)**2 + sin(x) + 1
|
| 111 |
+
>>> compogen([sqrt(x), 6*x**2 - 5], x)
|
| 112 |
+
sqrt(6*x**2 - 5)
|
| 113 |
+
>>> compogen([sin(x), sqrt(x), cos(x), x**2 + 1], x)
|
| 114 |
+
sin(sqrt(cos(x**2 + 1)))
|
| 115 |
+
>>> compogen([x**2 - x - 1, x**2 + x], x)
|
| 116 |
+
-x**2 - x + (x**2 + x)**2 - 1
|
| 117 |
+
"""
|
| 118 |
+
if len(g_s) == 1:
|
| 119 |
+
return g_s[0]
|
| 120 |
+
|
| 121 |
+
foo = g_s[0].subs(symbol, g_s[1])
|
| 122 |
+
|
| 123 |
+
if len(g_s) == 2:
|
| 124 |
+
return foo
|
| 125 |
+
|
| 126 |
+
return compogen([foo] + g_s[2:], symbol)
|
evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/deutils.py
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Utility functions for classifying and solving
|
| 2 |
+
ordinary and partial differential equations.
|
| 3 |
+
|
| 4 |
+
Contains
|
| 5 |
+
========
|
| 6 |
+
_preprocess
|
| 7 |
+
ode_order
|
| 8 |
+
_desolve
|
| 9 |
+
|
| 10 |
+
"""
|
| 11 |
+
from sympy.core import Pow
|
| 12 |
+
from sympy.core.function import Derivative, AppliedUndef
|
| 13 |
+
from sympy.core.relational import Equality
|
| 14 |
+
from sympy.core.symbol import Wild
|
| 15 |
+
|
| 16 |
+
def _preprocess(expr, func=None, hint='_Integral'):
|
| 17 |
+
"""Prepare expr for solving by making sure that differentiation
|
| 18 |
+
is done so that only func remains in unevaluated derivatives and
|
| 19 |
+
(if hint does not end with _Integral) that doit is applied to all
|
| 20 |
+
other derivatives. If hint is None, do not do any differentiation.
|
| 21 |
+
(Currently this may cause some simple differential equations to
|
| 22 |
+
fail.)
|
| 23 |
+
|
| 24 |
+
In case func is None, an attempt will be made to autodetect the
|
| 25 |
+
function to be solved for.
|
| 26 |
+
|
| 27 |
+
>>> from sympy.solvers.deutils import _preprocess
|
| 28 |
+
>>> from sympy import Derivative, Function
|
| 29 |
+
>>> from sympy.abc import x, y, z
|
| 30 |
+
>>> f, g = map(Function, 'fg')
|
| 31 |
+
|
| 32 |
+
If f(x)**p == 0 and p>0 then we can solve for f(x)=0
|
| 33 |
+
>>> _preprocess((f(x).diff(x)-4)**5, f(x))
|
| 34 |
+
(Derivative(f(x), x) - 4, f(x))
|
| 35 |
+
|
| 36 |
+
Apply doit to derivatives that contain more than the function
|
| 37 |
+
of interest:
|
| 38 |
+
|
| 39 |
+
>>> _preprocess(Derivative(f(x) + x, x))
|
| 40 |
+
(Derivative(f(x), x) + 1, f(x))
|
| 41 |
+
|
| 42 |
+
Do others if the differentiation variable(s) intersect with those
|
| 43 |
+
of the function of interest or contain the function of interest:
|
| 44 |
+
|
| 45 |
+
>>> _preprocess(Derivative(g(x), y, z), f(y))
|
| 46 |
+
(0, f(y))
|
| 47 |
+
>>> _preprocess(Derivative(f(y), z), f(y))
|
| 48 |
+
(0, f(y))
|
| 49 |
+
|
| 50 |
+
Do others if the hint does not end in '_Integral' (the default
|
| 51 |
+
assumes that it does):
|
| 52 |
+
|
| 53 |
+
>>> _preprocess(Derivative(g(x), y), f(x))
|
| 54 |
+
(Derivative(g(x), y), f(x))
|
| 55 |
+
>>> _preprocess(Derivative(f(x), y), f(x), hint='')
|
| 56 |
+
(0, f(x))
|
| 57 |
+
|
| 58 |
+
Do not do any derivatives if hint is None:
|
| 59 |
+
|
| 60 |
+
>>> eq = Derivative(f(x) + 1, x) + Derivative(f(x), y)
|
| 61 |
+
>>> _preprocess(eq, f(x), hint=None)
|
| 62 |
+
(Derivative(f(x) + 1, x) + Derivative(f(x), y), f(x))
|
| 63 |
+
|
| 64 |
+
If it's not clear what the function of interest is, it must be given:
|
| 65 |
+
|
| 66 |
+
>>> eq = Derivative(f(x) + g(x), x)
|
| 67 |
+
>>> _preprocess(eq, g(x))
|
| 68 |
+
(Derivative(f(x), x) + Derivative(g(x), x), g(x))
|
| 69 |
+
>>> try: _preprocess(eq)
|
| 70 |
+
... except ValueError: print("A ValueError was raised.")
|
| 71 |
+
A ValueError was raised.
|
| 72 |
+
|
| 73 |
+
"""
|
| 74 |
+
if isinstance(expr, Pow):
|
| 75 |
+
# if f(x)**p=0 then f(x)=0 (p>0)
|
| 76 |
+
if (expr.exp).is_positive:
|
| 77 |
+
expr = expr.base
|
| 78 |
+
derivs = expr.atoms(Derivative)
|
| 79 |
+
if not func:
|
| 80 |
+
funcs = set().union(*[d.atoms(AppliedUndef) for d in derivs])
|
| 81 |
+
if len(funcs) != 1:
|
| 82 |
+
raise ValueError('The function cannot be '
|
| 83 |
+
'automatically detected for %s.' % expr)
|
| 84 |
+
func = funcs.pop()
|
| 85 |
+
fvars = set(func.args)
|
| 86 |
+
if hint is None:
|
| 87 |
+
return expr, func
|
| 88 |
+
reps = [(d, d.doit()) for d in derivs if not hint.endswith('_Integral') or
|
| 89 |
+
d.has(func) or set(d.variables) & fvars]
|
| 90 |
+
eq = expr.subs(reps)
|
| 91 |
+
return eq, func
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def ode_order(expr, func):
|
| 95 |
+
"""
|
| 96 |
+
Returns the order of a given differential
|
| 97 |
+
equation with respect to func.
|
| 98 |
+
|
| 99 |
+
This function is implemented recursively.
|
| 100 |
+
|
| 101 |
+
Examples
|
| 102 |
+
========
|
| 103 |
+
|
| 104 |
+
>>> from sympy import Function
|
| 105 |
+
>>> from sympy.solvers.deutils import ode_order
|
| 106 |
+
>>> from sympy.abc import x
|
| 107 |
+
>>> f, g = map(Function, ['f', 'g'])
|
| 108 |
+
>>> ode_order(f(x).diff(x, 2) + f(x).diff(x)**2 +
|
| 109 |
+
... f(x).diff(x), f(x))
|
| 110 |
+
2
|
| 111 |
+
>>> ode_order(f(x).diff(x, 2) + g(x).diff(x, 3), f(x))
|
| 112 |
+
2
|
| 113 |
+
>>> ode_order(f(x).diff(x, 2) + g(x).diff(x, 3), g(x))
|
| 114 |
+
3
|
| 115 |
+
|
| 116 |
+
"""
|
| 117 |
+
a = Wild('a', exclude=[func])
|
| 118 |
+
if expr.match(a):
|
| 119 |
+
return 0
|
| 120 |
+
|
| 121 |
+
if isinstance(expr, Derivative):
|
| 122 |
+
if expr.args[0] == func:
|
| 123 |
+
return len(expr.variables)
|
| 124 |
+
else:
|
| 125 |
+
args = expr.args[0].args
|
| 126 |
+
rv = len(expr.variables)
|
| 127 |
+
if args:
|
| 128 |
+
rv += max(ode_order(_, func) for _ in args)
|
| 129 |
+
return rv
|
| 130 |
+
else:
|
| 131 |
+
return max(ode_order(_, func) for _ in expr.args) if expr.args else 0
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def _desolve(eq, func=None, hint="default", ics=None, simplify=True, *, prep=True, **kwargs):
|
| 135 |
+
"""This is a helper function to dsolve and pdsolve in the ode
|
| 136 |
+
and pde modules.
|
| 137 |
+
|
| 138 |
+
If the hint provided to the function is "default", then a dict with
|
| 139 |
+
the following keys are returned
|
| 140 |
+
|
| 141 |
+
'func' - It provides the function for which the differential equation
|
| 142 |
+
has to be solved. This is useful when the expression has
|
| 143 |
+
more than one function in it.
|
| 144 |
+
|
| 145 |
+
'default' - The default key as returned by classifier functions in ode
|
| 146 |
+
and pde.py
|
| 147 |
+
|
| 148 |
+
'hint' - The hint given by the user for which the differential equation
|
| 149 |
+
is to be solved. If the hint given by the user is 'default',
|
| 150 |
+
then the value of 'hint' and 'default' is the same.
|
| 151 |
+
|
| 152 |
+
'order' - The order of the function as returned by ode_order
|
| 153 |
+
|
| 154 |
+
'match' - It returns the match as given by the classifier functions, for
|
| 155 |
+
the default hint.
|
| 156 |
+
|
| 157 |
+
If the hint provided to the function is not "default" and is not in
|
| 158 |
+
('all', 'all_Integral', 'best'), then a dict with the above mentioned keys
|
| 159 |
+
is returned along with the keys which are returned when dict in
|
| 160 |
+
classify_ode or classify_pde is set True
|
| 161 |
+
|
| 162 |
+
If the hint given is in ('all', 'all_Integral', 'best'), then this function
|
| 163 |
+
returns a nested dict, with the keys, being the set of classified hints
|
| 164 |
+
returned by classifier functions, and the values being the dict of form
|
| 165 |
+
as mentioned above.
|
| 166 |
+
|
| 167 |
+
Key 'eq' is a common key to all the above mentioned hints which returns an
|
| 168 |
+
expression if eq given by user is an Equality.
|
| 169 |
+
|
| 170 |
+
See Also
|
| 171 |
+
========
|
| 172 |
+
classify_ode(ode.py)
|
| 173 |
+
classify_pde(pde.py)
|
| 174 |
+
"""
|
| 175 |
+
if isinstance(eq, Equality):
|
| 176 |
+
eq = eq.lhs - eq.rhs
|
| 177 |
+
|
| 178 |
+
# preprocess the equation and find func if not given
|
| 179 |
+
if prep or func is None:
|
| 180 |
+
eq, func = _preprocess(eq, func)
|
| 181 |
+
prep = False
|
| 182 |
+
|
| 183 |
+
# type is an argument passed by the solve functions in ode and pde.py
|
| 184 |
+
# that identifies whether the function caller is an ordinary
|
| 185 |
+
# or partial differential equation. Accordingly corresponding
|
| 186 |
+
# changes are made in the function.
|
| 187 |
+
type = kwargs.get('type', None)
|
| 188 |
+
xi = kwargs.get('xi')
|
| 189 |
+
eta = kwargs.get('eta')
|
| 190 |
+
x0 = kwargs.get('x0', 0)
|
| 191 |
+
terms = kwargs.get('n')
|
| 192 |
+
|
| 193 |
+
if type == 'ode':
|
| 194 |
+
from sympy.solvers.ode import classify_ode, allhints
|
| 195 |
+
classifier = classify_ode
|
| 196 |
+
string = 'ODE '
|
| 197 |
+
dummy = ''
|
| 198 |
+
|
| 199 |
+
elif type == 'pde':
|
| 200 |
+
from sympy.solvers.pde import classify_pde, allhints
|
| 201 |
+
classifier = classify_pde
|
| 202 |
+
string = 'PDE '
|
| 203 |
+
dummy = 'p'
|
| 204 |
+
|
| 205 |
+
# Magic that should only be used internally. Prevents classify_ode from
|
| 206 |
+
# being called more than it needs to be by passing its results through
|
| 207 |
+
# recursive calls.
|
| 208 |
+
if kwargs.get('classify', True):
|
| 209 |
+
hints = classifier(eq, func, dict=True, ics=ics, xi=xi, eta=eta,
|
| 210 |
+
n=terms, x0=x0, hint=hint, prep=prep)
|
| 211 |
+
|
| 212 |
+
else:
|
| 213 |
+
# Here is what all this means:
|
| 214 |
+
#
|
| 215 |
+
# hint: The hint method given to _desolve() by the user.
|
| 216 |
+
# hints: The dictionary of hints that match the DE, along with other
|
| 217 |
+
# information (including the internal pass-through magic).
|
| 218 |
+
# default: The default hint to return, the first hint from allhints
|
| 219 |
+
# that matches the hint; obtained from classify_ode().
|
| 220 |
+
# match: Dictionary containing the match dictionary for each hint
|
| 221 |
+
# (the parts of the DE for solving). When going through the
|
| 222 |
+
# hints in "all", this holds the match string for the current
|
| 223 |
+
# hint.
|
| 224 |
+
# order: The order of the DE, as determined by ode_order().
|
| 225 |
+
hints = kwargs.get('hint',
|
| 226 |
+
{'default': hint,
|
| 227 |
+
hint: kwargs['match'],
|
| 228 |
+
'order': kwargs['order']})
|
| 229 |
+
if not hints['default']:
|
| 230 |
+
# classify_ode will set hints['default'] to None if no hints match.
|
| 231 |
+
if hint not in allhints and hint != 'default':
|
| 232 |
+
raise ValueError("Hint not recognized: " + hint)
|
| 233 |
+
elif hint not in hints['ordered_hints'] and hint != 'default':
|
| 234 |
+
raise ValueError(string + str(eq) + " does not match hint " + hint)
|
| 235 |
+
# If dsolve can't solve the purely algebraic equation then dsolve will raise
|
| 236 |
+
# ValueError
|
| 237 |
+
elif hints['order'] == 0:
|
| 238 |
+
raise ValueError(
|
| 239 |
+
str(eq) + " is not a solvable differential equation in " + str(func))
|
| 240 |
+
else:
|
| 241 |
+
raise NotImplementedError(dummy + "solve" + ": Cannot solve " + str(eq))
|
| 242 |
+
if hint == 'default':
|
| 243 |
+
return _desolve(eq, func, ics=ics, hint=hints['default'], simplify=simplify,
|
| 244 |
+
prep=prep, x0=x0, classify=False, order=hints['order'],
|
| 245 |
+
match=hints[hints['default']], xi=xi, eta=eta, n=terms, type=type)
|
| 246 |
+
elif hint in ('all', 'all_Integral', 'best'):
|
| 247 |
+
retdict = {}
|
| 248 |
+
gethints = set(hints) - {'order', 'default', 'ordered_hints'}
|
| 249 |
+
if hint == 'all_Integral':
|
| 250 |
+
for i in hints:
|
| 251 |
+
if i.endswith('_Integral'):
|
| 252 |
+
gethints.remove(i[:-len('_Integral')])
|
| 253 |
+
# special cases
|
| 254 |
+
for k in ["1st_homogeneous_coeff_best", "1st_power_series",
|
| 255 |
+
"lie_group", "2nd_power_series_ordinary", "2nd_power_series_regular"]:
|
| 256 |
+
if k in gethints:
|
| 257 |
+
gethints.remove(k)
|
| 258 |
+
for i in gethints:
|
| 259 |
+
sol = _desolve(eq, func, ics=ics, hint=i, x0=x0, simplify=simplify, prep=prep,
|
| 260 |
+
classify=False, n=terms, order=hints['order'], match=hints[i], type=type)
|
| 261 |
+
retdict[i] = sol
|
| 262 |
+
retdict['all'] = True
|
| 263 |
+
retdict['eq'] = eq
|
| 264 |
+
return retdict
|
| 265 |
+
elif hint not in allhints: # and hint not in ('default', 'ordered_hints'):
|
| 266 |
+
raise ValueError("Hint not recognized: " + hint)
|
| 267 |
+
elif hint not in hints:
|
| 268 |
+
raise ValueError(string + str(eq) + " does not match hint " + hint)
|
| 269 |
+
else:
|
| 270 |
+
# Key added to identify the hint needed to solve the equation
|
| 271 |
+
hints['hint'] = hint
|
| 272 |
+
hints.update({'func': func, 'eq': eq})
|
| 273 |
+
return hints
|
evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/diophantine/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .diophantine import diophantine, classify_diop, diop_solve
|
| 2 |
+
|
| 3 |
+
__all__ = [
|
| 4 |
+
'diophantine', 'classify_diop', 'diop_solve'
|
| 5 |
+
]
|
evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/diophantine/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (285 Bytes). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/diophantine/diophantine.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/diophantine/tests/__init__.py
ADDED
|
File without changes
|
evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/diophantine/tests/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (193 Bytes). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/diophantine/tests/__pycache__/test_diophantine.cpython-310.pyc
ADDED
|
Binary file (46.5 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/diophantine/tests/test_diophantine.py
ADDED
|
@@ -0,0 +1,1051 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.add import Add
|
| 2 |
+
from sympy.core.mul import Mul
|
| 3 |
+
from sympy.core.numbers import (Rational, oo, pi)
|
| 4 |
+
from sympy.core.relational import Eq
|
| 5 |
+
from sympy.core.singleton import S
|
| 6 |
+
from sympy.core.symbol import symbols
|
| 7 |
+
from sympy.matrices.dense import Matrix
|
| 8 |
+
from sympy.ntheory.factor_ import factorint
|
| 9 |
+
from sympy.simplify.powsimp import powsimp
|
| 10 |
+
from sympy.core.function import _mexpand
|
| 11 |
+
from sympy.core.sorting import default_sort_key, ordered
|
| 12 |
+
from sympy.functions.elementary.trigonometric import sin
|
| 13 |
+
from sympy.solvers.diophantine import diophantine
|
| 14 |
+
from sympy.solvers.diophantine.diophantine import (diop_DN,
|
| 15 |
+
diop_solve, diop_ternary_quadratic_normal,
|
| 16 |
+
diop_general_pythagorean, diop_ternary_quadratic, diop_linear,
|
| 17 |
+
diop_quadratic, diop_general_sum_of_squares, diop_general_sum_of_even_powers,
|
| 18 |
+
descent, diop_bf_DN, divisible, equivalent, find_DN, ldescent, length,
|
| 19 |
+
reconstruct, partition, power_representation,
|
| 20 |
+
prime_as_sum_of_two_squares, square_factor, sum_of_four_squares,
|
| 21 |
+
sum_of_three_squares, transformation_to_DN, transformation_to_normal,
|
| 22 |
+
classify_diop, base_solution_linear, cornacchia, sqf_normal, gaussian_reduce, holzer,
|
| 23 |
+
check_param, parametrize_ternary_quadratic, sum_of_powers, sum_of_squares,
|
| 24 |
+
_diop_ternary_quadratic_normal, _nint_or_floor,
|
| 25 |
+
_odd, _even, _remove_gcd, _can_do_sum_of_squares, DiophantineSolutionSet, GeneralPythagorean,
|
| 26 |
+
BinaryQuadratic)
|
| 27 |
+
|
| 28 |
+
from sympy.testing.pytest import slow, raises, XFAIL
|
| 29 |
+
from sympy.utilities.iterables import (
|
| 30 |
+
signed_permutations)
|
| 31 |
+
|
| 32 |
+
a, b, c, d, p, q, x, y, z, w, t, u, v, X, Y, Z = symbols(
|
| 33 |
+
"a, b, c, d, p, q, x, y, z, w, t, u, v, X, Y, Z", integer=True)
|
| 34 |
+
t_0, t_1, t_2, t_3, t_4, t_5, t_6 = symbols("t_:7", integer=True)
|
| 35 |
+
m1, m2, m3 = symbols('m1:4', integer=True)
|
| 36 |
+
n1 = symbols('n1', integer=True)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def diop_simplify(eq):
|
| 40 |
+
return _mexpand(powsimp(_mexpand(eq)))
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def test_input_format():
|
| 44 |
+
raises(TypeError, lambda: diophantine(sin(x)))
|
| 45 |
+
raises(TypeError, lambda: diophantine(x/pi - 3))
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def test_nosols():
|
| 49 |
+
# diophantine should sympify eq so that these are equivalent
|
| 50 |
+
assert diophantine(3) == set()
|
| 51 |
+
assert diophantine(S(3)) == set()
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def test_univariate():
|
| 55 |
+
assert diop_solve((x - 1)*(x - 2)**2) == {(1,), (2,)}
|
| 56 |
+
assert diop_solve((x - 1)*(x - 2)) == {(1,), (2,)}
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def test_classify_diop():
|
| 60 |
+
raises(TypeError, lambda: classify_diop(x**2/3 - 1))
|
| 61 |
+
raises(ValueError, lambda: classify_diop(1))
|
| 62 |
+
raises(NotImplementedError, lambda: classify_diop(w*x*y*z - 1))
|
| 63 |
+
raises(NotImplementedError, lambda: classify_diop(x**3 + y**3 + z**4 - 90))
|
| 64 |
+
assert classify_diop(14*x**2 + 15*x - 42) == (
|
| 65 |
+
[x], {1: -42, x: 15, x**2: 14}, 'univariate')
|
| 66 |
+
assert classify_diop(x*y + z) == (
|
| 67 |
+
[x, y, z], {x*y: 1, z: 1}, 'inhomogeneous_ternary_quadratic')
|
| 68 |
+
assert classify_diop(x*y + z + w + x**2) == (
|
| 69 |
+
[w, x, y, z], {x*y: 1, w: 1, x**2: 1, z: 1}, 'inhomogeneous_general_quadratic')
|
| 70 |
+
assert classify_diop(x*y + x*z + x**2 + 1) == (
|
| 71 |
+
[x, y, z], {x*y: 1, x*z: 1, x**2: 1, 1: 1}, 'inhomogeneous_general_quadratic')
|
| 72 |
+
assert classify_diop(x*y + z + w + 42) == (
|
| 73 |
+
[w, x, y, z], {x*y: 1, w: 1, 1: 42, z: 1}, 'inhomogeneous_general_quadratic')
|
| 74 |
+
assert classify_diop(x*y + z*w) == (
|
| 75 |
+
[w, x, y, z], {x*y: 1, w*z: 1}, 'homogeneous_general_quadratic')
|
| 76 |
+
assert classify_diop(x*y**2 + 1) == (
|
| 77 |
+
[x, y], {x*y**2: 1, 1: 1}, 'cubic_thue')
|
| 78 |
+
assert classify_diop(x**4 + y**4 + z**4 - (1 + 16 + 81)) == (
|
| 79 |
+
[x, y, z], {1: -98, x**4: 1, z**4: 1, y**4: 1}, 'general_sum_of_even_powers')
|
| 80 |
+
assert classify_diop(x**2 + y**2 + z**2) == (
|
| 81 |
+
[x, y, z], {x**2: 1, y**2: 1, z**2: 1}, 'homogeneous_ternary_quadratic_normal')
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def test_linear():
|
| 85 |
+
assert diop_solve(x) == (0,)
|
| 86 |
+
assert diop_solve(1*x) == (0,)
|
| 87 |
+
assert diop_solve(3*x) == (0,)
|
| 88 |
+
assert diop_solve(x + 1) == (-1,)
|
| 89 |
+
assert diop_solve(2*x + 1) == (None,)
|
| 90 |
+
assert diop_solve(2*x + 4) == (-2,)
|
| 91 |
+
assert diop_solve(y + x) == (t_0, -t_0)
|
| 92 |
+
assert diop_solve(y + x + 0) == (t_0, -t_0)
|
| 93 |
+
assert diop_solve(y + x - 0) == (t_0, -t_0)
|
| 94 |
+
assert diop_solve(0*x - y - 5) == (-5,)
|
| 95 |
+
assert diop_solve(3*y + 2*x - 5) == (3*t_0 - 5, -2*t_0 + 5)
|
| 96 |
+
assert diop_solve(2*x - 3*y - 5) == (3*t_0 - 5, 2*t_0 - 5)
|
| 97 |
+
assert diop_solve(-2*x - 3*y - 5) == (3*t_0 + 5, -2*t_0 - 5)
|
| 98 |
+
assert diop_solve(7*x + 5*y) == (5*t_0, -7*t_0)
|
| 99 |
+
assert diop_solve(2*x + 4*y) == (-2*t_0, t_0)
|
| 100 |
+
assert diop_solve(4*x + 6*y - 4) == (3*t_0 - 2, -2*t_0 + 2)
|
| 101 |
+
assert diop_solve(4*x + 6*y - 3) == (None, None)
|
| 102 |
+
assert diop_solve(0*x + 3*y - 4*z + 5) == (4*t_0 + 5, 3*t_0 + 5)
|
| 103 |
+
assert diop_solve(4*x + 3*y - 4*z + 5) == (t_0, 8*t_0 + 4*t_1 + 5, 7*t_0 + 3*t_1 + 5)
|
| 104 |
+
assert diop_solve(4*x + 3*y - 4*z + 5, None) == (0, 5, 5)
|
| 105 |
+
assert diop_solve(4*x + 2*y + 8*z - 5) == (None, None, None)
|
| 106 |
+
assert diop_solve(5*x + 7*y - 2*z - 6) == (t_0, -3*t_0 + 2*t_1 + 6, -8*t_0 + 7*t_1 + 18)
|
| 107 |
+
assert diop_solve(3*x - 6*y + 12*z - 9) == (2*t_0 + 3, t_0 + 2*t_1, t_1)
|
| 108 |
+
assert diop_solve(6*w + 9*x + 20*y - z) == (t_0, t_1, t_1 + t_2, 6*t_0 + 29*t_1 + 20*t_2)
|
| 109 |
+
|
| 110 |
+
# to ignore constant factors, use diophantine
|
| 111 |
+
raises(TypeError, lambda: diop_solve(x/2))
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def test_quadratic_simple_hyperbolic_case():
|
| 115 |
+
# Simple Hyperbolic case: A = C = 0 and B != 0
|
| 116 |
+
assert diop_solve(3*x*y + 34*x - 12*y + 1) == \
|
| 117 |
+
{(-133, -11), (5, -57)}
|
| 118 |
+
assert diop_solve(6*x*y + 2*x + 3*y + 1) == set()
|
| 119 |
+
assert diop_solve(-13*x*y + 2*x - 4*y - 54) == {(27, 0)}
|
| 120 |
+
assert diop_solve(-27*x*y - 30*x - 12*y - 54) == {(-14, -1)}
|
| 121 |
+
assert diop_solve(2*x*y + 5*x + 56*y + 7) == {(-161, -3), (-47, -6), (-35, -12),
|
| 122 |
+
(-29, -69), (-27, 64), (-21, 7),
|
| 123 |
+
(-9, 1), (105, -2)}
|
| 124 |
+
assert diop_solve(6*x*y + 9*x + 2*y + 3) == set()
|
| 125 |
+
assert diop_solve(x*y + x + y + 1) == {(-1, t), (t, -1)}
|
| 126 |
+
assert diophantine(48*x*y)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def test_quadratic_elliptical_case():
|
| 130 |
+
# Elliptical case: B**2 - 4AC < 0
|
| 131 |
+
|
| 132 |
+
assert diop_solve(42*x**2 + 8*x*y + 15*y**2 + 23*x + 17*y - 4915) == {(-11, -1)}
|
| 133 |
+
assert diop_solve(4*x**2 + 3*y**2 + 5*x - 11*y + 12) == set()
|
| 134 |
+
assert diop_solve(x**2 + y**2 + 2*x + 2*y + 2) == {(-1, -1)}
|
| 135 |
+
assert diop_solve(15*x**2 - 9*x*y + 14*y**2 - 23*x - 14*y - 4950) == {(-15, 6)}
|
| 136 |
+
assert diop_solve(10*x**2 + 12*x*y + 12*y**2 - 34) == \
|
| 137 |
+
{(-1, -1), (-1, 2), (1, -2), (1, 1)}
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def test_quadratic_parabolic_case():
|
| 141 |
+
# Parabolic case: B**2 - 4AC = 0
|
| 142 |
+
assert check_solutions(8*x**2 - 24*x*y + 18*y**2 + 5*x + 7*y + 16)
|
| 143 |
+
assert check_solutions(8*x**2 - 24*x*y + 18*y**2 + 6*x + 12*y - 6)
|
| 144 |
+
assert check_solutions(8*x**2 + 24*x*y + 18*y**2 + 4*x + 6*y - 7)
|
| 145 |
+
assert check_solutions(-4*x**2 + 4*x*y - y**2 + 2*x - 3)
|
| 146 |
+
assert check_solutions(x**2 + 2*x*y + y**2 + 2*x + 2*y + 1)
|
| 147 |
+
assert check_solutions(x**2 - 2*x*y + y**2 + 2*x + 2*y + 1)
|
| 148 |
+
assert check_solutions(y**2 - 41*x + 40)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def test_quadratic_perfect_square():
|
| 152 |
+
# B**2 - 4*A*C > 0
|
| 153 |
+
# B**2 - 4*A*C is a perfect square
|
| 154 |
+
assert check_solutions(48*x*y)
|
| 155 |
+
assert check_solutions(4*x**2 - 5*x*y + y**2 + 2)
|
| 156 |
+
assert check_solutions(-2*x**2 - 3*x*y + 2*y**2 -2*x - 17*y + 25)
|
| 157 |
+
assert check_solutions(12*x**2 + 13*x*y + 3*y**2 - 2*x + 3*y - 12)
|
| 158 |
+
assert check_solutions(8*x**2 + 10*x*y + 2*y**2 - 32*x - 13*y - 23)
|
| 159 |
+
assert check_solutions(4*x**2 - 4*x*y - 3*y- 8*x - 3)
|
| 160 |
+
assert check_solutions(- 4*x*y - 4*y**2 - 3*y- 5*x - 10)
|
| 161 |
+
assert check_solutions(x**2 - y**2 - 2*x - 2*y)
|
| 162 |
+
assert check_solutions(x**2 - 9*y**2 - 2*x - 6*y)
|
| 163 |
+
assert check_solutions(4*x**2 - 9*y**2 - 4*x - 12*y - 3)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def test_quadratic_non_perfect_square():
|
| 167 |
+
# B**2 - 4*A*C is not a perfect square
|
| 168 |
+
# Used check_solutions() since the solutions are complex expressions involving
|
| 169 |
+
# square roots and exponents
|
| 170 |
+
assert check_solutions(x**2 - 2*x - 5*y**2)
|
| 171 |
+
assert check_solutions(3*x**2 - 2*y**2 - 2*x - 2*y)
|
| 172 |
+
assert check_solutions(x**2 - x*y - y**2 - 3*y)
|
| 173 |
+
assert check_solutions(x**2 - 9*y**2 - 2*x - 6*y)
|
| 174 |
+
assert BinaryQuadratic(x**2 + y**2 + 2*x + 2*y + 2).solve() == {(-1, -1)}
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def test_issue_9106():
|
| 178 |
+
eq = -48 - 2*x*(3*x - 1) + y*(3*y - 1)
|
| 179 |
+
v = (x, y)
|
| 180 |
+
for sol in diophantine(eq):
|
| 181 |
+
assert not diop_simplify(eq.xreplace(dict(zip(v, sol))))
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def test_issue_18138():
|
| 185 |
+
eq = x**2 - x - y**2
|
| 186 |
+
v = (x, y)
|
| 187 |
+
for sol in diophantine(eq):
|
| 188 |
+
assert not diop_simplify(eq.xreplace(dict(zip(v, sol))))
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
@slow
|
| 192 |
+
def test_quadratic_non_perfect_slow():
|
| 193 |
+
assert check_solutions(8*x**2 + 10*x*y - 2*y**2 - 32*x - 13*y - 23)
|
| 194 |
+
# This leads to very large numbers.
|
| 195 |
+
# assert check_solutions(5*x**2 - 13*x*y + y**2 - 4*x - 4*y - 15)
|
| 196 |
+
assert check_solutions(-3*x**2 - 2*x*y + 7*y**2 - 5*x - 7)
|
| 197 |
+
assert check_solutions(-4 - x + 4*x**2 - y - 3*x*y - 4*y**2)
|
| 198 |
+
assert check_solutions(1 + 2*x + 2*x**2 + 2*y + x*y - 2*y**2)
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def test_DN():
|
| 202 |
+
# Most of the test cases were adapted from,
|
| 203 |
+
# Solving the generalized Pell equation x**2 - D*y**2 = N, John P. Robertson, July 31, 2004.
|
| 204 |
+
# https://web.archive.org/web/20160323033128/http://www.jpr2718.org/pell.pdf
|
| 205 |
+
# others are verified using Wolfram Alpha.
|
| 206 |
+
|
| 207 |
+
# Covers cases where D <= 0 or D > 0 and D is a square or N = 0
|
| 208 |
+
# Solutions are straightforward in these cases.
|
| 209 |
+
assert diop_DN(3, 0) == [(0, 0)]
|
| 210 |
+
assert diop_DN(-17, -5) == []
|
| 211 |
+
assert diop_DN(-19, 23) == [(2, 1)]
|
| 212 |
+
assert diop_DN(-13, 17) == [(2, 1)]
|
| 213 |
+
assert diop_DN(-15, 13) == []
|
| 214 |
+
assert diop_DN(0, 5) == []
|
| 215 |
+
assert diop_DN(0, 9) == [(3, t)]
|
| 216 |
+
assert diop_DN(9, 0) == [(3*t, t)]
|
| 217 |
+
assert diop_DN(16, 24) == []
|
| 218 |
+
assert diop_DN(9, 180) == [(18, 4)]
|
| 219 |
+
assert diop_DN(9, -180) == [(12, 6)]
|
| 220 |
+
assert diop_DN(7, 0) == [(0, 0)]
|
| 221 |
+
|
| 222 |
+
# When equation is x**2 + y**2 = N
|
| 223 |
+
# Solutions are interchangeable
|
| 224 |
+
assert diop_DN(-1, 5) == [(2, 1), (1, 2)]
|
| 225 |
+
assert diop_DN(-1, 169) == [(12, 5), (5, 12), (13, 0), (0, 13)]
|
| 226 |
+
|
| 227 |
+
# D > 0 and D is not a square
|
| 228 |
+
|
| 229 |
+
# N = 1
|
| 230 |
+
assert diop_DN(13, 1) == [(649, 180)]
|
| 231 |
+
assert diop_DN(980, 1) == [(51841, 1656)]
|
| 232 |
+
assert diop_DN(981, 1) == [(158070671986249, 5046808151700)]
|
| 233 |
+
assert diop_DN(986, 1) == [(49299, 1570)]
|
| 234 |
+
assert diop_DN(991, 1) == [(379516400906811930638014896080, 12055735790331359447442538767)]
|
| 235 |
+
assert diop_DN(17, 1) == [(33, 8)]
|
| 236 |
+
assert diop_DN(19, 1) == [(170, 39)]
|
| 237 |
+
|
| 238 |
+
# N = -1
|
| 239 |
+
assert diop_DN(13, -1) == [(18, 5)]
|
| 240 |
+
assert diop_DN(991, -1) == []
|
| 241 |
+
assert diop_DN(41, -1) == [(32, 5)]
|
| 242 |
+
assert diop_DN(290, -1) == [(17, 1)]
|
| 243 |
+
assert diop_DN(21257, -1) == [(13913102721304, 95427381109)]
|
| 244 |
+
assert diop_DN(32, -1) == []
|
| 245 |
+
|
| 246 |
+
# |N| > 1
|
| 247 |
+
# Some tests were created using calculator at
|
| 248 |
+
# http://www.numbertheory.org/php/patz.html
|
| 249 |
+
|
| 250 |
+
assert diop_DN(13, -4) == [(3, 1), (393, 109), (36, 10)]
|
| 251 |
+
# Source I referred returned (3, 1), (393, 109) and (-3, 1) as fundamental solutions
|
| 252 |
+
# So (-3, 1) and (393, 109) should be in the same equivalent class
|
| 253 |
+
assert equivalent(-3, 1, 393, 109, 13, -4) == True
|
| 254 |
+
|
| 255 |
+
assert diop_DN(13, 27) == [(220, 61), (40, 11), (768, 213), (12, 3)]
|
| 256 |
+
assert set(diop_DN(157, 12)) == {(13, 1), (10663, 851), (579160, 46222),
|
| 257 |
+
(483790960, 38610722), (26277068347, 2097138361),
|
| 258 |
+
(21950079635497, 1751807067011)}
|
| 259 |
+
assert diop_DN(13, 25) == [(3245, 900)]
|
| 260 |
+
assert diop_DN(192, 18) == []
|
| 261 |
+
assert diop_DN(23, 13) == [(-6, 1), (6, 1)]
|
| 262 |
+
assert diop_DN(167, 2) == [(13, 1)]
|
| 263 |
+
assert diop_DN(167, -2) == []
|
| 264 |
+
|
| 265 |
+
assert diop_DN(123, -2) == [(11, 1)]
|
| 266 |
+
# One calculator returned [(11, 1), (-11, 1)] but both of these are in
|
| 267 |
+
# the same equivalence class
|
| 268 |
+
assert equivalent(11, 1, -11, 1, 123, -2)
|
| 269 |
+
|
| 270 |
+
assert diop_DN(123, -23) == [(-10, 1), (10, 1)]
|
| 271 |
+
|
| 272 |
+
assert diop_DN(0, 0, t) == [(0, t)]
|
| 273 |
+
assert diop_DN(0, -1, t) == []
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
def test_bf_pell():
|
| 277 |
+
assert diop_bf_DN(13, -4) == [(3, 1), (-3, 1), (36, 10)]
|
| 278 |
+
assert diop_bf_DN(13, 27) == [(12, 3), (-12, 3), (40, 11), (-40, 11)]
|
| 279 |
+
assert diop_bf_DN(167, -2) == []
|
| 280 |
+
assert diop_bf_DN(1729, 1) == [(44611924489705, 1072885712316)]
|
| 281 |
+
assert diop_bf_DN(89, -8) == [(9, 1), (-9, 1)]
|
| 282 |
+
assert diop_bf_DN(21257, -1) == [(13913102721304, 95427381109)]
|
| 283 |
+
assert diop_bf_DN(340, -4) == [(756, 41)]
|
| 284 |
+
assert diop_bf_DN(-1, 0, t) == [(0, 0)]
|
| 285 |
+
assert diop_bf_DN(0, 0, t) == [(0, t)]
|
| 286 |
+
assert diop_bf_DN(4, 0, t) == [(2*t, t), (-2*t, t)]
|
| 287 |
+
assert diop_bf_DN(3, 0, t) == [(0, 0)]
|
| 288 |
+
assert diop_bf_DN(1, -2, t) == []
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def test_length():
|
| 292 |
+
assert length(2, 1, 0) == 1
|
| 293 |
+
assert length(-2, 4, 5) == 3
|
| 294 |
+
assert length(-5, 4, 17) == 4
|
| 295 |
+
assert length(0, 4, 13) == 6
|
| 296 |
+
assert length(7, 13, 11) == 23
|
| 297 |
+
assert length(1, 6, 4) == 2
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def is_pell_transformation_ok(eq):
|
| 301 |
+
"""
|
| 302 |
+
Test whether X*Y, X, or Y terms are present in the equation
|
| 303 |
+
after transforming the equation using the transformation returned
|
| 304 |
+
by transformation_to_pell(). If they are not present we are good.
|
| 305 |
+
Moreover, coefficient of X**2 should be a divisor of coefficient of
|
| 306 |
+
Y**2 and the constant term.
|
| 307 |
+
"""
|
| 308 |
+
A, B = transformation_to_DN(eq)
|
| 309 |
+
u = (A*Matrix([X, Y]) + B)[0]
|
| 310 |
+
v = (A*Matrix([X, Y]) + B)[1]
|
| 311 |
+
simplified = diop_simplify(eq.subs(zip((x, y), (u, v))))
|
| 312 |
+
|
| 313 |
+
coeff = dict([reversed(t.as_independent(*[X, Y])) for t in simplified.args])
|
| 314 |
+
|
| 315 |
+
for term in [X*Y, X, Y]:
|
| 316 |
+
if term in coeff.keys():
|
| 317 |
+
return False
|
| 318 |
+
|
| 319 |
+
for term in [X**2, Y**2, 1]:
|
| 320 |
+
if term not in coeff.keys():
|
| 321 |
+
coeff[term] = 0
|
| 322 |
+
|
| 323 |
+
if coeff[X**2] != 0:
|
| 324 |
+
return divisible(coeff[Y**2], coeff[X**2]) and \
|
| 325 |
+
divisible(coeff[1], coeff[X**2])
|
| 326 |
+
|
| 327 |
+
return True
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def test_transformation_to_pell():
|
| 331 |
+
assert is_pell_transformation_ok(-13*x**2 - 7*x*y + y**2 + 2*x - 2*y - 14)
|
| 332 |
+
assert is_pell_transformation_ok(-17*x**2 + 19*x*y - 7*y**2 - 5*x - 13*y - 23)
|
| 333 |
+
assert is_pell_transformation_ok(x**2 - y**2 + 17)
|
| 334 |
+
assert is_pell_transformation_ok(-x**2 + 7*y**2 - 23)
|
| 335 |
+
assert is_pell_transformation_ok(25*x**2 - 45*x*y + 5*y**2 - 5*x - 10*y + 5)
|
| 336 |
+
assert is_pell_transformation_ok(190*x**2 + 30*x*y + y**2 - 3*y - 170*x - 130)
|
| 337 |
+
assert is_pell_transformation_ok(x**2 - 2*x*y -190*y**2 - 7*y - 23*x - 89)
|
| 338 |
+
assert is_pell_transformation_ok(15*x**2 - 9*x*y + 14*y**2 - 23*x - 14*y - 4950)
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
def test_find_DN():
|
| 342 |
+
assert find_DN(x**2 - 2*x - y**2) == (1, 1)
|
| 343 |
+
assert find_DN(x**2 - 3*y**2 - 5) == (3, 5)
|
| 344 |
+
assert find_DN(x**2 - 2*x*y - 4*y**2 - 7) == (5, 7)
|
| 345 |
+
assert find_DN(4*x**2 - 8*x*y - y**2 - 9) == (20, 36)
|
| 346 |
+
assert find_DN(7*x**2 - 2*x*y - y**2 - 12) == (8, 84)
|
| 347 |
+
assert find_DN(-3*x**2 + 4*x*y -y**2) == (1, 0)
|
| 348 |
+
assert find_DN(-13*x**2 - 7*x*y + y**2 + 2*x - 2*y -14) == (101, -7825480)
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
def test_ldescent():
|
| 352 |
+
# Equations which have solutions
|
| 353 |
+
u = ([(13, 23), (3, -11), (41, -113), (4, -7), (-7, 4), (91, -3), (1, 1), (1, -1),
|
| 354 |
+
(4, 32), (17, 13), (123689, 1), (19, -570)])
|
| 355 |
+
for a, b in u:
|
| 356 |
+
w, x, y = ldescent(a, b)
|
| 357 |
+
assert a*x**2 + b*y**2 == w**2
|
| 358 |
+
assert ldescent(-1, -1) is None
|
| 359 |
+
assert ldescent(2, 6) is None
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
def test_diop_ternary_quadratic_normal():
|
| 363 |
+
assert check_solutions(234*x**2 - 65601*y**2 - z**2)
|
| 364 |
+
assert check_solutions(23*x**2 + 616*y**2 - z**2)
|
| 365 |
+
assert check_solutions(5*x**2 + 4*y**2 - z**2)
|
| 366 |
+
assert check_solutions(3*x**2 + 6*y**2 - 3*z**2)
|
| 367 |
+
assert check_solutions(x**2 + 3*y**2 - z**2)
|
| 368 |
+
assert check_solutions(4*x**2 + 5*y**2 - z**2)
|
| 369 |
+
assert check_solutions(x**2 + y**2 - z**2)
|
| 370 |
+
assert check_solutions(16*x**2 + y**2 - 25*z**2)
|
| 371 |
+
assert check_solutions(6*x**2 - y**2 + 10*z**2)
|
| 372 |
+
assert check_solutions(213*x**2 + 12*y**2 - 9*z**2)
|
| 373 |
+
assert check_solutions(34*x**2 - 3*y**2 - 301*z**2)
|
| 374 |
+
assert check_solutions(124*x**2 - 30*y**2 - 7729*z**2)
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
def is_normal_transformation_ok(eq):
|
| 378 |
+
A = transformation_to_normal(eq)
|
| 379 |
+
X, Y, Z = A*Matrix([x, y, z])
|
| 380 |
+
simplified = diop_simplify(eq.subs(zip((x, y, z), (X, Y, Z))))
|
| 381 |
+
|
| 382 |
+
coeff = dict([reversed(t.as_independent(*[X, Y, Z])) for t in simplified.args])
|
| 383 |
+
for term in [X*Y, Y*Z, X*Z]:
|
| 384 |
+
if term in coeff.keys():
|
| 385 |
+
return False
|
| 386 |
+
|
| 387 |
+
return True
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
def test_transformation_to_normal():
|
| 391 |
+
assert is_normal_transformation_ok(x**2 + 3*y**2 + z**2 - 13*x*y - 16*y*z + 12*x*z)
|
| 392 |
+
assert is_normal_transformation_ok(x**2 + 3*y**2 - 100*z**2)
|
| 393 |
+
assert is_normal_transformation_ok(x**2 + 23*y*z)
|
| 394 |
+
assert is_normal_transformation_ok(3*y**2 - 100*z**2 - 12*x*y)
|
| 395 |
+
assert is_normal_transformation_ok(x**2 + 23*x*y - 34*y*z + 12*x*z)
|
| 396 |
+
assert is_normal_transformation_ok(z**2 + 34*x*y - 23*y*z + x*z)
|
| 397 |
+
assert is_normal_transformation_ok(x**2 + y**2 + z**2 - x*y - y*z - x*z)
|
| 398 |
+
assert is_normal_transformation_ok(x**2 + 2*y*z + 3*z**2)
|
| 399 |
+
assert is_normal_transformation_ok(x*y + 2*x*z + 3*y*z)
|
| 400 |
+
assert is_normal_transformation_ok(2*x*z + 3*y*z)
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
def test_diop_ternary_quadratic():
|
| 404 |
+
assert check_solutions(2*x**2 + z**2 + y**2 - 4*x*y)
|
| 405 |
+
assert check_solutions(x**2 - y**2 - z**2 - x*y - y*z)
|
| 406 |
+
assert check_solutions(3*x**2 - x*y - y*z - x*z)
|
| 407 |
+
assert check_solutions(x**2 - y*z - x*z)
|
| 408 |
+
assert check_solutions(5*x**2 - 3*x*y - x*z)
|
| 409 |
+
assert check_solutions(4*x**2 - 5*y**2 - x*z)
|
| 410 |
+
assert check_solutions(3*x**2 + 2*y**2 - z**2 - 2*x*y + 5*y*z - 7*y*z)
|
| 411 |
+
assert check_solutions(8*x**2 - 12*y*z)
|
| 412 |
+
assert check_solutions(45*x**2 - 7*y**2 - 8*x*y - z**2)
|
| 413 |
+
assert check_solutions(x**2 - 49*y**2 - z**2 + 13*z*y -8*x*y)
|
| 414 |
+
assert check_solutions(90*x**2 + 3*y**2 + 5*x*y + 2*z*y + 5*x*z)
|
| 415 |
+
assert check_solutions(x**2 + 3*y**2 + z**2 - x*y - 17*y*z)
|
| 416 |
+
assert check_solutions(x**2 + 3*y**2 + z**2 - x*y - 16*y*z + 12*x*z)
|
| 417 |
+
assert check_solutions(x**2 + 3*y**2 + z**2 - 13*x*y - 16*y*z + 12*x*z)
|
| 418 |
+
assert check_solutions(x*y - 7*y*z + 13*x*z)
|
| 419 |
+
|
| 420 |
+
assert diop_ternary_quadratic_normal(x**2 + y**2 + z**2) == (None, None, None)
|
| 421 |
+
assert diop_ternary_quadratic_normal(x**2 + y**2) is None
|
| 422 |
+
raises(ValueError, lambda:
|
| 423 |
+
_diop_ternary_quadratic_normal((x, y, z),
|
| 424 |
+
{x*y: 1, x**2: 2, y**2: 3, z**2: 0}))
|
| 425 |
+
eq = -2*x*y - 6*x*z + 7*y**2 - 3*y*z + 4*z**2
|
| 426 |
+
assert diop_ternary_quadratic(eq) == (7, 2, 0)
|
| 427 |
+
assert diop_ternary_quadratic_normal(4*x**2 + 5*y**2 - z**2) == \
|
| 428 |
+
(1, 0, 2)
|
| 429 |
+
assert diop_ternary_quadratic(x*y + 2*y*z) == \
|
| 430 |
+
(-2, 0, n1)
|
| 431 |
+
eq = -5*x*y - 8*x*z - 3*y*z + 8*z**2
|
| 432 |
+
assert parametrize_ternary_quadratic(eq) == \
|
| 433 |
+
(8*p**2 - 3*p*q, -8*p*q + 8*q**2, 5*p*q)
|
| 434 |
+
# this cannot be tested with diophantine because it will
|
| 435 |
+
# factor into a product
|
| 436 |
+
assert diop_solve(x*y + 2*y*z) == (-2*p*q, -n1*p**2 + p**2, p*q)
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
def test_square_factor():
|
| 440 |
+
assert square_factor(1) == square_factor(-1) == 1
|
| 441 |
+
assert square_factor(0) == 1
|
| 442 |
+
assert square_factor(5) == square_factor(-5) == 1
|
| 443 |
+
assert square_factor(4) == square_factor(-4) == 2
|
| 444 |
+
assert square_factor(12) == square_factor(-12) == 2
|
| 445 |
+
assert square_factor(6) == 1
|
| 446 |
+
assert square_factor(18) == 3
|
| 447 |
+
assert square_factor(52) == 2
|
| 448 |
+
assert square_factor(49) == 7
|
| 449 |
+
assert square_factor(392) == 14
|
| 450 |
+
assert square_factor(factorint(-12)) == 2
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
def test_parametrize_ternary_quadratic():
|
| 454 |
+
assert check_solutions(x**2 + y**2 - z**2)
|
| 455 |
+
assert check_solutions(x**2 + 2*x*y + z**2)
|
| 456 |
+
assert check_solutions(234*x**2 - 65601*y**2 - z**2)
|
| 457 |
+
assert check_solutions(3*x**2 + 2*y**2 - z**2 - 2*x*y + 5*y*z - 7*y*z)
|
| 458 |
+
assert check_solutions(x**2 - y**2 - z**2)
|
| 459 |
+
assert check_solutions(x**2 - 49*y**2 - z**2 + 13*z*y - 8*x*y)
|
| 460 |
+
assert check_solutions(8*x*y + z**2)
|
| 461 |
+
assert check_solutions(124*x**2 - 30*y**2 - 7729*z**2)
|
| 462 |
+
assert check_solutions(236*x**2 - 225*y**2 - 11*x*y - 13*y*z - 17*x*z)
|
| 463 |
+
assert check_solutions(90*x**2 + 3*y**2 + 5*x*y + 2*z*y + 5*x*z)
|
| 464 |
+
assert check_solutions(124*x**2 - 30*y**2 - 7729*z**2)
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
def test_no_square_ternary_quadratic():
|
| 468 |
+
assert check_solutions(2*x*y + y*z - 3*x*z)
|
| 469 |
+
assert check_solutions(189*x*y - 345*y*z - 12*x*z)
|
| 470 |
+
assert check_solutions(23*x*y + 34*y*z)
|
| 471 |
+
assert check_solutions(x*y + y*z + z*x)
|
| 472 |
+
assert check_solutions(23*x*y + 23*y*z + 23*x*z)
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
def test_descent():
|
| 476 |
+
|
| 477 |
+
u = ([(13, 23), (3, -11), (41, -113), (91, -3), (1, 1), (1, -1), (17, 13), (123689, 1), (19, -570)])
|
| 478 |
+
for a, b in u:
|
| 479 |
+
w, x, y = descent(a, b)
|
| 480 |
+
assert a*x**2 + b*y**2 == w**2
|
| 481 |
+
# the docstring warns against bad input, so these are expected results
|
| 482 |
+
# - can't both be negative
|
| 483 |
+
raises(TypeError, lambda: descent(-1, -3))
|
| 484 |
+
# A can't be zero unless B != 1
|
| 485 |
+
raises(ZeroDivisionError, lambda: descent(0, 3))
|
| 486 |
+
# supposed to be square-free
|
| 487 |
+
raises(TypeError, lambda: descent(4, 3))
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
def test_diophantine():
|
| 491 |
+
assert check_solutions((x - y)*(y - z)*(z - x))
|
| 492 |
+
assert check_solutions((x - y)*(x**2 + y**2 - z**2))
|
| 493 |
+
assert check_solutions((x - 3*y + 7*z)*(x**2 + y**2 - z**2))
|
| 494 |
+
assert check_solutions(x**2 - 3*y**2 - 1)
|
| 495 |
+
assert check_solutions(y**2 + 7*x*y)
|
| 496 |
+
assert check_solutions(x**2 - 3*x*y + y**2)
|
| 497 |
+
assert check_solutions(z*(x**2 - y**2 - 15))
|
| 498 |
+
assert check_solutions(x*(2*y - 2*z + 5))
|
| 499 |
+
assert check_solutions((x**2 - 3*y**2 - 1)*(x**2 - y**2 - 15))
|
| 500 |
+
assert check_solutions((x**2 - 3*y**2 - 1)*(y - 7*z))
|
| 501 |
+
assert check_solutions((x**2 + y**2 - z**2)*(x - 7*y - 3*z + 4*w))
|
| 502 |
+
# Following test case caused problems in parametric representation
|
| 503 |
+
# But this can be solved by factoring out y.
|
| 504 |
+
# No need to use methods for ternary quadratic equations.
|
| 505 |
+
assert check_solutions(y**2 - 7*x*y + 4*y*z)
|
| 506 |
+
assert check_solutions(x**2 - 2*x + 1)
|
| 507 |
+
|
| 508 |
+
assert diophantine(x - y) == diophantine(Eq(x, y))
|
| 509 |
+
# 18196
|
| 510 |
+
eq = x**4 + y**4 - 97
|
| 511 |
+
assert diophantine(eq, permute=True) == diophantine(-eq, permute=True)
|
| 512 |
+
assert diophantine(3*x*pi - 2*y*pi) == {(2*t_0, 3*t_0)}
|
| 513 |
+
eq = x**2 + y**2 + z**2 - 14
|
| 514 |
+
base_sol = {(1, 2, 3)}
|
| 515 |
+
assert diophantine(eq) == base_sol
|
| 516 |
+
complete_soln = set(signed_permutations(base_sol.pop()))
|
| 517 |
+
assert diophantine(eq, permute=True) == complete_soln
|
| 518 |
+
|
| 519 |
+
assert diophantine(x**2 + x*Rational(15, 14) - 3) == set()
|
| 520 |
+
# test issue 11049
|
| 521 |
+
eq = 92*x**2 - 99*y**2 - z**2
|
| 522 |
+
coeff = eq.as_coefficients_dict()
|
| 523 |
+
assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \
|
| 524 |
+
{(9, 7, 51)}
|
| 525 |
+
assert diophantine(eq) == {(
|
| 526 |
+
891*p**2 + 9*q**2, -693*p**2 - 102*p*q + 7*q**2,
|
| 527 |
+
5049*p**2 - 1386*p*q - 51*q**2)}
|
| 528 |
+
eq = 2*x**2 + 2*y**2 - z**2
|
| 529 |
+
coeff = eq.as_coefficients_dict()
|
| 530 |
+
assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \
|
| 531 |
+
{(1, 1, 2)}
|
| 532 |
+
assert diophantine(eq) == {(
|
| 533 |
+
2*p**2 - q**2, -2*p**2 + 4*p*q - q**2,
|
| 534 |
+
4*p**2 - 4*p*q + 2*q**2)}
|
| 535 |
+
eq = 411*x**2+57*y**2-221*z**2
|
| 536 |
+
coeff = eq.as_coefficients_dict()
|
| 537 |
+
assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \
|
| 538 |
+
{(2021, 2645, 3066)}
|
| 539 |
+
assert diophantine(eq) == \
|
| 540 |
+
{(115197*p**2 - 446641*q**2, -150765*p**2 + 1355172*p*q -
|
| 541 |
+
584545*q**2, 174762*p**2 - 301530*p*q + 677586*q**2)}
|
| 542 |
+
eq = 573*x**2+267*y**2-984*z**2
|
| 543 |
+
coeff = eq.as_coefficients_dict()
|
| 544 |
+
assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \
|
| 545 |
+
{(49, 233, 127)}
|
| 546 |
+
assert diophantine(eq) == \
|
| 547 |
+
{(4361*p**2 - 16072*q**2, -20737*p**2 + 83312*p*q - 76424*q**2,
|
| 548 |
+
11303*p**2 - 41474*p*q + 41656*q**2)}
|
| 549 |
+
# this produces factors during reconstruction
|
| 550 |
+
eq = x**2 + 3*y**2 - 12*z**2
|
| 551 |
+
coeff = eq.as_coefficients_dict()
|
| 552 |
+
assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \
|
| 553 |
+
{(0, 2, 1)}
|
| 554 |
+
assert diophantine(eq) == \
|
| 555 |
+
{(24*p*q, 2*p**2 - 24*q**2, p**2 + 12*q**2)}
|
| 556 |
+
# solvers have not been written for every type
|
| 557 |
+
raises(NotImplementedError, lambda: diophantine(x*y**2 + 1))
|
| 558 |
+
|
| 559 |
+
# rational expressions
|
| 560 |
+
assert diophantine(1/x) == set()
|
| 561 |
+
assert diophantine(1/x + 1/y - S.Half) == {(6, 3), (-2, 1), (4, 4), (1, -2), (3, 6)}
|
| 562 |
+
assert diophantine(x**2 + y**2 +3*x- 5, permute=True) == \
|
| 563 |
+
{(-1, 1), (-4, -1), (1, -1), (1, 1), (-4, 1), (-1, -1), (4, 1), (4, -1)}
|
| 564 |
+
|
| 565 |
+
|
| 566 |
+
#test issue 18186
|
| 567 |
+
assert diophantine(y**4 + x**4 - 2**4 - 3**4, syms=(x, y), permute=True) == \
|
| 568 |
+
{(-3, -2), (-3, 2), (-2, -3), (-2, 3), (2, -3), (2, 3), (3, -2), (3, 2)}
|
| 569 |
+
assert diophantine(y**4 + x**4 - 2**4 - 3**4, syms=(y, x), permute=True) == \
|
| 570 |
+
{(-3, -2), (-3, 2), (-2, -3), (-2, 3), (2, -3), (2, 3), (3, -2), (3, 2)}
|
| 571 |
+
|
| 572 |
+
# issue 18122
|
| 573 |
+
assert check_solutions(x**2 - y)
|
| 574 |
+
assert check_solutions(y**2 - x)
|
| 575 |
+
assert diophantine((x**2 - y), t) == {(t, t**2)}
|
| 576 |
+
assert diophantine((y**2 - x), t) == {(t**2, t)}
|
| 577 |
+
|
| 578 |
+
|
| 579 |
+
def test_general_pythagorean():
|
| 580 |
+
from sympy.abc import a, b, c, d, e
|
| 581 |
+
|
| 582 |
+
assert check_solutions(a**2 + b**2 + c**2 - d**2)
|
| 583 |
+
assert check_solutions(a**2 + 4*b**2 + 4*c**2 - d**2)
|
| 584 |
+
assert check_solutions(9*a**2 + 4*b**2 + 4*c**2 - d**2)
|
| 585 |
+
assert check_solutions(9*a**2 + 4*b**2 - 25*d**2 + 4*c**2 )
|
| 586 |
+
assert check_solutions(9*a**2 - 16*d**2 + 4*b**2 + 4*c**2)
|
| 587 |
+
assert check_solutions(-e**2 + 9*a**2 + 4*b**2 + 4*c**2 + 25*d**2)
|
| 588 |
+
assert check_solutions(16*a**2 - b**2 + 9*c**2 + d**2 + 25*e**2)
|
| 589 |
+
|
| 590 |
+
assert GeneralPythagorean(a**2 + b**2 + c**2 - d**2).solve(parameters=[x, y, z]) == \
|
| 591 |
+
{(x**2 + y**2 - z**2, 2*x*z, 2*y*z, x**2 + y**2 + z**2)}
|
| 592 |
+
|
| 593 |
+
|
| 594 |
+
def test_diop_general_sum_of_squares_quick():
|
| 595 |
+
for i in range(3, 10):
|
| 596 |
+
assert check_solutions(sum(i**2 for i in symbols(':%i' % i)) - i)
|
| 597 |
+
|
| 598 |
+
assert diop_general_sum_of_squares(x**2 + y**2 - 2) is None
|
| 599 |
+
assert diop_general_sum_of_squares(x**2 + y**2 + z**2 + 2) == set()
|
| 600 |
+
eq = x**2 + y**2 + z**2 - (1 + 4 + 9)
|
| 601 |
+
assert diop_general_sum_of_squares(eq) == \
|
| 602 |
+
{(1, 2, 3)}
|
| 603 |
+
eq = u**2 + v**2 + x**2 + y**2 + z**2 - 1313
|
| 604 |
+
assert len(diop_general_sum_of_squares(eq, 3)) == 3
|
| 605 |
+
# issue 11016
|
| 606 |
+
var = symbols(':5') + (symbols('6', negative=True),)
|
| 607 |
+
eq = Add(*[i**2 for i in var]) - 112
|
| 608 |
+
|
| 609 |
+
base_soln = {(0, 1, 1, 5, 6, -7), (1, 1, 1, 3, 6, -8), (2, 3, 3, 4, 5, -7), (0, 1, 1, 1, 3, -10),
|
| 610 |
+
(0, 0, 4, 4, 4, -8), (1, 2, 3, 3, 5, -8), (0, 1, 2, 3, 7, -7), (2, 2, 4, 4, 6, -6),
|
| 611 |
+
(1, 1, 3, 4, 6, -7), (0, 2, 3, 3, 3, -9), (0, 0, 2, 2, 2, -10), (1, 1, 2, 3, 4, -9),
|
| 612 |
+
(0, 1, 1, 2, 5, -9), (0, 0, 2, 6, 6, -6), (1, 3, 4, 5, 5, -6), (0, 2, 2, 2, 6, -8),
|
| 613 |
+
(0, 3, 3, 3, 6, -7), (0, 2, 3, 5, 5, -7), (0, 1, 5, 5, 5, -6)}
|
| 614 |
+
assert diophantine(eq) == base_soln
|
| 615 |
+
assert len(diophantine(eq, permute=True)) == 196800
|
| 616 |
+
|
| 617 |
+
# handle negated squares with signsimp
|
| 618 |
+
assert diophantine(12 - x**2 - y**2 - z**2) == {(2, 2, 2)}
|
| 619 |
+
# diophantine handles simplification, so classify_diop should
|
| 620 |
+
# not have to look for additional patterns that are removed
|
| 621 |
+
# by diophantine
|
| 622 |
+
eq = a**2 + b**2 + c**2 + d**2 - 4
|
| 623 |
+
raises(NotImplementedError, lambda: classify_diop(-eq))
|
| 624 |
+
|
| 625 |
+
|
| 626 |
+
def test_issue_23807():
|
| 627 |
+
# fixes recursion error
|
| 628 |
+
eq = x**2 + y**2 + z**2 - 1000000
|
| 629 |
+
base_soln = {(0, 0, 1000), (0, 352, 936), (480, 600, 640), (24, 640, 768), (192, 640, 744),
|
| 630 |
+
(192, 480, 856), (168, 224, 960), (0, 600, 800), (280, 576, 768), (152, 480, 864),
|
| 631 |
+
(0, 280, 960), (352, 360, 864), (424, 480, 768), (360, 480, 800), (224, 600, 768),
|
| 632 |
+
(96, 360, 928), (168, 576, 800), (96, 480, 872)}
|
| 633 |
+
|
| 634 |
+
assert diophantine(eq) == base_soln
|
| 635 |
+
|
| 636 |
+
|
| 637 |
+
def test_diop_partition():
|
| 638 |
+
for n in [8, 10]:
|
| 639 |
+
for k in range(1, 8):
|
| 640 |
+
for p in partition(n, k):
|
| 641 |
+
assert len(p) == k
|
| 642 |
+
assert list(partition(3, 5)) == []
|
| 643 |
+
assert [list(p) for p in partition(3, 5, 1)] == [
|
| 644 |
+
[0, 0, 0, 0, 3], [0, 0, 0, 1, 2], [0, 0, 1, 1, 1]]
|
| 645 |
+
assert list(partition(0)) == [()]
|
| 646 |
+
assert list(partition(1, 0)) == [()]
|
| 647 |
+
assert [list(i) for i in partition(3)] == [[1, 1, 1], [1, 2], [3]]
|
| 648 |
+
|
| 649 |
+
|
| 650 |
+
def test_prime_as_sum_of_two_squares():
|
| 651 |
+
for i in [5, 13, 17, 29, 37, 41, 2341, 3557, 34841, 64601]:
|
| 652 |
+
a, b = prime_as_sum_of_two_squares(i)
|
| 653 |
+
assert a**2 + b**2 == i
|
| 654 |
+
assert prime_as_sum_of_two_squares(7) is None
|
| 655 |
+
ans = prime_as_sum_of_two_squares(800029)
|
| 656 |
+
assert ans == (450, 773) and type(ans[0]) is int
|
| 657 |
+
|
| 658 |
+
|
| 659 |
+
def test_sum_of_three_squares():
|
| 660 |
+
for i in [0, 1, 2, 34, 123, 34304595905, 34304595905394941, 343045959052344,
|
| 661 |
+
800, 801, 802, 803, 804, 805, 806]:
|
| 662 |
+
a, b, c = sum_of_three_squares(i)
|
| 663 |
+
assert a**2 + b**2 + c**2 == i
|
| 664 |
+
assert a >= 0
|
| 665 |
+
|
| 666 |
+
# error
|
| 667 |
+
raises(ValueError, lambda: sum_of_three_squares(-1))
|
| 668 |
+
|
| 669 |
+
assert sum_of_three_squares(7) is None
|
| 670 |
+
assert sum_of_three_squares((4**5)*15) is None
|
| 671 |
+
# if there are two zeros, there might be a solution
|
| 672 |
+
# with only one zero, e.g. 25 => (0, 3, 4) or
|
| 673 |
+
# with no zeros, e.g. 49 => (2, 3, 6)
|
| 674 |
+
assert sum_of_three_squares(25) == (0, 0, 5)
|
| 675 |
+
assert sum_of_three_squares(4) == (0, 0, 2)
|
| 676 |
+
|
| 677 |
+
|
| 678 |
+
def test_sum_of_four_squares():
|
| 679 |
+
from sympy.core.random import randint
|
| 680 |
+
|
| 681 |
+
# this should never fail
|
| 682 |
+
n = randint(1, 100000000000000)
|
| 683 |
+
assert sum(i**2 for i in sum_of_four_squares(n)) == n
|
| 684 |
+
|
| 685 |
+
# error
|
| 686 |
+
raises(ValueError, lambda: sum_of_four_squares(-1))
|
| 687 |
+
|
| 688 |
+
for n in range(1000):
|
| 689 |
+
result = sum_of_four_squares(n)
|
| 690 |
+
assert len(result) == 4
|
| 691 |
+
assert all(r >= 0 for r in result)
|
| 692 |
+
assert sum(r**2 for r in result) == n
|
| 693 |
+
assert list(result) == sorted(result)
|
| 694 |
+
|
| 695 |
+
|
| 696 |
+
def test_power_representation():
|
| 697 |
+
tests = [(1729, 3, 2), (234, 2, 4), (2, 1, 2), (3, 1, 3), (5, 2, 2), (12352, 2, 4),
|
| 698 |
+
(32760, 2, 3)]
|
| 699 |
+
|
| 700 |
+
for test in tests:
|
| 701 |
+
n, p, k = test
|
| 702 |
+
f = power_representation(n, p, k)
|
| 703 |
+
|
| 704 |
+
while True:
|
| 705 |
+
try:
|
| 706 |
+
l = next(f)
|
| 707 |
+
assert len(l) == k
|
| 708 |
+
|
| 709 |
+
chk_sum = 0
|
| 710 |
+
for l_i in l:
|
| 711 |
+
chk_sum = chk_sum + l_i**p
|
| 712 |
+
assert chk_sum == n
|
| 713 |
+
|
| 714 |
+
except StopIteration:
|
| 715 |
+
break
|
| 716 |
+
|
| 717 |
+
assert list(power_representation(20, 2, 4, True)) == \
|
| 718 |
+
[(1, 1, 3, 3), (0, 0, 2, 4)]
|
| 719 |
+
raises(ValueError, lambda: list(power_representation(1.2, 2, 2)))
|
| 720 |
+
raises(ValueError, lambda: list(power_representation(2, 0, 2)))
|
| 721 |
+
raises(ValueError, lambda: list(power_representation(2, 2, 0)))
|
| 722 |
+
assert list(power_representation(-1, 2, 2)) == []
|
| 723 |
+
assert list(power_representation(1, 1, 1)) == [(1,)]
|
| 724 |
+
assert list(power_representation(3, 2, 1)) == []
|
| 725 |
+
assert list(power_representation(4, 2, 1)) == [(2,)]
|
| 726 |
+
assert list(power_representation(3**4, 4, 6, zeros=True)) == \
|
| 727 |
+
[(1, 2, 2, 2, 2, 2), (0, 0, 0, 0, 0, 3)]
|
| 728 |
+
assert list(power_representation(3**4, 4, 5, zeros=False)) == []
|
| 729 |
+
assert list(power_representation(-2, 3, 2)) == [(-1, -1)]
|
| 730 |
+
assert list(power_representation(-2, 4, 2)) == []
|
| 731 |
+
assert list(power_representation(0, 3, 2, True)) == [(0, 0)]
|
| 732 |
+
assert list(power_representation(0, 3, 2, False)) == []
|
| 733 |
+
# when we are dealing with squares, do feasibility checks
|
| 734 |
+
assert len(list(power_representation(4**10*(8*10 + 7), 2, 3))) == 0
|
| 735 |
+
# there will be a recursion error if these aren't recognized
|
| 736 |
+
big = 2**30
|
| 737 |
+
for i in [13, 10, 7, 5, 4, 2, 1]:
|
| 738 |
+
assert list(sum_of_powers(big, 2, big - i)) == []
|
| 739 |
+
|
| 740 |
+
|
| 741 |
+
def test_assumptions():
|
| 742 |
+
"""
|
| 743 |
+
Test whether diophantine respects the assumptions.
|
| 744 |
+
"""
|
| 745 |
+
#Test case taken from the below so question regarding assumptions in diophantine module
|
| 746 |
+
#https://stackoverflow.com/questions/23301941/how-can-i-declare-natural-symbols-with-sympy
|
| 747 |
+
m, n = symbols('m n', integer=True, positive=True)
|
| 748 |
+
diof = diophantine(n**2 + m*n - 500)
|
| 749 |
+
assert diof == {(5, 20), (40, 10), (95, 5), (121, 4), (248, 2), (499, 1)}
|
| 750 |
+
|
| 751 |
+
a, b = symbols('a b', integer=True, positive=False)
|
| 752 |
+
diof = diophantine(a*b + 2*a + 3*b - 6)
|
| 753 |
+
assert diof == {(-15, -3), (-9, -4), (-7, -5), (-6, -6), (-5, -8), (-4, -14)}
|
| 754 |
+
|
| 755 |
+
|
| 756 |
+
def check_solutions(eq):
|
| 757 |
+
"""
|
| 758 |
+
Determines whether solutions returned by diophantine() satisfy the original
|
| 759 |
+
equation. Hope to generalize this so we can remove functions like check_ternay_quadratic,
|
| 760 |
+
check_solutions_normal, check_solutions()
|
| 761 |
+
"""
|
| 762 |
+
s = diophantine(eq)
|
| 763 |
+
|
| 764 |
+
factors = Mul.make_args(eq)
|
| 765 |
+
|
| 766 |
+
var = list(eq.free_symbols)
|
| 767 |
+
var.sort(key=default_sort_key)
|
| 768 |
+
|
| 769 |
+
while s:
|
| 770 |
+
solution = s.pop()
|
| 771 |
+
for f in factors:
|
| 772 |
+
if diop_simplify(f.subs(zip(var, solution))) == 0:
|
| 773 |
+
break
|
| 774 |
+
else:
|
| 775 |
+
return False
|
| 776 |
+
return True
|
| 777 |
+
|
| 778 |
+
|
| 779 |
+
def test_diopcoverage():
|
| 780 |
+
eq = (2*x + y + 1)**2
|
| 781 |
+
assert diop_solve(eq) == {(t_0, -2*t_0 - 1)}
|
| 782 |
+
eq = 2*x**2 + 6*x*y + 12*x + 4*y**2 + 18*y + 18
|
| 783 |
+
assert diop_solve(eq) == {(t, -t - 3), (-2*t - 3, t)}
|
| 784 |
+
assert diop_quadratic(x + y**2 - 3) == {(-t**2 + 3, t)}
|
| 785 |
+
|
| 786 |
+
assert diop_linear(x + y - 3) == (t_0, 3 - t_0)
|
| 787 |
+
|
| 788 |
+
assert base_solution_linear(0, 1, 2, t=None) == (0, 0)
|
| 789 |
+
ans = (3*t - 1, -2*t + 1)
|
| 790 |
+
assert base_solution_linear(4, 8, 12, t) == ans
|
| 791 |
+
assert base_solution_linear(4, 8, 12, t=None) == tuple(_.subs(t, 0) for _ in ans)
|
| 792 |
+
|
| 793 |
+
assert cornacchia(1, 1, 20) == set()
|
| 794 |
+
assert cornacchia(1, 1, 5) == {(2, 1)}
|
| 795 |
+
assert cornacchia(1, 2, 17) == {(3, 2)}
|
| 796 |
+
|
| 797 |
+
raises(ValueError, lambda: reconstruct(4, 20, 1))
|
| 798 |
+
|
| 799 |
+
assert gaussian_reduce(4, 1, 3) == (1, 1)
|
| 800 |
+
eq = -w**2 - x**2 - y**2 + z**2
|
| 801 |
+
|
| 802 |
+
assert diop_general_pythagorean(eq) == \
|
| 803 |
+
diop_general_pythagorean(-eq) == \
|
| 804 |
+
(m1**2 + m2**2 - m3**2, 2*m1*m3,
|
| 805 |
+
2*m2*m3, m1**2 + m2**2 + m3**2)
|
| 806 |
+
|
| 807 |
+
assert len(check_param(S(3) + x/3, S(4) + x/2, S(2), [x])) == 0
|
| 808 |
+
assert len(check_param(Rational(3, 2), S(4) + x, S(2), [x])) == 0
|
| 809 |
+
assert len(check_param(S(4) + x, Rational(3, 2), S(2), [x])) == 0
|
| 810 |
+
|
| 811 |
+
assert _nint_or_floor(16, 10) == 2
|
| 812 |
+
assert _odd(1) == (not _even(1)) == True
|
| 813 |
+
assert _odd(0) == (not _even(0)) == False
|
| 814 |
+
assert _remove_gcd(2, 4, 6) == (1, 2, 3)
|
| 815 |
+
raises(TypeError, lambda: _remove_gcd((2, 4, 6)))
|
| 816 |
+
assert sqf_normal(2*3**2*5, 2*5*11, 2*7**2*11) == \
|
| 817 |
+
(11, 1, 5)
|
| 818 |
+
|
| 819 |
+
# it's ok if these pass some day when the solvers are implemented
|
| 820 |
+
raises(NotImplementedError, lambda: diophantine(x**2 + y**2 + x*y + 2*y*z - 12))
|
| 821 |
+
raises(NotImplementedError, lambda: diophantine(x**3 + y**2))
|
| 822 |
+
assert diop_quadratic(x**2 + y**2 - 1**2 - 3**4) == \
|
| 823 |
+
{(-9, -1), (-9, 1), (-1, -9), (-1, 9), (1, -9), (1, 9), (9, -1), (9, 1)}
|
| 824 |
+
|
| 825 |
+
|
| 826 |
+
def test_holzer():
|
| 827 |
+
# if the input is good, don't let it diverge in holzer()
|
| 828 |
+
# (but see test_fail_holzer below)
|
| 829 |
+
assert holzer(2, 7, 13, 4, 79, 23) == (2, 7, 13)
|
| 830 |
+
|
| 831 |
+
# None in uv condition met; solution is not Holzer reduced
|
| 832 |
+
# so this will hopefully change but is here for coverage
|
| 833 |
+
assert holzer(2, 6, 2, 1, 1, 10) == (2, 6, 2)
|
| 834 |
+
|
| 835 |
+
raises(ValueError, lambda: holzer(2, 7, 14, 4, 79, 23))
|
| 836 |
+
|
| 837 |
+
|
| 838 |
+
@XFAIL
|
| 839 |
+
def test_fail_holzer():
|
| 840 |
+
eq = lambda x, y, z: a*x**2 + b*y**2 - c*z**2
|
| 841 |
+
a, b, c = 4, 79, 23
|
| 842 |
+
x, y, z = xyz = 26, 1, 11
|
| 843 |
+
X, Y, Z = ans = 2, 7, 13
|
| 844 |
+
assert eq(*xyz) == 0
|
| 845 |
+
assert eq(*ans) == 0
|
| 846 |
+
assert max(a*x**2, b*y**2, c*z**2) <= a*b*c
|
| 847 |
+
assert max(a*X**2, b*Y**2, c*Z**2) <= a*b*c
|
| 848 |
+
h = holzer(x, y, z, a, b, c)
|
| 849 |
+
assert h == ans # it would be nice to get the smaller soln
|
| 850 |
+
|
| 851 |
+
|
| 852 |
+
def test_issue_9539():
|
| 853 |
+
assert diophantine(6*w + 9*y + 20*x - z) == \
|
| 854 |
+
{(t_0, t_1, t_1 + t_2, 6*t_0 + 29*t_1 + 9*t_2)}
|
| 855 |
+
|
| 856 |
+
|
| 857 |
+
def test_issue_8943():
|
| 858 |
+
assert diophantine(
|
| 859 |
+
3*(x**2 + y**2 + z**2) - 14*(x*y + y*z + z*x)) == \
|
| 860 |
+
{(0, 0, 0)}
|
| 861 |
+
|
| 862 |
+
|
| 863 |
+
def test_diop_sum_of_even_powers():
|
| 864 |
+
eq = x**4 + y**4 + z**4 - 2673
|
| 865 |
+
assert diop_solve(eq) == {(3, 6, 6), (2, 4, 7)}
|
| 866 |
+
assert diop_general_sum_of_even_powers(eq, 2) == {(3, 6, 6), (2, 4, 7)}
|
| 867 |
+
raises(NotImplementedError, lambda: diop_general_sum_of_even_powers(-eq, 2))
|
| 868 |
+
neg = symbols('neg', negative=True)
|
| 869 |
+
eq = x**4 + y**4 + neg**4 - 2673
|
| 870 |
+
assert diop_general_sum_of_even_powers(eq) == {(-3, 6, 6)}
|
| 871 |
+
assert diophantine(x**4 + y**4 + 2) == set()
|
| 872 |
+
assert diop_general_sum_of_even_powers(x**4 + y**4 - 2, limit=0) == set()
|
| 873 |
+
|
| 874 |
+
|
| 875 |
+
def test_sum_of_squares_powers():
|
| 876 |
+
tru = {(0, 0, 1, 1, 11), (0, 0, 5, 7, 7), (0, 1, 3, 7, 8), (0, 1, 4, 5, 9), (0, 3, 4, 7, 7), (0, 3, 5, 5, 8),
|
| 877 |
+
(1, 1, 2, 6, 9), (1, 1, 6, 6, 7), (1, 2, 3, 3, 10), (1, 3, 4, 4, 9), (1, 5, 5, 6, 6), (2, 2, 3, 5, 9),
|
| 878 |
+
(2, 3, 5, 6, 7), (3, 3, 4, 5, 8)}
|
| 879 |
+
eq = u**2 + v**2 + x**2 + y**2 + z**2 - 123
|
| 880 |
+
ans = diop_general_sum_of_squares(eq, oo) # allow oo to be used
|
| 881 |
+
assert len(ans) == 14
|
| 882 |
+
assert ans == tru
|
| 883 |
+
|
| 884 |
+
raises(ValueError, lambda: list(sum_of_squares(10, -1)))
|
| 885 |
+
assert list(sum_of_squares(1, 1)) == [(1,)]
|
| 886 |
+
assert list(sum_of_squares(1, 2)) == []
|
| 887 |
+
assert list(sum_of_squares(1, 2, True)) == [(0, 1)]
|
| 888 |
+
assert list(sum_of_squares(-10, 2)) == []
|
| 889 |
+
assert list(sum_of_squares(2, 3)) == []
|
| 890 |
+
assert list(sum_of_squares(0, 3, True)) == [(0, 0, 0)]
|
| 891 |
+
assert list(sum_of_squares(0, 3)) == []
|
| 892 |
+
assert list(sum_of_squares(4, 1)) == [(2,)]
|
| 893 |
+
assert list(sum_of_squares(5, 1)) == []
|
| 894 |
+
assert list(sum_of_squares(50, 2)) == [(5, 5), (1, 7)]
|
| 895 |
+
assert list(sum_of_squares(11, 5, True)) == [
|
| 896 |
+
(1, 1, 1, 2, 2), (0, 0, 1, 1, 3)]
|
| 897 |
+
assert list(sum_of_squares(8, 8)) == [(1, 1, 1, 1, 1, 1, 1, 1)]
|
| 898 |
+
|
| 899 |
+
assert [len(list(sum_of_squares(i, 5, True))) for i in range(30)] == [
|
| 900 |
+
1, 1, 1, 1, 2,
|
| 901 |
+
2, 1, 1, 2, 2,
|
| 902 |
+
2, 2, 2, 3, 2,
|
| 903 |
+
1, 3, 3, 3, 3,
|
| 904 |
+
4, 3, 3, 2, 2,
|
| 905 |
+
4, 4, 4, 4, 5]
|
| 906 |
+
assert [len(list(sum_of_squares(i, 5))) for i in range(30)] == [
|
| 907 |
+
0, 0, 0, 0, 0,
|
| 908 |
+
1, 0, 0, 1, 0,
|
| 909 |
+
0, 1, 0, 1, 1,
|
| 910 |
+
0, 1, 1, 0, 1,
|
| 911 |
+
2, 1, 1, 1, 1,
|
| 912 |
+
1, 1, 1, 1, 3]
|
| 913 |
+
for i in range(30):
|
| 914 |
+
s1 = set(sum_of_squares(i, 5, True))
|
| 915 |
+
assert not s1 or all(sum(j**2 for j in t) == i for t in s1)
|
| 916 |
+
s2 = set(sum_of_squares(i, 5))
|
| 917 |
+
assert all(sum(j**2 for j in t) == i for t in s2)
|
| 918 |
+
|
| 919 |
+
raises(ValueError, lambda: list(sum_of_powers(2, -1, 1)))
|
| 920 |
+
raises(ValueError, lambda: list(sum_of_powers(2, 1, -1)))
|
| 921 |
+
assert list(sum_of_powers(-2, 3, 2)) == [(-1, -1)]
|
| 922 |
+
assert list(sum_of_powers(-2, 4, 2)) == []
|
| 923 |
+
assert list(sum_of_powers(2, 1, 1)) == [(2,)]
|
| 924 |
+
assert list(sum_of_powers(2, 1, 3, True)) == [(0, 0, 2), (0, 1, 1)]
|
| 925 |
+
assert list(sum_of_powers(5, 1, 2, True)) == [(0, 5), (1, 4), (2, 3)]
|
| 926 |
+
assert list(sum_of_powers(6, 2, 2)) == []
|
| 927 |
+
assert list(sum_of_powers(3**5, 3, 1)) == []
|
| 928 |
+
assert list(sum_of_powers(3**6, 3, 1)) == [(9,)] and (9**3 == 3**6)
|
| 929 |
+
assert list(sum_of_powers(2**1000, 5, 2)) == []
|
| 930 |
+
|
| 931 |
+
|
| 932 |
+
def test__can_do_sum_of_squares():
|
| 933 |
+
assert _can_do_sum_of_squares(3, -1) is False
|
| 934 |
+
assert _can_do_sum_of_squares(-3, 1) is False
|
| 935 |
+
assert _can_do_sum_of_squares(0, 1)
|
| 936 |
+
assert _can_do_sum_of_squares(4, 1)
|
| 937 |
+
assert _can_do_sum_of_squares(1, 2)
|
| 938 |
+
assert _can_do_sum_of_squares(2, 2)
|
| 939 |
+
assert _can_do_sum_of_squares(3, 2) is False
|
| 940 |
+
|
| 941 |
+
|
| 942 |
+
def test_diophantine_permute_sign():
|
| 943 |
+
from sympy.abc import a, b, c, d, e
|
| 944 |
+
eq = a**4 + b**4 - (2**4 + 3**4)
|
| 945 |
+
base_sol = {(2, 3)}
|
| 946 |
+
assert diophantine(eq) == base_sol
|
| 947 |
+
complete_soln = set(signed_permutations(base_sol.pop()))
|
| 948 |
+
assert diophantine(eq, permute=True) == complete_soln
|
| 949 |
+
|
| 950 |
+
eq = a**2 + b**2 + c**2 + d**2 + e**2 - 234
|
| 951 |
+
assert len(diophantine(eq)) == 35
|
| 952 |
+
assert len(diophantine(eq, permute=True)) == 62000
|
| 953 |
+
soln = {(-1, -1), (-1, 2), (1, -2), (1, 1)}
|
| 954 |
+
assert diophantine(10*x**2 + 12*x*y + 12*y**2 - 34, permute=True) == soln
|
| 955 |
+
|
| 956 |
+
|
| 957 |
+
@XFAIL
|
| 958 |
+
def test_not_implemented():
|
| 959 |
+
eq = x**2 + y**4 - 1**2 - 3**4
|
| 960 |
+
assert diophantine(eq, syms=[x, y]) == {(9, 1), (1, 3)}
|
| 961 |
+
|
| 962 |
+
|
| 963 |
+
def test_issue_9538():
|
| 964 |
+
eq = x - 3*y + 2
|
| 965 |
+
assert diophantine(eq, syms=[y,x]) == {(t_0, 3*t_0 - 2)}
|
| 966 |
+
raises(TypeError, lambda: diophantine(eq, syms={y, x}))
|
| 967 |
+
|
| 968 |
+
|
| 969 |
+
def test_ternary_quadratic():
|
| 970 |
+
# solution with 3 parameters
|
| 971 |
+
s = diophantine(2*x**2 + y**2 - 2*z**2)
|
| 972 |
+
p, q, r = ordered(S(s).free_symbols)
|
| 973 |
+
assert s == {(
|
| 974 |
+
p**2 - 2*q**2,
|
| 975 |
+
-2*p**2 + 4*p*q - 4*p*r - 4*q**2,
|
| 976 |
+
p**2 - 4*p*q + 2*q**2 - 4*q*r)}
|
| 977 |
+
# solution with Mul in solution
|
| 978 |
+
s = diophantine(x**2 + 2*y**2 - 2*z**2)
|
| 979 |
+
assert s == {(4*p*q, p**2 - 2*q**2, p**2 + 2*q**2)}
|
| 980 |
+
# solution with no Mul in solution
|
| 981 |
+
s = diophantine(2*x**2 + 2*y**2 - z**2)
|
| 982 |
+
assert s == {(2*p**2 - q**2, -2*p**2 + 4*p*q - q**2,
|
| 983 |
+
4*p**2 - 4*p*q + 2*q**2)}
|
| 984 |
+
# reduced form when parametrized
|
| 985 |
+
s = diophantine(3*x**2 + 72*y**2 - 27*z**2)
|
| 986 |
+
assert s == {(24*p**2 - 9*q**2, 6*p*q, 8*p**2 + 3*q**2)}
|
| 987 |
+
assert parametrize_ternary_quadratic(
|
| 988 |
+
3*x**2 + 2*y**2 - z**2 - 2*x*y + 5*y*z - 7*y*z) == (
|
| 989 |
+
2*p**2 - 2*p*q - q**2, 2*p**2 + 2*p*q - q**2, 2*p**2 -
|
| 990 |
+
2*p*q + 3*q**2)
|
| 991 |
+
assert parametrize_ternary_quadratic(
|
| 992 |
+
124*x**2 - 30*y**2 - 7729*z**2) == (
|
| 993 |
+
-1410*p**2 - 363263*q**2, 2700*p**2 + 30916*p*q -
|
| 994 |
+
695610*q**2, -60*p**2 + 5400*p*q + 15458*q**2)
|
| 995 |
+
|
| 996 |
+
|
| 997 |
+
def test_diophantine_solution_set():
|
| 998 |
+
s1 = DiophantineSolutionSet([], [])
|
| 999 |
+
assert set(s1) == set()
|
| 1000 |
+
assert s1.symbols == ()
|
| 1001 |
+
assert s1.parameters == ()
|
| 1002 |
+
raises(ValueError, lambda: s1.add((x,)))
|
| 1003 |
+
assert list(s1.dict_iterator()) == []
|
| 1004 |
+
|
| 1005 |
+
s2 = DiophantineSolutionSet([x, y], [t, u])
|
| 1006 |
+
assert s2.symbols == (x, y)
|
| 1007 |
+
assert s2.parameters == (t, u)
|
| 1008 |
+
raises(ValueError, lambda: s2.add((1,)))
|
| 1009 |
+
s2.add((3, 4))
|
| 1010 |
+
assert set(s2) == {(3, 4)}
|
| 1011 |
+
s2.update((3, 4), (-1, u))
|
| 1012 |
+
assert set(s2) == {(3, 4), (-1, u)}
|
| 1013 |
+
raises(ValueError, lambda: s1.update(s2))
|
| 1014 |
+
assert list(s2.dict_iterator()) == [{x: -1, y: u}, {x: 3, y: 4}]
|
| 1015 |
+
|
| 1016 |
+
s3 = DiophantineSolutionSet([x, y, z], [t, u])
|
| 1017 |
+
assert len(s3.parameters) == 2
|
| 1018 |
+
s3.add((t**2 + u, t - u, 1))
|
| 1019 |
+
assert set(s3) == {(t**2 + u, t - u, 1)}
|
| 1020 |
+
assert s3.subs(t, 2) == {(u + 4, 2 - u, 1)}
|
| 1021 |
+
assert s3(2) == {(u + 4, 2 - u, 1)}
|
| 1022 |
+
assert s3.subs({t: 7, u: 8}) == {(57, -1, 1)}
|
| 1023 |
+
assert s3(7, 8) == {(57, -1, 1)}
|
| 1024 |
+
assert s3.subs({t: 5}) == {(u + 25, 5 - u, 1)}
|
| 1025 |
+
assert s3(5) == {(u + 25, 5 - u, 1)}
|
| 1026 |
+
assert s3.subs(u, -3) == {(t**2 - 3, t + 3, 1)}
|
| 1027 |
+
assert s3(None, -3) == {(t**2 - 3, t + 3, 1)}
|
| 1028 |
+
assert s3.subs({t: 2, u: 8}) == {(12, -6, 1)}
|
| 1029 |
+
assert s3(2, 8) == {(12, -6, 1)}
|
| 1030 |
+
assert s3.subs({t: 5, u: -3}) == {(22, 8, 1)}
|
| 1031 |
+
assert s3(5, -3) == {(22, 8, 1)}
|
| 1032 |
+
raises(ValueError, lambda: s3.subs(x=1))
|
| 1033 |
+
raises(ValueError, lambda: s3.subs(1, 2, 3))
|
| 1034 |
+
raises(ValueError, lambda: s3.add(()))
|
| 1035 |
+
raises(ValueError, lambda: s3.add((1, 2, 3, 4)))
|
| 1036 |
+
raises(ValueError, lambda: s3.add((1, 2)))
|
| 1037 |
+
raises(ValueError, lambda: s3(1, 2, 3))
|
| 1038 |
+
raises(TypeError, lambda: s3(t=1))
|
| 1039 |
+
|
| 1040 |
+
s4 = DiophantineSolutionSet([x, y], [t, u])
|
| 1041 |
+
s4.add((t, 11*t))
|
| 1042 |
+
s4.add((-t, 22*t))
|
| 1043 |
+
assert s4(0, 0) == {(0, 0)}
|
| 1044 |
+
|
| 1045 |
+
|
| 1046 |
+
def test_quadratic_parameter_passing():
|
| 1047 |
+
eq = -33*x*y + 3*y**2
|
| 1048 |
+
solution = BinaryQuadratic(eq).solve(parameters=[t, u])
|
| 1049 |
+
# test that parameters are passed all the way to the final solution
|
| 1050 |
+
assert solution == {(t, 11*t), (t, -22*t)}
|
| 1051 |
+
assert solution(0, 0) == {(0, 0)}
|
evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/inequalities.py
ADDED
|
@@ -0,0 +1,986 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tools for solving inequalities and systems of inequalities. """
|
| 2 |
+
import itertools
|
| 3 |
+
|
| 4 |
+
from sympy.calculus.util import (continuous_domain, periodicity,
|
| 5 |
+
function_range)
|
| 6 |
+
from sympy.core import sympify
|
| 7 |
+
from sympy.core.exprtools import factor_terms
|
| 8 |
+
from sympy.core.relational import Relational, Lt, Ge, Eq
|
| 9 |
+
from sympy.core.symbol import Symbol, Dummy
|
| 10 |
+
from sympy.sets.sets import Interval, FiniteSet, Union, Intersection
|
| 11 |
+
from sympy.core.singleton import S
|
| 12 |
+
from sympy.core.function import expand_mul
|
| 13 |
+
from sympy.functions.elementary.complexes import Abs
|
| 14 |
+
from sympy.logic import And
|
| 15 |
+
from sympy.polys import Poly, PolynomialError, parallel_poly_from_expr
|
| 16 |
+
from sympy.polys.polyutils import _nsort
|
| 17 |
+
from sympy.solvers.solveset import solvify, solveset
|
| 18 |
+
from sympy.utilities.iterables import sift, iterable
|
| 19 |
+
from sympy.utilities.misc import filldedent
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def solve_poly_inequality(poly, rel):
|
| 23 |
+
"""Solve a polynomial inequality with rational coefficients.
|
| 24 |
+
|
| 25 |
+
Examples
|
| 26 |
+
========
|
| 27 |
+
|
| 28 |
+
>>> from sympy import solve_poly_inequality, Poly
|
| 29 |
+
>>> from sympy.abc import x
|
| 30 |
+
|
| 31 |
+
>>> solve_poly_inequality(Poly(x, x, domain='ZZ'), '==')
|
| 32 |
+
[{0}]
|
| 33 |
+
|
| 34 |
+
>>> solve_poly_inequality(Poly(x**2 - 1, x, domain='ZZ'), '!=')
|
| 35 |
+
[Interval.open(-oo, -1), Interval.open(-1, 1), Interval.open(1, oo)]
|
| 36 |
+
|
| 37 |
+
>>> solve_poly_inequality(Poly(x**2 - 1, x, domain='ZZ'), '==')
|
| 38 |
+
[{-1}, {1}]
|
| 39 |
+
|
| 40 |
+
See Also
|
| 41 |
+
========
|
| 42 |
+
solve_poly_inequalities
|
| 43 |
+
"""
|
| 44 |
+
if not isinstance(poly, Poly):
|
| 45 |
+
raise ValueError(
|
| 46 |
+
'For efficiency reasons, `poly` should be a Poly instance')
|
| 47 |
+
if poly.as_expr().is_number:
|
| 48 |
+
t = Relational(poly.as_expr(), 0, rel)
|
| 49 |
+
if t is S.true:
|
| 50 |
+
return [S.Reals]
|
| 51 |
+
elif t is S.false:
|
| 52 |
+
return [S.EmptySet]
|
| 53 |
+
else:
|
| 54 |
+
raise NotImplementedError(
|
| 55 |
+
"could not determine truth value of %s" % t)
|
| 56 |
+
|
| 57 |
+
reals, intervals = poly.real_roots(multiple=False), []
|
| 58 |
+
|
| 59 |
+
if rel == '==':
|
| 60 |
+
for root, _ in reals:
|
| 61 |
+
interval = Interval(root, root)
|
| 62 |
+
intervals.append(interval)
|
| 63 |
+
elif rel == '!=':
|
| 64 |
+
left = S.NegativeInfinity
|
| 65 |
+
|
| 66 |
+
for right, _ in reals + [(S.Infinity, 1)]:
|
| 67 |
+
interval = Interval(left, right, True, True)
|
| 68 |
+
intervals.append(interval)
|
| 69 |
+
left = right
|
| 70 |
+
else:
|
| 71 |
+
if poly.LC() > 0:
|
| 72 |
+
sign = +1
|
| 73 |
+
else:
|
| 74 |
+
sign = -1
|
| 75 |
+
|
| 76 |
+
eq_sign, equal = None, False
|
| 77 |
+
|
| 78 |
+
if rel == '>':
|
| 79 |
+
eq_sign = +1
|
| 80 |
+
elif rel == '<':
|
| 81 |
+
eq_sign = -1
|
| 82 |
+
elif rel == '>=':
|
| 83 |
+
eq_sign, equal = +1, True
|
| 84 |
+
elif rel == '<=':
|
| 85 |
+
eq_sign, equal = -1, True
|
| 86 |
+
else:
|
| 87 |
+
raise ValueError("'%s' is not a valid relation" % rel)
|
| 88 |
+
|
| 89 |
+
right, right_open = S.Infinity, True
|
| 90 |
+
|
| 91 |
+
for left, multiplicity in reversed(reals):
|
| 92 |
+
if multiplicity % 2:
|
| 93 |
+
if sign == eq_sign:
|
| 94 |
+
intervals.insert(
|
| 95 |
+
0, Interval(left, right, not equal, right_open))
|
| 96 |
+
|
| 97 |
+
sign, right, right_open = -sign, left, not equal
|
| 98 |
+
else:
|
| 99 |
+
if sign == eq_sign and not equal:
|
| 100 |
+
intervals.insert(
|
| 101 |
+
0, Interval(left, right, True, right_open))
|
| 102 |
+
right, right_open = left, True
|
| 103 |
+
elif sign != eq_sign and equal:
|
| 104 |
+
intervals.insert(0, Interval(left, left))
|
| 105 |
+
|
| 106 |
+
if sign == eq_sign:
|
| 107 |
+
intervals.insert(
|
| 108 |
+
0, Interval(S.NegativeInfinity, right, True, right_open))
|
| 109 |
+
|
| 110 |
+
return intervals
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def solve_poly_inequalities(polys):
|
| 114 |
+
"""Solve polynomial inequalities with rational coefficients.
|
| 115 |
+
|
| 116 |
+
Examples
|
| 117 |
+
========
|
| 118 |
+
|
| 119 |
+
>>> from sympy import Poly
|
| 120 |
+
>>> from sympy.solvers.inequalities import solve_poly_inequalities
|
| 121 |
+
>>> from sympy.abc import x
|
| 122 |
+
>>> solve_poly_inequalities(((
|
| 123 |
+
... Poly(x**2 - 3), ">"), (
|
| 124 |
+
... Poly(-x**2 + 1), ">")))
|
| 125 |
+
Union(Interval.open(-oo, -sqrt(3)), Interval.open(-1, 1), Interval.open(sqrt(3), oo))
|
| 126 |
+
"""
|
| 127 |
+
return Union(*[s for p in polys for s in solve_poly_inequality(*p)])
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def solve_rational_inequalities(eqs):
|
| 131 |
+
"""Solve a system of rational inequalities with rational coefficients.
|
| 132 |
+
|
| 133 |
+
Examples
|
| 134 |
+
========
|
| 135 |
+
|
| 136 |
+
>>> from sympy.abc import x
|
| 137 |
+
>>> from sympy import solve_rational_inequalities, Poly
|
| 138 |
+
|
| 139 |
+
>>> solve_rational_inequalities([[
|
| 140 |
+
... ((Poly(-x + 1), Poly(1, x)), '>='),
|
| 141 |
+
... ((Poly(-x + 1), Poly(1, x)), '<=')]])
|
| 142 |
+
{1}
|
| 143 |
+
|
| 144 |
+
>>> solve_rational_inequalities([[
|
| 145 |
+
... ((Poly(x), Poly(1, x)), '!='),
|
| 146 |
+
... ((Poly(-x + 1), Poly(1, x)), '>=')]])
|
| 147 |
+
Union(Interval.open(-oo, 0), Interval.Lopen(0, 1))
|
| 148 |
+
|
| 149 |
+
See Also
|
| 150 |
+
========
|
| 151 |
+
solve_poly_inequality
|
| 152 |
+
"""
|
| 153 |
+
result = S.EmptySet
|
| 154 |
+
|
| 155 |
+
for _eqs in eqs:
|
| 156 |
+
if not _eqs:
|
| 157 |
+
continue
|
| 158 |
+
|
| 159 |
+
global_intervals = [Interval(S.NegativeInfinity, S.Infinity)]
|
| 160 |
+
|
| 161 |
+
for (numer, denom), rel in _eqs:
|
| 162 |
+
numer_intervals = solve_poly_inequality(numer*denom, rel)
|
| 163 |
+
denom_intervals = solve_poly_inequality(denom, '==')
|
| 164 |
+
|
| 165 |
+
intervals = []
|
| 166 |
+
|
| 167 |
+
for numer_interval, global_interval in itertools.product(
|
| 168 |
+
numer_intervals, global_intervals):
|
| 169 |
+
interval = numer_interval.intersect(global_interval)
|
| 170 |
+
|
| 171 |
+
if interval is not S.EmptySet:
|
| 172 |
+
intervals.append(interval)
|
| 173 |
+
|
| 174 |
+
global_intervals = intervals
|
| 175 |
+
|
| 176 |
+
intervals = []
|
| 177 |
+
|
| 178 |
+
for global_interval in global_intervals:
|
| 179 |
+
for denom_interval in denom_intervals:
|
| 180 |
+
global_interval -= denom_interval
|
| 181 |
+
|
| 182 |
+
if global_interval is not S.EmptySet:
|
| 183 |
+
intervals.append(global_interval)
|
| 184 |
+
|
| 185 |
+
global_intervals = intervals
|
| 186 |
+
|
| 187 |
+
if not global_intervals:
|
| 188 |
+
break
|
| 189 |
+
|
| 190 |
+
for interval in global_intervals:
|
| 191 |
+
result = result.union(interval)
|
| 192 |
+
|
| 193 |
+
return result
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def reduce_rational_inequalities(exprs, gen, relational=True):
|
| 197 |
+
"""Reduce a system of rational inequalities with rational coefficients.
|
| 198 |
+
|
| 199 |
+
Examples
|
| 200 |
+
========
|
| 201 |
+
|
| 202 |
+
>>> from sympy import Symbol
|
| 203 |
+
>>> from sympy.solvers.inequalities import reduce_rational_inequalities
|
| 204 |
+
|
| 205 |
+
>>> x = Symbol('x', real=True)
|
| 206 |
+
|
| 207 |
+
>>> reduce_rational_inequalities([[x**2 <= 0]], x)
|
| 208 |
+
Eq(x, 0)
|
| 209 |
+
|
| 210 |
+
>>> reduce_rational_inequalities([[x + 2 > 0]], x)
|
| 211 |
+
-2 < x
|
| 212 |
+
>>> reduce_rational_inequalities([[(x + 2, ">")]], x)
|
| 213 |
+
-2 < x
|
| 214 |
+
>>> reduce_rational_inequalities([[x + 2]], x)
|
| 215 |
+
Eq(x, -2)
|
| 216 |
+
|
| 217 |
+
This function find the non-infinite solution set so if the unknown symbol
|
| 218 |
+
is declared as extended real rather than real then the result may include
|
| 219 |
+
finiteness conditions:
|
| 220 |
+
|
| 221 |
+
>>> y = Symbol('y', extended_real=True)
|
| 222 |
+
>>> reduce_rational_inequalities([[y + 2 > 0]], y)
|
| 223 |
+
(-2 < y) & (y < oo)
|
| 224 |
+
"""
|
| 225 |
+
exact = True
|
| 226 |
+
eqs = []
|
| 227 |
+
solution = S.EmptySet # add pieces for each group
|
| 228 |
+
for _exprs in exprs:
|
| 229 |
+
if not _exprs:
|
| 230 |
+
continue
|
| 231 |
+
_eqs = []
|
| 232 |
+
_sol = S.Reals
|
| 233 |
+
for expr in _exprs:
|
| 234 |
+
if isinstance(expr, tuple):
|
| 235 |
+
expr, rel = expr
|
| 236 |
+
else:
|
| 237 |
+
if expr.is_Relational:
|
| 238 |
+
expr, rel = expr.lhs - expr.rhs, expr.rel_op
|
| 239 |
+
else:
|
| 240 |
+
expr, rel = expr, '=='
|
| 241 |
+
|
| 242 |
+
if expr is S.true:
|
| 243 |
+
numer, denom, rel = S.Zero, S.One, '=='
|
| 244 |
+
elif expr is S.false:
|
| 245 |
+
numer, denom, rel = S.One, S.One, '=='
|
| 246 |
+
else:
|
| 247 |
+
numer, denom = expr.together().as_numer_denom()
|
| 248 |
+
|
| 249 |
+
try:
|
| 250 |
+
(numer, denom), opt = parallel_poly_from_expr(
|
| 251 |
+
(numer, denom), gen)
|
| 252 |
+
except PolynomialError:
|
| 253 |
+
raise PolynomialError(filldedent('''
|
| 254 |
+
only polynomials and rational functions are
|
| 255 |
+
supported in this context.
|
| 256 |
+
'''))
|
| 257 |
+
|
| 258 |
+
if not opt.domain.is_Exact:
|
| 259 |
+
numer, denom, exact = numer.to_exact(), denom.to_exact(), False
|
| 260 |
+
|
| 261 |
+
domain = opt.domain.get_exact()
|
| 262 |
+
|
| 263 |
+
if not (domain.is_ZZ or domain.is_QQ):
|
| 264 |
+
expr = numer/denom
|
| 265 |
+
expr = Relational(expr, 0, rel)
|
| 266 |
+
_sol &= solve_univariate_inequality(expr, gen, relational=False)
|
| 267 |
+
else:
|
| 268 |
+
_eqs.append(((numer, denom), rel))
|
| 269 |
+
|
| 270 |
+
if _eqs:
|
| 271 |
+
_sol &= solve_rational_inequalities([_eqs])
|
| 272 |
+
exclude = solve_rational_inequalities([[((d, d.one), '==')
|
| 273 |
+
for i in eqs for ((n, d), _) in i if d.has(gen)]])
|
| 274 |
+
_sol -= exclude
|
| 275 |
+
|
| 276 |
+
solution |= _sol
|
| 277 |
+
|
| 278 |
+
if not exact and solution:
|
| 279 |
+
solution = solution.evalf()
|
| 280 |
+
|
| 281 |
+
if relational:
|
| 282 |
+
solution = solution.as_relational(gen)
|
| 283 |
+
|
| 284 |
+
return solution
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
def reduce_abs_inequality(expr, rel, gen):
|
| 288 |
+
"""Reduce an inequality with nested absolute values.
|
| 289 |
+
|
| 290 |
+
Examples
|
| 291 |
+
========
|
| 292 |
+
|
| 293 |
+
>>> from sympy import reduce_abs_inequality, Abs, Symbol
|
| 294 |
+
>>> x = Symbol('x', real=True)
|
| 295 |
+
|
| 296 |
+
>>> reduce_abs_inequality(Abs(x - 5) - 3, '<', x)
|
| 297 |
+
(2 < x) & (x < 8)
|
| 298 |
+
|
| 299 |
+
>>> reduce_abs_inequality(Abs(x + 2)*3 - 13, '<', x)
|
| 300 |
+
(-19/3 < x) & (x < 7/3)
|
| 301 |
+
|
| 302 |
+
See Also
|
| 303 |
+
========
|
| 304 |
+
|
| 305 |
+
reduce_abs_inequalities
|
| 306 |
+
"""
|
| 307 |
+
if gen.is_extended_real is False:
|
| 308 |
+
raise TypeError(filldedent('''
|
| 309 |
+
Cannot solve inequalities with absolute values containing
|
| 310 |
+
non-real variables.
|
| 311 |
+
'''))
|
| 312 |
+
|
| 313 |
+
def _bottom_up_scan(expr):
|
| 314 |
+
exprs = []
|
| 315 |
+
|
| 316 |
+
if expr.is_Add or expr.is_Mul:
|
| 317 |
+
op = expr.func
|
| 318 |
+
|
| 319 |
+
for arg in expr.args:
|
| 320 |
+
_exprs = _bottom_up_scan(arg)
|
| 321 |
+
|
| 322 |
+
if not exprs:
|
| 323 |
+
exprs = _exprs
|
| 324 |
+
else:
|
| 325 |
+
exprs = [(op(expr, _expr), conds + _conds) for (expr, conds), (_expr, _conds) in
|
| 326 |
+
itertools.product(exprs, _exprs)]
|
| 327 |
+
elif expr.is_Pow:
|
| 328 |
+
n = expr.exp
|
| 329 |
+
if not n.is_Integer:
|
| 330 |
+
raise ValueError("Only Integer Powers are allowed on Abs.")
|
| 331 |
+
|
| 332 |
+
exprs.extend((expr**n, conds) for expr, conds in _bottom_up_scan(expr.base))
|
| 333 |
+
elif isinstance(expr, Abs):
|
| 334 |
+
_exprs = _bottom_up_scan(expr.args[0])
|
| 335 |
+
|
| 336 |
+
for expr, conds in _exprs:
|
| 337 |
+
exprs.append(( expr, conds + [Ge(expr, 0)]))
|
| 338 |
+
exprs.append((-expr, conds + [Lt(expr, 0)]))
|
| 339 |
+
else:
|
| 340 |
+
exprs = [(expr, [])]
|
| 341 |
+
|
| 342 |
+
return exprs
|
| 343 |
+
|
| 344 |
+
mapping = {'<': '>', '<=': '>='}
|
| 345 |
+
inequalities = []
|
| 346 |
+
|
| 347 |
+
for expr, conds in _bottom_up_scan(expr):
|
| 348 |
+
if rel not in mapping.keys():
|
| 349 |
+
expr = Relational( expr, 0, rel)
|
| 350 |
+
else:
|
| 351 |
+
expr = Relational(-expr, 0, mapping[rel])
|
| 352 |
+
|
| 353 |
+
inequalities.append([expr] + conds)
|
| 354 |
+
|
| 355 |
+
return reduce_rational_inequalities(inequalities, gen)
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
def reduce_abs_inequalities(exprs, gen):
|
| 359 |
+
"""Reduce a system of inequalities with nested absolute values.
|
| 360 |
+
|
| 361 |
+
Examples
|
| 362 |
+
========
|
| 363 |
+
|
| 364 |
+
>>> from sympy import reduce_abs_inequalities, Abs, Symbol
|
| 365 |
+
>>> x = Symbol('x', extended_real=True)
|
| 366 |
+
|
| 367 |
+
>>> reduce_abs_inequalities([(Abs(3*x - 5) - 7, '<'),
|
| 368 |
+
... (Abs(x + 25) - 13, '>')], x)
|
| 369 |
+
(-2/3 < x) & (x < 4) & (((-oo < x) & (x < -38)) | ((-12 < x) & (x < oo)))
|
| 370 |
+
|
| 371 |
+
>>> reduce_abs_inequalities([(Abs(x - 4) + Abs(3*x - 5) - 7, '<')], x)
|
| 372 |
+
(1/2 < x) & (x < 4)
|
| 373 |
+
|
| 374 |
+
See Also
|
| 375 |
+
========
|
| 376 |
+
|
| 377 |
+
reduce_abs_inequality
|
| 378 |
+
"""
|
| 379 |
+
return And(*[ reduce_abs_inequality(expr, rel, gen)
|
| 380 |
+
for expr, rel in exprs ])
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
def solve_univariate_inequality(expr, gen, relational=True, domain=S.Reals, continuous=False):
|
| 384 |
+
"""Solves a real univariate inequality.
|
| 385 |
+
|
| 386 |
+
Parameters
|
| 387 |
+
==========
|
| 388 |
+
|
| 389 |
+
expr : Relational
|
| 390 |
+
The target inequality
|
| 391 |
+
gen : Symbol
|
| 392 |
+
The variable for which the inequality is solved
|
| 393 |
+
relational : bool
|
| 394 |
+
A Relational type output is expected or not
|
| 395 |
+
domain : Set
|
| 396 |
+
The domain over which the equation is solved
|
| 397 |
+
continuous: bool
|
| 398 |
+
True if expr is known to be continuous over the given domain
|
| 399 |
+
(and so continuous_domain() does not need to be called on it)
|
| 400 |
+
|
| 401 |
+
Raises
|
| 402 |
+
======
|
| 403 |
+
|
| 404 |
+
NotImplementedError
|
| 405 |
+
The solution of the inequality cannot be determined due to limitation
|
| 406 |
+
in :func:`sympy.solvers.solveset.solvify`.
|
| 407 |
+
|
| 408 |
+
Notes
|
| 409 |
+
=====
|
| 410 |
+
|
| 411 |
+
Currently, we cannot solve all the inequalities due to limitations in
|
| 412 |
+
:func:`sympy.solvers.solveset.solvify`. Also, the solution returned for trigonometric inequalities
|
| 413 |
+
are restricted in its periodic interval.
|
| 414 |
+
|
| 415 |
+
See Also
|
| 416 |
+
========
|
| 417 |
+
|
| 418 |
+
sympy.solvers.solveset.solvify: solver returning solveset solutions with solve's output API
|
| 419 |
+
|
| 420 |
+
Examples
|
| 421 |
+
========
|
| 422 |
+
|
| 423 |
+
>>> from sympy import solve_univariate_inequality, Symbol, sin, Interval, S
|
| 424 |
+
>>> x = Symbol('x')
|
| 425 |
+
|
| 426 |
+
>>> solve_univariate_inequality(x**2 >= 4, x)
|
| 427 |
+
((2 <= x) & (x < oo)) | ((-oo < x) & (x <= -2))
|
| 428 |
+
|
| 429 |
+
>>> solve_univariate_inequality(x**2 >= 4, x, relational=False)
|
| 430 |
+
Union(Interval(-oo, -2), Interval(2, oo))
|
| 431 |
+
|
| 432 |
+
>>> domain = Interval(0, S.Infinity)
|
| 433 |
+
>>> solve_univariate_inequality(x**2 >= 4, x, False, domain)
|
| 434 |
+
Interval(2, oo)
|
| 435 |
+
|
| 436 |
+
>>> solve_univariate_inequality(sin(x) > 0, x, relational=False)
|
| 437 |
+
Interval.open(0, pi)
|
| 438 |
+
|
| 439 |
+
"""
|
| 440 |
+
from sympy.solvers.solvers import denoms
|
| 441 |
+
|
| 442 |
+
if domain.is_subset(S.Reals) is False:
|
| 443 |
+
raise NotImplementedError(filldedent('''
|
| 444 |
+
Inequalities in the complex domain are
|
| 445 |
+
not supported. Try the real domain by
|
| 446 |
+
setting domain=S.Reals'''))
|
| 447 |
+
elif domain is not S.Reals:
|
| 448 |
+
rv = solve_univariate_inequality(
|
| 449 |
+
expr, gen, relational=False, continuous=continuous).intersection(domain)
|
| 450 |
+
if relational:
|
| 451 |
+
rv = rv.as_relational(gen)
|
| 452 |
+
return rv
|
| 453 |
+
else:
|
| 454 |
+
pass # continue with attempt to solve in Real domain
|
| 455 |
+
|
| 456 |
+
# This keeps the function independent of the assumptions about `gen`.
|
| 457 |
+
# `solveset` makes sure this function is called only when the domain is
|
| 458 |
+
# real.
|
| 459 |
+
_gen = gen
|
| 460 |
+
_domain = domain
|
| 461 |
+
if gen.is_extended_real is False:
|
| 462 |
+
rv = S.EmptySet
|
| 463 |
+
return rv if not relational else rv.as_relational(_gen)
|
| 464 |
+
elif gen.is_extended_real is None:
|
| 465 |
+
gen = Dummy('gen', extended_real=True)
|
| 466 |
+
try:
|
| 467 |
+
expr = expr.xreplace({_gen: gen})
|
| 468 |
+
except TypeError:
|
| 469 |
+
raise TypeError(filldedent('''
|
| 470 |
+
When gen is real, the relational has a complex part
|
| 471 |
+
which leads to an invalid comparison like I < 0.
|
| 472 |
+
'''))
|
| 473 |
+
|
| 474 |
+
rv = None
|
| 475 |
+
|
| 476 |
+
if expr is S.true:
|
| 477 |
+
rv = domain
|
| 478 |
+
|
| 479 |
+
elif expr is S.false:
|
| 480 |
+
rv = S.EmptySet
|
| 481 |
+
|
| 482 |
+
else:
|
| 483 |
+
e = expr.lhs - expr.rhs
|
| 484 |
+
period = periodicity(e, gen)
|
| 485 |
+
if period == S.Zero:
|
| 486 |
+
e = expand_mul(e)
|
| 487 |
+
const = expr.func(e, 0)
|
| 488 |
+
if const is S.true:
|
| 489 |
+
rv = domain
|
| 490 |
+
elif const is S.false:
|
| 491 |
+
rv = S.EmptySet
|
| 492 |
+
elif period is not None:
|
| 493 |
+
frange = function_range(e, gen, domain)
|
| 494 |
+
|
| 495 |
+
rel = expr.rel_op
|
| 496 |
+
if rel in ('<', '<='):
|
| 497 |
+
if expr.func(frange.sup, 0):
|
| 498 |
+
rv = domain
|
| 499 |
+
elif not expr.func(frange.inf, 0):
|
| 500 |
+
rv = S.EmptySet
|
| 501 |
+
|
| 502 |
+
elif rel in ('>', '>='):
|
| 503 |
+
if expr.func(frange.inf, 0):
|
| 504 |
+
rv = domain
|
| 505 |
+
elif not expr.func(frange.sup, 0):
|
| 506 |
+
rv = S.EmptySet
|
| 507 |
+
|
| 508 |
+
inf, sup = domain.inf, domain.sup
|
| 509 |
+
if sup - inf is S.Infinity:
|
| 510 |
+
domain = Interval(0, period, False, True).intersect(_domain)
|
| 511 |
+
_domain = domain
|
| 512 |
+
|
| 513 |
+
if rv is None:
|
| 514 |
+
n, d = e.as_numer_denom()
|
| 515 |
+
try:
|
| 516 |
+
if gen not in n.free_symbols and len(e.free_symbols) > 1:
|
| 517 |
+
raise ValueError
|
| 518 |
+
# this might raise ValueError on its own
|
| 519 |
+
# or it might give None...
|
| 520 |
+
solns = solvify(e, gen, domain)
|
| 521 |
+
if solns is None:
|
| 522 |
+
# in which case we raise ValueError
|
| 523 |
+
raise ValueError
|
| 524 |
+
except (ValueError, NotImplementedError):
|
| 525 |
+
# replace gen with generic x since it's
|
| 526 |
+
# univariate anyway
|
| 527 |
+
raise NotImplementedError(filldedent('''
|
| 528 |
+
The inequality, %s, cannot be solved using
|
| 529 |
+
solve_univariate_inequality.
|
| 530 |
+
''' % expr.subs(gen, Symbol('x'))))
|
| 531 |
+
|
| 532 |
+
expanded_e = expand_mul(e)
|
| 533 |
+
def valid(x):
|
| 534 |
+
# this is used to see if gen=x satisfies the
|
| 535 |
+
# relational by substituting it into the
|
| 536 |
+
# expanded form and testing against 0, e.g.
|
| 537 |
+
# if expr = x*(x + 1) < 2 then e = x*(x + 1) - 2
|
| 538 |
+
# and expanded_e = x**2 + x - 2; the test is
|
| 539 |
+
# whether a given value of x satisfies
|
| 540 |
+
# x**2 + x - 2 < 0
|
| 541 |
+
#
|
| 542 |
+
# expanded_e, expr and gen used from enclosing scope
|
| 543 |
+
v = expanded_e.subs(gen, expand_mul(x))
|
| 544 |
+
try:
|
| 545 |
+
r = expr.func(v, 0)
|
| 546 |
+
except TypeError:
|
| 547 |
+
r = S.false
|
| 548 |
+
if r in (S.true, S.false):
|
| 549 |
+
return r
|
| 550 |
+
if v.is_extended_real is False:
|
| 551 |
+
return S.false
|
| 552 |
+
else:
|
| 553 |
+
v = v.n(2)
|
| 554 |
+
if v.is_comparable:
|
| 555 |
+
return expr.func(v, 0)
|
| 556 |
+
# not comparable or couldn't be evaluated
|
| 557 |
+
raise NotImplementedError(
|
| 558 |
+
'relationship did not evaluate: %s' % r)
|
| 559 |
+
|
| 560 |
+
singularities = []
|
| 561 |
+
for d in denoms(expr, gen):
|
| 562 |
+
singularities.extend(solvify(d, gen, domain))
|
| 563 |
+
if not continuous:
|
| 564 |
+
domain = continuous_domain(expanded_e, gen, domain)
|
| 565 |
+
|
| 566 |
+
include_x = '=' in expr.rel_op and expr.rel_op != '!='
|
| 567 |
+
|
| 568 |
+
try:
|
| 569 |
+
discontinuities = set(domain.boundary -
|
| 570 |
+
FiniteSet(domain.inf, domain.sup))
|
| 571 |
+
# remove points that are not between inf and sup of domain
|
| 572 |
+
critical_points = FiniteSet(*(solns + singularities + list(
|
| 573 |
+
discontinuities))).intersection(
|
| 574 |
+
Interval(domain.inf, domain.sup,
|
| 575 |
+
domain.inf not in domain, domain.sup not in domain))
|
| 576 |
+
if all(r.is_number for r in critical_points):
|
| 577 |
+
reals = _nsort(critical_points, separated=True)[0]
|
| 578 |
+
else:
|
| 579 |
+
sifted = sift(critical_points, lambda x: x.is_extended_real)
|
| 580 |
+
if sifted[None]:
|
| 581 |
+
# there were some roots that weren't known
|
| 582 |
+
# to be real
|
| 583 |
+
raise NotImplementedError
|
| 584 |
+
try:
|
| 585 |
+
reals = sifted[True]
|
| 586 |
+
if len(reals) > 1:
|
| 587 |
+
reals = sorted(reals)
|
| 588 |
+
except TypeError:
|
| 589 |
+
raise NotImplementedError
|
| 590 |
+
except NotImplementedError:
|
| 591 |
+
raise NotImplementedError('sorting of these roots is not supported')
|
| 592 |
+
|
| 593 |
+
# If expr contains imaginary coefficients, only take real
|
| 594 |
+
# values of x for which the imaginary part is 0
|
| 595 |
+
make_real = S.Reals
|
| 596 |
+
if (coeffI := expanded_e.coeff(S.ImaginaryUnit)) != S.Zero:
|
| 597 |
+
check = True
|
| 598 |
+
im_sol = FiniteSet()
|
| 599 |
+
try:
|
| 600 |
+
a = solveset(coeffI, gen, domain)
|
| 601 |
+
if not isinstance(a, Interval):
|
| 602 |
+
for z in a:
|
| 603 |
+
if z not in singularities and valid(z) and z.is_extended_real:
|
| 604 |
+
im_sol += FiniteSet(z)
|
| 605 |
+
else:
|
| 606 |
+
start, end = a.inf, a.sup
|
| 607 |
+
for z in _nsort(critical_points + FiniteSet(end)):
|
| 608 |
+
valid_start = valid(start)
|
| 609 |
+
if start != end:
|
| 610 |
+
valid_z = valid(z)
|
| 611 |
+
pt = _pt(start, z)
|
| 612 |
+
if pt not in singularities and pt.is_extended_real and valid(pt):
|
| 613 |
+
if valid_start and valid_z:
|
| 614 |
+
im_sol += Interval(start, z)
|
| 615 |
+
elif valid_start:
|
| 616 |
+
im_sol += Interval.Ropen(start, z)
|
| 617 |
+
elif valid_z:
|
| 618 |
+
im_sol += Interval.Lopen(start, z)
|
| 619 |
+
else:
|
| 620 |
+
im_sol += Interval.open(start, z)
|
| 621 |
+
start = z
|
| 622 |
+
for s in singularities:
|
| 623 |
+
im_sol -= FiniteSet(s)
|
| 624 |
+
except (TypeError):
|
| 625 |
+
im_sol = S.Reals
|
| 626 |
+
check = False
|
| 627 |
+
|
| 628 |
+
if im_sol is S.EmptySet:
|
| 629 |
+
raise ValueError(filldedent('''
|
| 630 |
+
%s contains imaginary parts which cannot be
|
| 631 |
+
made 0 for any value of %s satisfying the
|
| 632 |
+
inequality, leading to relations like I < 0.
|
| 633 |
+
''' % (expr.subs(gen, _gen), _gen)))
|
| 634 |
+
|
| 635 |
+
make_real = make_real.intersect(im_sol)
|
| 636 |
+
|
| 637 |
+
sol_sets = [S.EmptySet]
|
| 638 |
+
|
| 639 |
+
start = domain.inf
|
| 640 |
+
if start in domain and valid(start) and start.is_finite:
|
| 641 |
+
sol_sets.append(FiniteSet(start))
|
| 642 |
+
|
| 643 |
+
for x in reals:
|
| 644 |
+
end = x
|
| 645 |
+
|
| 646 |
+
if valid(_pt(start, end)):
|
| 647 |
+
sol_sets.append(Interval(start, end, True, True))
|
| 648 |
+
|
| 649 |
+
if x in singularities:
|
| 650 |
+
singularities.remove(x)
|
| 651 |
+
else:
|
| 652 |
+
if x in discontinuities:
|
| 653 |
+
discontinuities.remove(x)
|
| 654 |
+
_valid = valid(x)
|
| 655 |
+
else: # it's a solution
|
| 656 |
+
_valid = include_x
|
| 657 |
+
if _valid:
|
| 658 |
+
sol_sets.append(FiniteSet(x))
|
| 659 |
+
|
| 660 |
+
start = end
|
| 661 |
+
|
| 662 |
+
end = domain.sup
|
| 663 |
+
if end in domain and valid(end) and end.is_finite:
|
| 664 |
+
sol_sets.append(FiniteSet(end))
|
| 665 |
+
|
| 666 |
+
if valid(_pt(start, end)):
|
| 667 |
+
sol_sets.append(Interval.open(start, end))
|
| 668 |
+
|
| 669 |
+
if coeffI != S.Zero and check:
|
| 670 |
+
rv = (make_real).intersect(_domain)
|
| 671 |
+
else:
|
| 672 |
+
rv = Intersection(
|
| 673 |
+
(Union(*sol_sets)), make_real, _domain).subs(gen, _gen)
|
| 674 |
+
|
| 675 |
+
return rv if not relational else rv.as_relational(_gen)
|
| 676 |
+
|
| 677 |
+
|
| 678 |
+
def _pt(start, end):
|
| 679 |
+
"""Return a point between start and end"""
|
| 680 |
+
if not start.is_infinite and not end.is_infinite:
|
| 681 |
+
pt = (start + end)/2
|
| 682 |
+
elif start.is_infinite and end.is_infinite:
|
| 683 |
+
pt = S.Zero
|
| 684 |
+
else:
|
| 685 |
+
if (start.is_infinite and start.is_extended_positive is None or
|
| 686 |
+
end.is_infinite and end.is_extended_positive is None):
|
| 687 |
+
raise ValueError('cannot proceed with unsigned infinite values')
|
| 688 |
+
if (end.is_infinite and end.is_extended_negative or
|
| 689 |
+
start.is_infinite and start.is_extended_positive):
|
| 690 |
+
start, end = end, start
|
| 691 |
+
# if possible, use a multiple of self which has
|
| 692 |
+
# better behavior when checking assumptions than
|
| 693 |
+
# an expression obtained by adding or subtracting 1
|
| 694 |
+
if end.is_infinite:
|
| 695 |
+
if start.is_extended_positive:
|
| 696 |
+
pt = start*2
|
| 697 |
+
elif start.is_extended_negative:
|
| 698 |
+
pt = start*S.Half
|
| 699 |
+
else:
|
| 700 |
+
pt = start + 1
|
| 701 |
+
elif start.is_infinite:
|
| 702 |
+
if end.is_extended_positive:
|
| 703 |
+
pt = end*S.Half
|
| 704 |
+
elif end.is_extended_negative:
|
| 705 |
+
pt = end*2
|
| 706 |
+
else:
|
| 707 |
+
pt = end - 1
|
| 708 |
+
return pt
|
| 709 |
+
|
| 710 |
+
|
| 711 |
+
def _solve_inequality(ie, s, linear=False):
|
| 712 |
+
"""Return the inequality with s isolated on the left, if possible.
|
| 713 |
+
If the relationship is non-linear, a solution involving And or Or
|
| 714 |
+
may be returned. False or True are returned if the relationship
|
| 715 |
+
is never True or always True, respectively.
|
| 716 |
+
|
| 717 |
+
If `linear` is True (default is False) an `s`-dependent expression
|
| 718 |
+
will be isolated on the left, if possible
|
| 719 |
+
but it will not be solved for `s` unless the expression is linear
|
| 720 |
+
in `s`. Furthermore, only "safe" operations which do not change the
|
| 721 |
+
sense of the relationship are applied: no division by an unsigned
|
| 722 |
+
value is attempted unless the relationship involves Eq or Ne and
|
| 723 |
+
no division by a value not known to be nonzero is ever attempted.
|
| 724 |
+
|
| 725 |
+
Examples
|
| 726 |
+
========
|
| 727 |
+
|
| 728 |
+
>>> from sympy import Eq, Symbol
|
| 729 |
+
>>> from sympy.solvers.inequalities import _solve_inequality as f
|
| 730 |
+
>>> from sympy.abc import x, y
|
| 731 |
+
|
| 732 |
+
For linear expressions, the symbol can be isolated:
|
| 733 |
+
|
| 734 |
+
>>> f(x - 2 < 0, x)
|
| 735 |
+
x < 2
|
| 736 |
+
>>> f(-x - 6 < x, x)
|
| 737 |
+
x > -3
|
| 738 |
+
|
| 739 |
+
Sometimes nonlinear relationships will be False
|
| 740 |
+
|
| 741 |
+
>>> f(x**2 + 4 < 0, x)
|
| 742 |
+
False
|
| 743 |
+
|
| 744 |
+
Or they may involve more than one region of values:
|
| 745 |
+
|
| 746 |
+
>>> f(x**2 - 4 < 0, x)
|
| 747 |
+
(-2 < x) & (x < 2)
|
| 748 |
+
|
| 749 |
+
To restrict the solution to a relational, set linear=True
|
| 750 |
+
and only the x-dependent portion will be isolated on the left:
|
| 751 |
+
|
| 752 |
+
>>> f(x**2 - 4 < 0, x, linear=True)
|
| 753 |
+
x**2 < 4
|
| 754 |
+
|
| 755 |
+
Division of only nonzero quantities is allowed, so x cannot
|
| 756 |
+
be isolated by dividing by y:
|
| 757 |
+
|
| 758 |
+
>>> y.is_nonzero is None # it is unknown whether it is 0 or not
|
| 759 |
+
True
|
| 760 |
+
>>> f(x*y < 1, x)
|
| 761 |
+
x*y < 1
|
| 762 |
+
|
| 763 |
+
And while an equality (or inequality) still holds after dividing by a
|
| 764 |
+
non-zero quantity
|
| 765 |
+
|
| 766 |
+
>>> nz = Symbol('nz', nonzero=True)
|
| 767 |
+
>>> f(Eq(x*nz, 1), x)
|
| 768 |
+
Eq(x, 1/nz)
|
| 769 |
+
|
| 770 |
+
the sign must be known for other inequalities involving > or <:
|
| 771 |
+
|
| 772 |
+
>>> f(x*nz <= 1, x)
|
| 773 |
+
nz*x <= 1
|
| 774 |
+
>>> p = Symbol('p', positive=True)
|
| 775 |
+
>>> f(x*p <= 1, x)
|
| 776 |
+
x <= 1/p
|
| 777 |
+
|
| 778 |
+
When there are denominators in the original expression that
|
| 779 |
+
are removed by expansion, conditions for them will be returned
|
| 780 |
+
as part of the result:
|
| 781 |
+
|
| 782 |
+
>>> f(x < x*(2/x - 1), x)
|
| 783 |
+
(x < 1) & Ne(x, 0)
|
| 784 |
+
"""
|
| 785 |
+
from sympy.solvers.solvers import denoms
|
| 786 |
+
if s not in ie.free_symbols:
|
| 787 |
+
return ie
|
| 788 |
+
if ie.rhs == s:
|
| 789 |
+
ie = ie.reversed
|
| 790 |
+
if ie.lhs == s and s not in ie.rhs.free_symbols:
|
| 791 |
+
return ie
|
| 792 |
+
|
| 793 |
+
def classify(ie, s, i):
|
| 794 |
+
# return True or False if ie evaluates when substituting s with
|
| 795 |
+
# i else None (if unevaluated) or NaN (when there is an error
|
| 796 |
+
# in evaluating)
|
| 797 |
+
try:
|
| 798 |
+
v = ie.subs(s, i)
|
| 799 |
+
if v is S.NaN:
|
| 800 |
+
return v
|
| 801 |
+
elif v not in (True, False):
|
| 802 |
+
return
|
| 803 |
+
return v
|
| 804 |
+
except TypeError:
|
| 805 |
+
return S.NaN
|
| 806 |
+
|
| 807 |
+
rv = None
|
| 808 |
+
oo = S.Infinity
|
| 809 |
+
expr = ie.lhs - ie.rhs
|
| 810 |
+
try:
|
| 811 |
+
p = Poly(expr, s)
|
| 812 |
+
if p.degree() == 0:
|
| 813 |
+
rv = ie.func(p.as_expr(), 0)
|
| 814 |
+
elif not linear and p.degree() > 1:
|
| 815 |
+
# handle in except clause
|
| 816 |
+
raise NotImplementedError
|
| 817 |
+
except (PolynomialError, NotImplementedError):
|
| 818 |
+
if not linear:
|
| 819 |
+
try:
|
| 820 |
+
rv = reduce_rational_inequalities([[ie]], s)
|
| 821 |
+
except PolynomialError:
|
| 822 |
+
rv = solve_univariate_inequality(ie, s)
|
| 823 |
+
# remove restrictions wrt +/-oo that may have been
|
| 824 |
+
# applied when using sets to simplify the relationship
|
| 825 |
+
okoo = classify(ie, s, oo)
|
| 826 |
+
if okoo is S.true and classify(rv, s, oo) is S.false:
|
| 827 |
+
rv = rv.subs(s < oo, True)
|
| 828 |
+
oknoo = classify(ie, s, -oo)
|
| 829 |
+
if (oknoo is S.true and
|
| 830 |
+
classify(rv, s, -oo) is S.false):
|
| 831 |
+
rv = rv.subs(-oo < s, True)
|
| 832 |
+
rv = rv.subs(s > -oo, True)
|
| 833 |
+
if rv is S.true:
|
| 834 |
+
rv = (s <= oo) if okoo is S.true else (s < oo)
|
| 835 |
+
if oknoo is not S.true:
|
| 836 |
+
rv = And(-oo < s, rv)
|
| 837 |
+
else:
|
| 838 |
+
p = Poly(expr)
|
| 839 |
+
|
| 840 |
+
conds = []
|
| 841 |
+
if rv is None:
|
| 842 |
+
e = p.as_expr() # this is in expanded form
|
| 843 |
+
# Do a safe inversion of e, moving non-s terms
|
| 844 |
+
# to the rhs and dividing by a nonzero factor if
|
| 845 |
+
# the relational is Eq/Ne; for other relationals
|
| 846 |
+
# the sign must also be positive or negative
|
| 847 |
+
rhs = 0
|
| 848 |
+
b, ax = e.as_independent(s, as_Add=True)
|
| 849 |
+
e -= b
|
| 850 |
+
rhs -= b
|
| 851 |
+
ef = factor_terms(e)
|
| 852 |
+
a, e = ef.as_independent(s, as_Add=False)
|
| 853 |
+
if (a.is_zero != False or # don't divide by potential 0
|
| 854 |
+
a.is_negative ==
|
| 855 |
+
a.is_positive is None and # if sign is not known then
|
| 856 |
+
ie.rel_op not in ('!=', '==')): # reject if not Eq/Ne
|
| 857 |
+
e = ef
|
| 858 |
+
a = S.One
|
| 859 |
+
rhs /= a
|
| 860 |
+
if a.is_positive:
|
| 861 |
+
rv = ie.func(e, rhs)
|
| 862 |
+
else:
|
| 863 |
+
rv = ie.reversed.func(e, rhs)
|
| 864 |
+
|
| 865 |
+
# return conditions under which the value is
|
| 866 |
+
# valid, too.
|
| 867 |
+
beginning_denoms = denoms(ie.lhs) | denoms(ie.rhs)
|
| 868 |
+
current_denoms = denoms(rv)
|
| 869 |
+
for d in beginning_denoms - current_denoms:
|
| 870 |
+
c = _solve_inequality(Eq(d, 0), s, linear=linear)
|
| 871 |
+
if isinstance(c, Eq) and c.lhs == s:
|
| 872 |
+
if classify(rv, s, c.rhs) is S.true:
|
| 873 |
+
# rv is permitting this value but it shouldn't
|
| 874 |
+
conds.append(~c)
|
| 875 |
+
for i in (-oo, oo):
|
| 876 |
+
if (classify(rv, s, i) is S.true and
|
| 877 |
+
classify(ie, s, i) is not S.true):
|
| 878 |
+
conds.append(s < i if i is oo else i < s)
|
| 879 |
+
|
| 880 |
+
conds.append(rv)
|
| 881 |
+
return And(*conds)
|
| 882 |
+
|
| 883 |
+
|
| 884 |
+
def _reduce_inequalities(inequalities, symbols):
|
| 885 |
+
# helper for reduce_inequalities
|
| 886 |
+
|
| 887 |
+
poly_part, abs_part = {}, {}
|
| 888 |
+
other = []
|
| 889 |
+
|
| 890 |
+
for inequality in inequalities:
|
| 891 |
+
|
| 892 |
+
expr, rel = inequality.lhs, inequality.rel_op # rhs is 0
|
| 893 |
+
|
| 894 |
+
# check for gens using atoms which is more strict than free_symbols to
|
| 895 |
+
# guard against EX domain which won't be handled by
|
| 896 |
+
# reduce_rational_inequalities
|
| 897 |
+
gens = expr.atoms(Symbol)
|
| 898 |
+
|
| 899 |
+
if len(gens) == 1:
|
| 900 |
+
gen = gens.pop()
|
| 901 |
+
else:
|
| 902 |
+
common = expr.free_symbols & symbols
|
| 903 |
+
if len(common) == 1:
|
| 904 |
+
gen = common.pop()
|
| 905 |
+
other.append(_solve_inequality(Relational(expr, 0, rel), gen))
|
| 906 |
+
continue
|
| 907 |
+
else:
|
| 908 |
+
raise NotImplementedError(filldedent('''
|
| 909 |
+
inequality has more than one symbol of interest.
|
| 910 |
+
'''))
|
| 911 |
+
|
| 912 |
+
if expr.is_polynomial(gen):
|
| 913 |
+
poly_part.setdefault(gen, []).append((expr, rel))
|
| 914 |
+
else:
|
| 915 |
+
components = expr.find(lambda u:
|
| 916 |
+
u.has(gen) and (
|
| 917 |
+
u.is_Function or u.is_Pow and not u.exp.is_Integer))
|
| 918 |
+
if components and all(isinstance(i, Abs) for i in components):
|
| 919 |
+
abs_part.setdefault(gen, []).append((expr, rel))
|
| 920 |
+
else:
|
| 921 |
+
other.append(_solve_inequality(Relational(expr, 0, rel), gen))
|
| 922 |
+
|
| 923 |
+
poly_reduced = [reduce_rational_inequalities([exprs], gen) for gen, exprs in poly_part.items()]
|
| 924 |
+
abs_reduced = [reduce_abs_inequalities(exprs, gen) for gen, exprs in abs_part.items()]
|
| 925 |
+
|
| 926 |
+
return And(*(poly_reduced + abs_reduced + other))
|
| 927 |
+
|
| 928 |
+
|
| 929 |
+
def reduce_inequalities(inequalities, symbols=[]):
|
| 930 |
+
"""Reduce a system of inequalities with rational coefficients.
|
| 931 |
+
|
| 932 |
+
Examples
|
| 933 |
+
========
|
| 934 |
+
|
| 935 |
+
>>> from sympy.abc import x, y
|
| 936 |
+
>>> from sympy import reduce_inequalities
|
| 937 |
+
|
| 938 |
+
>>> reduce_inequalities(0 <= x + 3, [])
|
| 939 |
+
(-3 <= x) & (x < oo)
|
| 940 |
+
|
| 941 |
+
>>> reduce_inequalities(0 <= x + y*2 - 1, [x])
|
| 942 |
+
(x < oo) & (x >= 1 - 2*y)
|
| 943 |
+
"""
|
| 944 |
+
if not iterable(inequalities):
|
| 945 |
+
inequalities = [inequalities]
|
| 946 |
+
inequalities = [sympify(i) for i in inequalities]
|
| 947 |
+
|
| 948 |
+
gens = set().union(*[i.free_symbols for i in inequalities])
|
| 949 |
+
|
| 950 |
+
if not iterable(symbols):
|
| 951 |
+
symbols = [symbols]
|
| 952 |
+
symbols = (set(symbols) or gens) & gens
|
| 953 |
+
if any(i.is_extended_real is False for i in symbols):
|
| 954 |
+
raise TypeError(filldedent('''
|
| 955 |
+
inequalities cannot contain symbols that are not real.
|
| 956 |
+
'''))
|
| 957 |
+
|
| 958 |
+
# make vanilla symbol real
|
| 959 |
+
recast = {i: Dummy(i.name, extended_real=True)
|
| 960 |
+
for i in gens if i.is_extended_real is None}
|
| 961 |
+
inequalities = [i.xreplace(recast) for i in inequalities]
|
| 962 |
+
symbols = {i.xreplace(recast) for i in symbols}
|
| 963 |
+
|
| 964 |
+
# prefilter
|
| 965 |
+
keep = []
|
| 966 |
+
for i in inequalities:
|
| 967 |
+
if isinstance(i, Relational):
|
| 968 |
+
i = i.func(i.lhs.as_expr() - i.rhs.as_expr(), 0)
|
| 969 |
+
elif i not in (True, False):
|
| 970 |
+
i = Eq(i, 0)
|
| 971 |
+
if i == True:
|
| 972 |
+
continue
|
| 973 |
+
elif i == False:
|
| 974 |
+
return S.false
|
| 975 |
+
if i.lhs.is_number:
|
| 976 |
+
raise NotImplementedError(
|
| 977 |
+
"could not determine truth value of %s" % i)
|
| 978 |
+
keep.append(i)
|
| 979 |
+
inequalities = keep
|
| 980 |
+
del keep
|
| 981 |
+
|
| 982 |
+
# solve system
|
| 983 |
+
rv = _reduce_inequalities(inequalities, symbols)
|
| 984 |
+
|
| 985 |
+
# restore original symbols and return
|
| 986 |
+
return rv.xreplace({v: k for k, v in recast.items()})
|
evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/pde.py
ADDED
|
@@ -0,0 +1,971 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This module contains pdsolve() and different helper functions that it
|
| 3 |
+
uses. It is heavily inspired by the ode module and hence the basic
|
| 4 |
+
infrastructure remains the same.
|
| 5 |
+
|
| 6 |
+
**Functions in this module**
|
| 7 |
+
|
| 8 |
+
These are the user functions in this module:
|
| 9 |
+
|
| 10 |
+
- pdsolve() - Solves PDE's
|
| 11 |
+
- classify_pde() - Classifies PDEs into possible hints for dsolve().
|
| 12 |
+
- pde_separate() - Separate variables in partial differential equation either by
|
| 13 |
+
additive or multiplicative separation approach.
|
| 14 |
+
|
| 15 |
+
These are the helper functions in this module:
|
| 16 |
+
|
| 17 |
+
- pde_separate_add() - Helper function for searching additive separable solutions.
|
| 18 |
+
- pde_separate_mul() - Helper function for searching multiplicative
|
| 19 |
+
separable solutions.
|
| 20 |
+
|
| 21 |
+
**Currently implemented solver methods**
|
| 22 |
+
|
| 23 |
+
The following methods are implemented for solving partial differential
|
| 24 |
+
equations. See the docstrings of the various pde_hint() functions for
|
| 25 |
+
more information on each (run help(pde)):
|
| 26 |
+
|
| 27 |
+
- 1st order linear homogeneous partial differential equations
|
| 28 |
+
with constant coefficients.
|
| 29 |
+
- 1st order linear general partial differential equations
|
| 30 |
+
with constant coefficients.
|
| 31 |
+
- 1st order linear partial differential equations with
|
| 32 |
+
variable coefficients.
|
| 33 |
+
|
| 34 |
+
"""
|
| 35 |
+
from functools import reduce
|
| 36 |
+
|
| 37 |
+
from itertools import combinations_with_replacement
|
| 38 |
+
from sympy.simplify import simplify # type: ignore
|
| 39 |
+
from sympy.core import Add, S
|
| 40 |
+
from sympy.core.function import Function, expand, AppliedUndef, Subs
|
| 41 |
+
from sympy.core.relational import Equality, Eq
|
| 42 |
+
from sympy.core.symbol import Symbol, Wild, symbols
|
| 43 |
+
from sympy.functions import exp
|
| 44 |
+
from sympy.integrals.integrals import Integral, integrate
|
| 45 |
+
from sympy.utilities.iterables import has_dups, is_sequence
|
| 46 |
+
from sympy.utilities.misc import filldedent
|
| 47 |
+
|
| 48 |
+
from sympy.solvers.deutils import _preprocess, ode_order, _desolve
|
| 49 |
+
from sympy.solvers.solvers import solve
|
| 50 |
+
from sympy.simplify.radsimp import collect
|
| 51 |
+
|
| 52 |
+
import operator
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
allhints = (
|
| 56 |
+
"1st_linear_constant_coeff_homogeneous",
|
| 57 |
+
"1st_linear_constant_coeff",
|
| 58 |
+
"1st_linear_constant_coeff_Integral",
|
| 59 |
+
"1st_linear_variable_coeff"
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def pdsolve(eq, func=None, hint='default', dict=False, solvefun=None, **kwargs):
|
| 64 |
+
"""
|
| 65 |
+
Solves any (supported) kind of partial differential equation.
|
| 66 |
+
|
| 67 |
+
**Usage**
|
| 68 |
+
|
| 69 |
+
pdsolve(eq, f(x,y), hint) -> Solve partial differential equation
|
| 70 |
+
eq for function f(x,y), using method hint.
|
| 71 |
+
|
| 72 |
+
**Details**
|
| 73 |
+
|
| 74 |
+
``eq`` can be any supported partial differential equation (see
|
| 75 |
+
the pde docstring for supported methods). This can either
|
| 76 |
+
be an Equality, or an expression, which is assumed to be
|
| 77 |
+
equal to 0.
|
| 78 |
+
|
| 79 |
+
``f(x,y)`` is a function of two variables whose derivatives in that
|
| 80 |
+
variable make up the partial differential equation. In many
|
| 81 |
+
cases it is not necessary to provide this; it will be autodetected
|
| 82 |
+
(and an error raised if it could not be detected).
|
| 83 |
+
|
| 84 |
+
``hint`` is the solving method that you want pdsolve to use. Use
|
| 85 |
+
classify_pde(eq, f(x,y)) to get all of the possible hints for
|
| 86 |
+
a PDE. The default hint, 'default', will use whatever hint
|
| 87 |
+
is returned first by classify_pde(). See Hints below for
|
| 88 |
+
more options that you can use for hint.
|
| 89 |
+
|
| 90 |
+
``solvefun`` is the convention used for arbitrary functions returned
|
| 91 |
+
by the PDE solver. If not set by the user, it is set by default
|
| 92 |
+
to be F.
|
| 93 |
+
|
| 94 |
+
**Hints**
|
| 95 |
+
|
| 96 |
+
Aside from the various solving methods, there are also some
|
| 97 |
+
meta-hints that you can pass to pdsolve():
|
| 98 |
+
|
| 99 |
+
"default":
|
| 100 |
+
This uses whatever hint is returned first by
|
| 101 |
+
classify_pde(). This is the default argument to
|
| 102 |
+
pdsolve().
|
| 103 |
+
|
| 104 |
+
"all":
|
| 105 |
+
To make pdsolve apply all relevant classification hints,
|
| 106 |
+
use pdsolve(PDE, func, hint="all"). This will return a
|
| 107 |
+
dictionary of hint:solution terms. If a hint causes
|
| 108 |
+
pdsolve to raise the NotImplementedError, value of that
|
| 109 |
+
hint's key will be the exception object raised. The
|
| 110 |
+
dictionary will also include some special keys:
|
| 111 |
+
|
| 112 |
+
- order: The order of the PDE. See also ode_order() in
|
| 113 |
+
deutils.py
|
| 114 |
+
- default: The solution that would be returned by
|
| 115 |
+
default. This is the one produced by the hint that
|
| 116 |
+
appears first in the tuple returned by classify_pde().
|
| 117 |
+
|
| 118 |
+
"all_Integral":
|
| 119 |
+
This is the same as "all", except if a hint also has a
|
| 120 |
+
corresponding "_Integral" hint, it only returns the
|
| 121 |
+
"_Integral" hint. This is useful if "all" causes
|
| 122 |
+
pdsolve() to hang because of a difficult or impossible
|
| 123 |
+
integral. This meta-hint will also be much faster than
|
| 124 |
+
"all", because integrate() is an expensive routine.
|
| 125 |
+
|
| 126 |
+
See also the classify_pde() docstring for more info on hints,
|
| 127 |
+
and the pde docstring for a list of all supported hints.
|
| 128 |
+
|
| 129 |
+
**Tips**
|
| 130 |
+
- You can declare the derivative of an unknown function this way:
|
| 131 |
+
|
| 132 |
+
>>> from sympy import Function, Derivative
|
| 133 |
+
>>> from sympy.abc import x, y # x and y are the independent variables
|
| 134 |
+
>>> f = Function("f")(x, y) # f is a function of x and y
|
| 135 |
+
>>> # fx will be the partial derivative of f with respect to x
|
| 136 |
+
>>> fx = Derivative(f, x)
|
| 137 |
+
>>> # fy will be the partial derivative of f with respect to y
|
| 138 |
+
>>> fy = Derivative(f, y)
|
| 139 |
+
|
| 140 |
+
- See test_pde.py for many tests, which serves also as a set of
|
| 141 |
+
examples for how to use pdsolve().
|
| 142 |
+
- pdsolve always returns an Equality class (except for the case
|
| 143 |
+
when the hint is "all" or "all_Integral"). Note that it is not possible
|
| 144 |
+
to get an explicit solution for f(x, y) as in the case of ODE's
|
| 145 |
+
- Do help(pde.pde_hintname) to get help more information on a
|
| 146 |
+
specific hint
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
Examples
|
| 150 |
+
========
|
| 151 |
+
|
| 152 |
+
>>> from sympy.solvers.pde import pdsolve
|
| 153 |
+
>>> from sympy import Function, Eq
|
| 154 |
+
>>> from sympy.abc import x, y
|
| 155 |
+
>>> f = Function('f')
|
| 156 |
+
>>> u = f(x, y)
|
| 157 |
+
>>> ux = u.diff(x)
|
| 158 |
+
>>> uy = u.diff(y)
|
| 159 |
+
>>> eq = Eq(1 + (2*(ux/u)) + (3*(uy/u)), 0)
|
| 160 |
+
>>> pdsolve(eq)
|
| 161 |
+
Eq(f(x, y), F(3*x - 2*y)*exp(-2*x/13 - 3*y/13))
|
| 162 |
+
|
| 163 |
+
"""
|
| 164 |
+
|
| 165 |
+
if not solvefun:
|
| 166 |
+
solvefun = Function('F')
|
| 167 |
+
|
| 168 |
+
# See the docstring of _desolve for more details.
|
| 169 |
+
hints = _desolve(eq, func=func, hint=hint, simplify=True,
|
| 170 |
+
type='pde', **kwargs)
|
| 171 |
+
eq = hints.pop('eq', False)
|
| 172 |
+
all_ = hints.pop('all', False)
|
| 173 |
+
|
| 174 |
+
if all_:
|
| 175 |
+
# TODO : 'best' hint should be implemented when adequate
|
| 176 |
+
# number of hints are added.
|
| 177 |
+
pdedict = {}
|
| 178 |
+
failed_hints = {}
|
| 179 |
+
gethints = classify_pde(eq, dict=True)
|
| 180 |
+
pdedict.update({'order': gethints['order'],
|
| 181 |
+
'default': gethints['default']})
|
| 182 |
+
for hint in hints:
|
| 183 |
+
try:
|
| 184 |
+
rv = _helper_simplify(eq, hint, hints[hint]['func'],
|
| 185 |
+
hints[hint]['order'], hints[hint][hint], solvefun)
|
| 186 |
+
except NotImplementedError as detail:
|
| 187 |
+
failed_hints[hint] = detail
|
| 188 |
+
else:
|
| 189 |
+
pdedict[hint] = rv
|
| 190 |
+
pdedict.update(failed_hints)
|
| 191 |
+
return pdedict
|
| 192 |
+
|
| 193 |
+
else:
|
| 194 |
+
return _helper_simplify(eq, hints['hint'], hints['func'],
|
| 195 |
+
hints['order'], hints[hints['hint']], solvefun)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def _helper_simplify(eq, hint, func, order, match, solvefun):
|
| 199 |
+
"""Helper function of pdsolve that calls the respective
|
| 200 |
+
pde functions to solve for the partial differential
|
| 201 |
+
equations. This minimizes the computation in
|
| 202 |
+
calling _desolve multiple times.
|
| 203 |
+
"""
|
| 204 |
+
|
| 205 |
+
if hint.endswith("_Integral"):
|
| 206 |
+
solvefunc = globals()[
|
| 207 |
+
"pde_" + hint[:-len("_Integral")]]
|
| 208 |
+
else:
|
| 209 |
+
solvefunc = globals()["pde_" + hint]
|
| 210 |
+
return _handle_Integral(solvefunc(eq, func, order,
|
| 211 |
+
match, solvefun), func, order, hint)
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def _handle_Integral(expr, func, order, hint):
|
| 215 |
+
r"""
|
| 216 |
+
Converts a solution with integrals in it into an actual solution.
|
| 217 |
+
|
| 218 |
+
Simplifies the integral mainly using doit()
|
| 219 |
+
"""
|
| 220 |
+
if hint.endswith("_Integral"):
|
| 221 |
+
return expr
|
| 222 |
+
|
| 223 |
+
elif hint == "1st_linear_constant_coeff":
|
| 224 |
+
return simplify(expr.doit())
|
| 225 |
+
|
| 226 |
+
else:
|
| 227 |
+
return expr
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def classify_pde(eq, func=None, dict=False, *, prep=True, **kwargs):
|
| 231 |
+
"""
|
| 232 |
+
Returns a tuple of possible pdsolve() classifications for a PDE.
|
| 233 |
+
|
| 234 |
+
The tuple is ordered so that first item is the classification that
|
| 235 |
+
pdsolve() uses to solve the PDE by default. In general,
|
| 236 |
+
classifications near the beginning of the list will produce
|
| 237 |
+
better solutions faster than those near the end, though there are
|
| 238 |
+
always exceptions. To make pdsolve use a different classification,
|
| 239 |
+
use pdsolve(PDE, func, hint=<classification>). See also the pdsolve()
|
| 240 |
+
docstring for different meta-hints you can use.
|
| 241 |
+
|
| 242 |
+
If ``dict`` is true, classify_pde() will return a dictionary of
|
| 243 |
+
hint:match expression terms. This is intended for internal use by
|
| 244 |
+
pdsolve(). Note that because dictionaries are ordered arbitrarily,
|
| 245 |
+
this will most likely not be in the same order as the tuple.
|
| 246 |
+
|
| 247 |
+
You can get help on different hints by doing help(pde.pde_hintname),
|
| 248 |
+
where hintname is the name of the hint without "_Integral".
|
| 249 |
+
|
| 250 |
+
See sympy.pde.allhints or the sympy.pde docstring for a list of all
|
| 251 |
+
supported hints that can be returned from classify_pde.
|
| 252 |
+
|
| 253 |
+
|
| 254 |
+
Examples
|
| 255 |
+
========
|
| 256 |
+
|
| 257 |
+
>>> from sympy.solvers.pde import classify_pde
|
| 258 |
+
>>> from sympy import Function, Eq
|
| 259 |
+
>>> from sympy.abc import x, y
|
| 260 |
+
>>> f = Function('f')
|
| 261 |
+
>>> u = f(x, y)
|
| 262 |
+
>>> ux = u.diff(x)
|
| 263 |
+
>>> uy = u.diff(y)
|
| 264 |
+
>>> eq = Eq(1 + (2*(ux/u)) + (3*(uy/u)), 0)
|
| 265 |
+
>>> classify_pde(eq)
|
| 266 |
+
('1st_linear_constant_coeff_homogeneous',)
|
| 267 |
+
"""
|
| 268 |
+
|
| 269 |
+
if func and len(func.args) != 2:
|
| 270 |
+
raise NotImplementedError("Right now only partial "
|
| 271 |
+
"differential equations of two variables are supported")
|
| 272 |
+
|
| 273 |
+
if prep or func is None:
|
| 274 |
+
prep, func_ = _preprocess(eq, func)
|
| 275 |
+
if func is None:
|
| 276 |
+
func = func_
|
| 277 |
+
|
| 278 |
+
if isinstance(eq, Equality):
|
| 279 |
+
if eq.rhs != 0:
|
| 280 |
+
return classify_pde(eq.lhs - eq.rhs, func)
|
| 281 |
+
eq = eq.lhs
|
| 282 |
+
|
| 283 |
+
f = func.func
|
| 284 |
+
x = func.args[0]
|
| 285 |
+
y = func.args[1]
|
| 286 |
+
fx = f(x,y).diff(x)
|
| 287 |
+
fy = f(x,y).diff(y)
|
| 288 |
+
|
| 289 |
+
# TODO : For now pde.py uses support offered by the ode_order function
|
| 290 |
+
# to find the order with respect to a multi-variable function. An
|
| 291 |
+
# improvement could be to classify the order of the PDE on the basis of
|
| 292 |
+
# individual variables.
|
| 293 |
+
order = ode_order(eq, f(x,y))
|
| 294 |
+
|
| 295 |
+
# hint:matchdict or hint:(tuple of matchdicts)
|
| 296 |
+
# Also will contain "default":<default hint> and "order":order items.
|
| 297 |
+
matching_hints = {'order': order}
|
| 298 |
+
|
| 299 |
+
if not order:
|
| 300 |
+
if dict:
|
| 301 |
+
matching_hints["default"] = None
|
| 302 |
+
return matching_hints
|
| 303 |
+
return ()
|
| 304 |
+
|
| 305 |
+
eq = expand(eq)
|
| 306 |
+
|
| 307 |
+
a = Wild('a', exclude = [f(x,y)])
|
| 308 |
+
b = Wild('b', exclude = [f(x,y), fx, fy, x, y])
|
| 309 |
+
c = Wild('c', exclude = [f(x,y), fx, fy, x, y])
|
| 310 |
+
d = Wild('d', exclude = [f(x,y), fx, fy, x, y])
|
| 311 |
+
e = Wild('e', exclude = [f(x,y), fx, fy])
|
| 312 |
+
n = Wild('n', exclude = [x, y])
|
| 313 |
+
# Try removing the smallest power of f(x,y)
|
| 314 |
+
# from the highest partial derivatives of f(x,y)
|
| 315 |
+
reduced_eq = eq
|
| 316 |
+
if eq.is_Add:
|
| 317 |
+
power = None
|
| 318 |
+
for i in set(combinations_with_replacement((x,y), order)):
|
| 319 |
+
coeff = eq.coeff(f(x,y).diff(*i))
|
| 320 |
+
if coeff == 1:
|
| 321 |
+
continue
|
| 322 |
+
match = coeff.match(a*f(x,y)**n)
|
| 323 |
+
if match and match[a]:
|
| 324 |
+
if power is None or match[n] < power:
|
| 325 |
+
power = match[n]
|
| 326 |
+
if power:
|
| 327 |
+
den = f(x,y)**power
|
| 328 |
+
reduced_eq = Add(*[arg/den for arg in eq.args])
|
| 329 |
+
|
| 330 |
+
if order == 1:
|
| 331 |
+
reduced_eq = collect(reduced_eq, f(x, y))
|
| 332 |
+
r = reduced_eq.match(b*fx + c*fy + d*f(x,y) + e)
|
| 333 |
+
if r:
|
| 334 |
+
if not r[e]:
|
| 335 |
+
## Linear first-order homogeneous partial-differential
|
| 336 |
+
## equation with constant coefficients
|
| 337 |
+
r.update({'b': b, 'c': c, 'd': d})
|
| 338 |
+
matching_hints["1st_linear_constant_coeff_homogeneous"] = r
|
| 339 |
+
elif r[b]**2 + r[c]**2 != 0:
|
| 340 |
+
## Linear first-order general partial-differential
|
| 341 |
+
## equation with constant coefficients
|
| 342 |
+
r.update({'b': b, 'c': c, 'd': d, 'e': e})
|
| 343 |
+
matching_hints["1st_linear_constant_coeff"] = r
|
| 344 |
+
matching_hints["1st_linear_constant_coeff_Integral"] = r
|
| 345 |
+
|
| 346 |
+
else:
|
| 347 |
+
b = Wild('b', exclude=[f(x, y), fx, fy])
|
| 348 |
+
c = Wild('c', exclude=[f(x, y), fx, fy])
|
| 349 |
+
d = Wild('d', exclude=[f(x, y), fx, fy])
|
| 350 |
+
r = reduced_eq.match(b*fx + c*fy + d*f(x,y) + e)
|
| 351 |
+
if r:
|
| 352 |
+
r.update({'b': b, 'c': c, 'd': d, 'e': e})
|
| 353 |
+
matching_hints["1st_linear_variable_coeff"] = r
|
| 354 |
+
|
| 355 |
+
# Order keys based on allhints.
|
| 356 |
+
rettuple = tuple(i for i in allhints if i in matching_hints)
|
| 357 |
+
|
| 358 |
+
if dict:
|
| 359 |
+
# Dictionaries are ordered arbitrarily, so make note of which
|
| 360 |
+
# hint would come first for pdsolve(). Use an ordered dict in Py 3.
|
| 361 |
+
matching_hints["default"] = None
|
| 362 |
+
matching_hints["ordered_hints"] = rettuple
|
| 363 |
+
for i in allhints:
|
| 364 |
+
if i in matching_hints:
|
| 365 |
+
matching_hints["default"] = i
|
| 366 |
+
break
|
| 367 |
+
return matching_hints
|
| 368 |
+
return rettuple
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
def checkpdesol(pde, sol, func=None, solve_for_func=True):
|
| 372 |
+
"""
|
| 373 |
+
Checks if the given solution satisfies the partial differential
|
| 374 |
+
equation.
|
| 375 |
+
|
| 376 |
+
pde is the partial differential equation which can be given in the
|
| 377 |
+
form of an equation or an expression. sol is the solution for which
|
| 378 |
+
the pde is to be checked. This can also be given in an equation or
|
| 379 |
+
an expression form. If the function is not provided, the helper
|
| 380 |
+
function _preprocess from deutils is used to identify the function.
|
| 381 |
+
|
| 382 |
+
If a sequence of solutions is passed, the same sort of container will be
|
| 383 |
+
used to return the result for each solution.
|
| 384 |
+
|
| 385 |
+
The following methods are currently being implemented to check if the
|
| 386 |
+
solution satisfies the PDE:
|
| 387 |
+
|
| 388 |
+
1. Directly substitute the solution in the PDE and check. If the
|
| 389 |
+
solution has not been solved for f, then it will solve for f
|
| 390 |
+
provided solve_for_func has not been set to False.
|
| 391 |
+
|
| 392 |
+
If the solution satisfies the PDE, then a tuple (True, 0) is returned.
|
| 393 |
+
Otherwise a tuple (False, expr) where expr is the value obtained
|
| 394 |
+
after substituting the solution in the PDE. However if a known solution
|
| 395 |
+
returns False, it may be due to the inability of doit() to simplify it to zero.
|
| 396 |
+
|
| 397 |
+
Examples
|
| 398 |
+
========
|
| 399 |
+
|
| 400 |
+
>>> from sympy import Function, symbols
|
| 401 |
+
>>> from sympy.solvers.pde import checkpdesol, pdsolve
|
| 402 |
+
>>> x, y = symbols('x y')
|
| 403 |
+
>>> f = Function('f')
|
| 404 |
+
>>> eq = 2*f(x,y) + 3*f(x,y).diff(x) + 4*f(x,y).diff(y)
|
| 405 |
+
>>> sol = pdsolve(eq)
|
| 406 |
+
>>> assert checkpdesol(eq, sol)[0]
|
| 407 |
+
>>> eq = x*f(x,y) + f(x,y).diff(x)
|
| 408 |
+
>>> checkpdesol(eq, sol)
|
| 409 |
+
(False, (x*F(4*x - 3*y) - 6*F(4*x - 3*y)/25 + 4*Subs(Derivative(F(_xi_1), _xi_1), _xi_1, 4*x - 3*y))*exp(-6*x/25 - 8*y/25))
|
| 410 |
+
"""
|
| 411 |
+
|
| 412 |
+
# Converting the pde into an equation
|
| 413 |
+
if not isinstance(pde, Equality):
|
| 414 |
+
pde = Eq(pde, 0)
|
| 415 |
+
|
| 416 |
+
# If no function is given, try finding the function present.
|
| 417 |
+
if func is None:
|
| 418 |
+
try:
|
| 419 |
+
_, func = _preprocess(pde.lhs)
|
| 420 |
+
except ValueError:
|
| 421 |
+
funcs = [s.atoms(AppliedUndef) for s in (
|
| 422 |
+
sol if is_sequence(sol, set) else [sol])]
|
| 423 |
+
funcs = set().union(funcs)
|
| 424 |
+
if len(funcs) != 1:
|
| 425 |
+
raise ValueError(
|
| 426 |
+
'must pass func arg to checkpdesol for this case.')
|
| 427 |
+
func = funcs.pop()
|
| 428 |
+
|
| 429 |
+
# If the given solution is in the form of a list or a set
|
| 430 |
+
# then return a list or set of tuples.
|
| 431 |
+
if is_sequence(sol, set):
|
| 432 |
+
return type(sol)([checkpdesol(
|
| 433 |
+
pde, i, func=func,
|
| 434 |
+
solve_for_func=solve_for_func) for i in sol])
|
| 435 |
+
|
| 436 |
+
# Convert solution into an equation
|
| 437 |
+
if not isinstance(sol, Equality):
|
| 438 |
+
sol = Eq(func, sol)
|
| 439 |
+
elif sol.rhs == func:
|
| 440 |
+
sol = sol.reversed
|
| 441 |
+
|
| 442 |
+
# Try solving for the function
|
| 443 |
+
solved = sol.lhs == func and not sol.rhs.has(func)
|
| 444 |
+
if solve_for_func and not solved:
|
| 445 |
+
solved = solve(sol, func)
|
| 446 |
+
if solved:
|
| 447 |
+
if len(solved) == 1:
|
| 448 |
+
return checkpdesol(pde, Eq(func, solved[0]),
|
| 449 |
+
func=func, solve_for_func=False)
|
| 450 |
+
else:
|
| 451 |
+
return checkpdesol(pde, [Eq(func, t) for t in solved],
|
| 452 |
+
func=func, solve_for_func=False)
|
| 453 |
+
|
| 454 |
+
# try direct substitution of the solution into the PDE and simplify
|
| 455 |
+
if sol.lhs == func:
|
| 456 |
+
pde = pde.lhs - pde.rhs
|
| 457 |
+
s = simplify(pde.subs(func, sol.rhs).doit())
|
| 458 |
+
return s is S.Zero, s
|
| 459 |
+
|
| 460 |
+
raise NotImplementedError(filldedent('''
|
| 461 |
+
Unable to test if %s is a solution to %s.''' % (sol, pde)))
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
def pde_1st_linear_constant_coeff_homogeneous(eq, func, order, match, solvefun):
|
| 466 |
+
r"""
|
| 467 |
+
Solves a first order linear homogeneous
|
| 468 |
+
partial differential equation with constant coefficients.
|
| 469 |
+
|
| 470 |
+
The general form of this partial differential equation is
|
| 471 |
+
|
| 472 |
+
.. math:: a \frac{\partial f(x,y)}{\partial x}
|
| 473 |
+
+ b \frac{\partial f(x,y)}{\partial y} + c f(x,y) = 0
|
| 474 |
+
|
| 475 |
+
where `a`, `b` and `c` are constants.
|
| 476 |
+
|
| 477 |
+
The general solution is of the form:
|
| 478 |
+
|
| 479 |
+
.. math::
|
| 480 |
+
f(x, y) = F(- a y + b x ) e^{- \frac{c (a x + b y)}{a^2 + b^2}}
|
| 481 |
+
|
| 482 |
+
and can be found in SymPy with ``pdsolve``::
|
| 483 |
+
|
| 484 |
+
>>> from sympy.solvers import pdsolve
|
| 485 |
+
>>> from sympy.abc import x, y, a, b, c
|
| 486 |
+
>>> from sympy import Function, pprint
|
| 487 |
+
>>> f = Function('f')
|
| 488 |
+
>>> u = f(x,y)
|
| 489 |
+
>>> ux = u.diff(x)
|
| 490 |
+
>>> uy = u.diff(y)
|
| 491 |
+
>>> genform = a*ux + b*uy + c*u
|
| 492 |
+
>>> pprint(genform)
|
| 493 |
+
d d
|
| 494 |
+
a*--(f(x, y)) + b*--(f(x, y)) + c*f(x, y)
|
| 495 |
+
dx dy
|
| 496 |
+
|
| 497 |
+
>>> pprint(pdsolve(genform))
|
| 498 |
+
-c*(a*x + b*y)
|
| 499 |
+
---------------
|
| 500 |
+
2 2
|
| 501 |
+
a + b
|
| 502 |
+
f(x, y) = F(-a*y + b*x)*e
|
| 503 |
+
|
| 504 |
+
Examples
|
| 505 |
+
========
|
| 506 |
+
|
| 507 |
+
>>> from sympy import pdsolve
|
| 508 |
+
>>> from sympy import Function, pprint
|
| 509 |
+
>>> from sympy.abc import x,y
|
| 510 |
+
>>> f = Function('f')
|
| 511 |
+
>>> pdsolve(f(x,y) + f(x,y).diff(x) + f(x,y).diff(y))
|
| 512 |
+
Eq(f(x, y), F(x - y)*exp(-x/2 - y/2))
|
| 513 |
+
>>> pprint(pdsolve(f(x,y) + f(x,y).diff(x) + f(x,y).diff(y)))
|
| 514 |
+
x y
|
| 515 |
+
- - - -
|
| 516 |
+
2 2
|
| 517 |
+
f(x, y) = F(x - y)*e
|
| 518 |
+
|
| 519 |
+
References
|
| 520 |
+
==========
|
| 521 |
+
|
| 522 |
+
- Viktor Grigoryan, "Partial Differential Equations"
|
| 523 |
+
Math 124A - Fall 2010, pp.7
|
| 524 |
+
|
| 525 |
+
"""
|
| 526 |
+
# TODO : For now homogeneous first order linear PDE's having
|
| 527 |
+
# two variables are implemented. Once there is support for
|
| 528 |
+
# solving systems of ODE's, this can be extended to n variables.
|
| 529 |
+
|
| 530 |
+
f = func.func
|
| 531 |
+
x = func.args[0]
|
| 532 |
+
y = func.args[1]
|
| 533 |
+
b = match[match['b']]
|
| 534 |
+
c = match[match['c']]
|
| 535 |
+
d = match[match['d']]
|
| 536 |
+
return Eq(f(x,y), exp(-S(d)/(b**2 + c**2)*(b*x + c*y))*solvefun(c*x - b*y))
|
| 537 |
+
|
| 538 |
+
|
| 539 |
+
def pde_1st_linear_constant_coeff(eq, func, order, match, solvefun):
|
| 540 |
+
r"""
|
| 541 |
+
Solves a first order linear partial differential equation
|
| 542 |
+
with constant coefficients.
|
| 543 |
+
|
| 544 |
+
The general form of this partial differential equation is
|
| 545 |
+
|
| 546 |
+
.. math:: a \frac{\partial f(x,y)}{\partial x}
|
| 547 |
+
+ b \frac{\partial f(x,y)}{\partial y}
|
| 548 |
+
+ c f(x,y) = G(x,y)
|
| 549 |
+
|
| 550 |
+
where `a`, `b` and `c` are constants and `G(x, y)` can be an arbitrary
|
| 551 |
+
function in `x` and `y`.
|
| 552 |
+
|
| 553 |
+
The general solution of the PDE is:
|
| 554 |
+
|
| 555 |
+
.. math::
|
| 556 |
+
f(x, y) = \left. \left[F(\eta) + \frac{1}{a^2 + b^2}
|
| 557 |
+
\int\limits^{a x + b y} G\left(\frac{a \xi + b \eta}{a^2 + b^2},
|
| 558 |
+
\frac{- a \eta + b \xi}{a^2 + b^2} \right)
|
| 559 |
+
e^{\frac{c \xi}{a^2 + b^2}}\, d\xi\right]
|
| 560 |
+
e^{- \frac{c \xi}{a^2 + b^2}}
|
| 561 |
+
\right|_{\substack{\eta=- a y + b x\\ \xi=a x + b y }}\, ,
|
| 562 |
+
|
| 563 |
+
where `F(\eta)` is an arbitrary single-valued function. The solution
|
| 564 |
+
can be found in SymPy with ``pdsolve``::
|
| 565 |
+
|
| 566 |
+
>>> from sympy.solvers import pdsolve
|
| 567 |
+
>>> from sympy.abc import x, y, a, b, c
|
| 568 |
+
>>> from sympy import Function, pprint
|
| 569 |
+
>>> f = Function('f')
|
| 570 |
+
>>> G = Function('G')
|
| 571 |
+
>>> u = f(x, y)
|
| 572 |
+
>>> ux = u.diff(x)
|
| 573 |
+
>>> uy = u.diff(y)
|
| 574 |
+
>>> genform = a*ux + b*uy + c*u - G(x,y)
|
| 575 |
+
>>> pprint(genform)
|
| 576 |
+
d d
|
| 577 |
+
a*--(f(x, y)) + b*--(f(x, y)) + c*f(x, y) - G(x, y)
|
| 578 |
+
dx dy
|
| 579 |
+
>>> pprint(pdsolve(genform, hint='1st_linear_constant_coeff_Integral'))
|
| 580 |
+
// a*x + b*y \ \|
|
| 581 |
+
|| / | ||
|
| 582 |
+
|| | | ||
|
| 583 |
+
|| | c*xi | ||
|
| 584 |
+
|| | ------- | ||
|
| 585 |
+
|| | 2 2 | ||
|
| 586 |
+
|| | /a*xi + b*eta -a*eta + b*xi\ a + b | ||
|
| 587 |
+
|| | G|------------, -------------|*e d(xi)| ||
|
| 588 |
+
|| | | 2 2 2 2 | | ||
|
| 589 |
+
|| | \ a + b a + b / | -c*xi ||
|
| 590 |
+
|| | | -------||
|
| 591 |
+
|| / | 2 2||
|
| 592 |
+
|| | a + b ||
|
| 593 |
+
f(x, y) = ||F(eta) + -------------------------------------------------------|*e ||
|
| 594 |
+
|| 2 2 | ||
|
| 595 |
+
\\ a + b / /|eta=-a*y + b*x, xi=a*x + b*y
|
| 596 |
+
|
| 597 |
+
Examples
|
| 598 |
+
========
|
| 599 |
+
|
| 600 |
+
>>> from sympy.solvers.pde import pdsolve
|
| 601 |
+
>>> from sympy import Function, pprint, exp
|
| 602 |
+
>>> from sympy.abc import x,y
|
| 603 |
+
>>> f = Function('f')
|
| 604 |
+
>>> eq = -2*f(x,y).diff(x) + 4*f(x,y).diff(y) + 5*f(x,y) - exp(x + 3*y)
|
| 605 |
+
>>> pdsolve(eq)
|
| 606 |
+
Eq(f(x, y), (F(4*x + 2*y)*exp(x/2) + exp(x + 4*y)/15)*exp(-y))
|
| 607 |
+
|
| 608 |
+
References
|
| 609 |
+
==========
|
| 610 |
+
|
| 611 |
+
- Viktor Grigoryan, "Partial Differential Equations"
|
| 612 |
+
Math 124A - Fall 2010, pp.7
|
| 613 |
+
|
| 614 |
+
"""
|
| 615 |
+
|
| 616 |
+
# TODO : For now homogeneous first order linear PDE's having
|
| 617 |
+
# two variables are implemented. Once there is support for
|
| 618 |
+
# solving systems of ODE's, this can be extended to n variables.
|
| 619 |
+
xi, eta = symbols("xi eta")
|
| 620 |
+
f = func.func
|
| 621 |
+
x = func.args[0]
|
| 622 |
+
y = func.args[1]
|
| 623 |
+
b = match[match['b']]
|
| 624 |
+
c = match[match['c']]
|
| 625 |
+
d = match[match['d']]
|
| 626 |
+
e = -match[match['e']]
|
| 627 |
+
expterm = exp(-S(d)/(b**2 + c**2)*xi)
|
| 628 |
+
functerm = solvefun(eta)
|
| 629 |
+
solvedict = solve((b*x + c*y - xi, c*x - b*y - eta), x, y)
|
| 630 |
+
# Integral should remain as it is in terms of xi,
|
| 631 |
+
# doit() should be done in _handle_Integral.
|
| 632 |
+
genterm = (1/S(b**2 + c**2))*Integral(
|
| 633 |
+
(1/expterm*e).subs(solvedict), (xi, b*x + c*y))
|
| 634 |
+
return Eq(f(x,y), Subs(expterm*(functerm + genterm),
|
| 635 |
+
(eta, xi), (c*x - b*y, b*x + c*y)))
|
| 636 |
+
|
| 637 |
+
|
| 638 |
+
def pde_1st_linear_variable_coeff(eq, func, order, match, solvefun):
|
| 639 |
+
r"""
|
| 640 |
+
Solves a first order linear partial differential equation
|
| 641 |
+
with variable coefficients. The general form of this partial
|
| 642 |
+
differential equation is
|
| 643 |
+
|
| 644 |
+
.. math:: a(x, y) \frac{\partial f(x, y)}{\partial x}
|
| 645 |
+
+ b(x, y) \frac{\partial f(x, y)}{\partial y}
|
| 646 |
+
+ c(x, y) f(x, y) = G(x, y)
|
| 647 |
+
|
| 648 |
+
where `a(x, y)`, `b(x, y)`, `c(x, y)` and `G(x, y)` are arbitrary
|
| 649 |
+
functions in `x` and `y`. This PDE is converted into an ODE by
|
| 650 |
+
making the following transformation:
|
| 651 |
+
|
| 652 |
+
1. `\xi` as `x`
|
| 653 |
+
|
| 654 |
+
2. `\eta` as the constant in the solution to the differential
|
| 655 |
+
equation `\frac{dy}{dx} = -\frac{b}{a}`
|
| 656 |
+
|
| 657 |
+
Making the previous substitutions reduces it to the linear ODE
|
| 658 |
+
|
| 659 |
+
.. math:: a(\xi, \eta)\frac{du}{d\xi} + c(\xi, \eta)u - G(\xi, \eta) = 0
|
| 660 |
+
|
| 661 |
+
which can be solved using ``dsolve``.
|
| 662 |
+
|
| 663 |
+
>>> from sympy.abc import x, y
|
| 664 |
+
>>> from sympy import Function, pprint
|
| 665 |
+
>>> a, b, c, G, f= [Function(i) for i in ['a', 'b', 'c', 'G', 'f']]
|
| 666 |
+
>>> u = f(x,y)
|
| 667 |
+
>>> ux = u.diff(x)
|
| 668 |
+
>>> uy = u.diff(y)
|
| 669 |
+
>>> genform = a(x, y)*u + b(x, y)*ux + c(x, y)*uy - G(x,y)
|
| 670 |
+
>>> pprint(genform)
|
| 671 |
+
d d
|
| 672 |
+
-G(x, y) + a(x, y)*f(x, y) + b(x, y)*--(f(x, y)) + c(x, y)*--(f(x, y))
|
| 673 |
+
dx dy
|
| 674 |
+
|
| 675 |
+
|
| 676 |
+
Examples
|
| 677 |
+
========
|
| 678 |
+
|
| 679 |
+
>>> from sympy.solvers.pde import pdsolve
|
| 680 |
+
>>> from sympy import Function, pprint
|
| 681 |
+
>>> from sympy.abc import x,y
|
| 682 |
+
>>> f = Function('f')
|
| 683 |
+
>>> eq = x*(u.diff(x)) - y*(u.diff(y)) + y**2*u - y**2
|
| 684 |
+
>>> pdsolve(eq)
|
| 685 |
+
Eq(f(x, y), F(x*y)*exp(y**2/2) + 1)
|
| 686 |
+
|
| 687 |
+
References
|
| 688 |
+
==========
|
| 689 |
+
|
| 690 |
+
- Viktor Grigoryan, "Partial Differential Equations"
|
| 691 |
+
Math 124A - Fall 2010, pp.7
|
| 692 |
+
|
| 693 |
+
"""
|
| 694 |
+
from sympy.solvers.ode import dsolve
|
| 695 |
+
|
| 696 |
+
xi, eta = symbols("xi eta")
|
| 697 |
+
f = func.func
|
| 698 |
+
x = func.args[0]
|
| 699 |
+
y = func.args[1]
|
| 700 |
+
b = match[match['b']]
|
| 701 |
+
c = match[match['c']]
|
| 702 |
+
d = match[match['d']]
|
| 703 |
+
e = -match[match['e']]
|
| 704 |
+
|
| 705 |
+
|
| 706 |
+
if not d:
|
| 707 |
+
# To deal with cases like b*ux = e or c*uy = e
|
| 708 |
+
if not (b and c):
|
| 709 |
+
if c:
|
| 710 |
+
try:
|
| 711 |
+
tsol = integrate(e/c, y)
|
| 712 |
+
except NotImplementedError:
|
| 713 |
+
raise NotImplementedError("Unable to find a solution"
|
| 714 |
+
" due to inability of integrate")
|
| 715 |
+
else:
|
| 716 |
+
return Eq(f(x,y), solvefun(x) + tsol)
|
| 717 |
+
if b:
|
| 718 |
+
try:
|
| 719 |
+
tsol = integrate(e/b, x)
|
| 720 |
+
except NotImplementedError:
|
| 721 |
+
raise NotImplementedError("Unable to find a solution"
|
| 722 |
+
" due to inability of integrate")
|
| 723 |
+
else:
|
| 724 |
+
return Eq(f(x,y), solvefun(y) + tsol)
|
| 725 |
+
|
| 726 |
+
if not c:
|
| 727 |
+
# To deal with cases when c is 0, a simpler method is used.
|
| 728 |
+
# The PDE reduces to b*(u.diff(x)) + d*u = e, which is a linear ODE in x
|
| 729 |
+
plode = f(x).diff(x)*b + d*f(x) - e
|
| 730 |
+
sol = dsolve(plode, f(x))
|
| 731 |
+
syms = sol.free_symbols - plode.free_symbols - {x, y}
|
| 732 |
+
rhs = _simplify_variable_coeff(sol.rhs, syms, solvefun, y)
|
| 733 |
+
return Eq(f(x, y), rhs)
|
| 734 |
+
|
| 735 |
+
if not b:
|
| 736 |
+
# To deal with cases when b is 0, a simpler method is used.
|
| 737 |
+
# The PDE reduces to c*(u.diff(y)) + d*u = e, which is a linear ODE in y
|
| 738 |
+
plode = f(y).diff(y)*c + d*f(y) - e
|
| 739 |
+
sol = dsolve(plode, f(y))
|
| 740 |
+
syms = sol.free_symbols - plode.free_symbols - {x, y}
|
| 741 |
+
rhs = _simplify_variable_coeff(sol.rhs, syms, solvefun, x)
|
| 742 |
+
return Eq(f(x, y), rhs)
|
| 743 |
+
|
| 744 |
+
dummy = Function('d')
|
| 745 |
+
h = (c/b).subs(y, dummy(x))
|
| 746 |
+
sol = dsolve(dummy(x).diff(x) - h, dummy(x))
|
| 747 |
+
if isinstance(sol, list):
|
| 748 |
+
sol = sol[0]
|
| 749 |
+
solsym = sol.free_symbols - h.free_symbols - {x, y}
|
| 750 |
+
if len(solsym) == 1:
|
| 751 |
+
solsym = solsym.pop()
|
| 752 |
+
etat = (solve(sol, solsym)[0]).subs(dummy(x), y)
|
| 753 |
+
ysub = solve(eta - etat, y)[0]
|
| 754 |
+
deq = (b*(f(x).diff(x)) + d*f(x) - e).subs(y, ysub)
|
| 755 |
+
final = (dsolve(deq, f(x), hint='1st_linear')).rhs
|
| 756 |
+
if isinstance(final, list):
|
| 757 |
+
final = final[0]
|
| 758 |
+
finsyms = final.free_symbols - deq.free_symbols - {x, y}
|
| 759 |
+
rhs = _simplify_variable_coeff(final, finsyms, solvefun, etat)
|
| 760 |
+
return Eq(f(x, y), rhs)
|
| 761 |
+
|
| 762 |
+
else:
|
| 763 |
+
raise NotImplementedError("Cannot solve the partial differential equation due"
|
| 764 |
+
" to inability of constantsimp")
|
| 765 |
+
|
| 766 |
+
|
| 767 |
+
def _simplify_variable_coeff(sol, syms, func, funcarg):
|
| 768 |
+
r"""
|
| 769 |
+
Helper function to replace constants by functions in 1st_linear_variable_coeff
|
| 770 |
+
"""
|
| 771 |
+
eta = Symbol("eta")
|
| 772 |
+
if len(syms) == 1:
|
| 773 |
+
sym = syms.pop()
|
| 774 |
+
final = sol.subs(sym, func(funcarg))
|
| 775 |
+
|
| 776 |
+
else:
|
| 777 |
+
for sym in syms:
|
| 778 |
+
final = sol.subs(sym, func(funcarg))
|
| 779 |
+
|
| 780 |
+
return simplify(final.subs(eta, funcarg))
|
| 781 |
+
|
| 782 |
+
|
| 783 |
+
def pde_separate(eq, fun, sep, strategy='mul'):
|
| 784 |
+
"""Separate variables in partial differential equation either by additive
|
| 785 |
+
or multiplicative separation approach. It tries to rewrite an equation so
|
| 786 |
+
that one of the specified variables occurs on a different side of the
|
| 787 |
+
equation than the others.
|
| 788 |
+
|
| 789 |
+
:param eq: Partial differential equation
|
| 790 |
+
|
| 791 |
+
:param fun: Original function F(x, y, z)
|
| 792 |
+
|
| 793 |
+
:param sep: List of separated functions [X(x), u(y, z)]
|
| 794 |
+
|
| 795 |
+
:param strategy: Separation strategy. You can choose between additive
|
| 796 |
+
separation ('add') and multiplicative separation ('mul') which is
|
| 797 |
+
default.
|
| 798 |
+
|
| 799 |
+
Examples
|
| 800 |
+
========
|
| 801 |
+
|
| 802 |
+
>>> from sympy import E, Eq, Function, pde_separate, Derivative as D
|
| 803 |
+
>>> from sympy.abc import x, t
|
| 804 |
+
>>> u, X, T = map(Function, 'uXT')
|
| 805 |
+
|
| 806 |
+
>>> eq = Eq(D(u(x, t), x), E**(u(x, t))*D(u(x, t), t))
|
| 807 |
+
>>> pde_separate(eq, u(x, t), [X(x), T(t)], strategy='add')
|
| 808 |
+
[exp(-X(x))*Derivative(X(x), x), exp(T(t))*Derivative(T(t), t)]
|
| 809 |
+
|
| 810 |
+
>>> eq = Eq(D(u(x, t), x, 2), D(u(x, t), t, 2))
|
| 811 |
+
>>> pde_separate(eq, u(x, t), [X(x), T(t)], strategy='mul')
|
| 812 |
+
[Derivative(X(x), (x, 2))/X(x), Derivative(T(t), (t, 2))/T(t)]
|
| 813 |
+
|
| 814 |
+
See Also
|
| 815 |
+
========
|
| 816 |
+
pde_separate_add, pde_separate_mul
|
| 817 |
+
"""
|
| 818 |
+
|
| 819 |
+
do_add = False
|
| 820 |
+
if strategy == 'add':
|
| 821 |
+
do_add = True
|
| 822 |
+
elif strategy == 'mul':
|
| 823 |
+
do_add = False
|
| 824 |
+
else:
|
| 825 |
+
raise ValueError('Unknown strategy: %s' % strategy)
|
| 826 |
+
|
| 827 |
+
if isinstance(eq, Equality):
|
| 828 |
+
if eq.rhs != 0:
|
| 829 |
+
return pde_separate(Eq(eq.lhs - eq.rhs, 0), fun, sep, strategy)
|
| 830 |
+
else:
|
| 831 |
+
return pde_separate(Eq(eq, 0), fun, sep, strategy)
|
| 832 |
+
|
| 833 |
+
if eq.rhs != 0:
|
| 834 |
+
raise ValueError("Value should be 0")
|
| 835 |
+
|
| 836 |
+
# Handle arguments
|
| 837 |
+
orig_args = list(fun.args)
|
| 838 |
+
subs_args = [arg for s in sep for arg in s.args]
|
| 839 |
+
|
| 840 |
+
if do_add:
|
| 841 |
+
functions = reduce(operator.add, sep)
|
| 842 |
+
else:
|
| 843 |
+
functions = reduce(operator.mul, sep)
|
| 844 |
+
|
| 845 |
+
# Check whether variables match
|
| 846 |
+
if len(subs_args) != len(orig_args):
|
| 847 |
+
raise ValueError("Variable counts do not match")
|
| 848 |
+
# Check for duplicate arguments like [X(x), u(x, y)]
|
| 849 |
+
if has_dups(subs_args):
|
| 850 |
+
raise ValueError("Duplicate substitution arguments detected")
|
| 851 |
+
# Check whether the variables match
|
| 852 |
+
if set(orig_args) != set(subs_args):
|
| 853 |
+
raise ValueError("Arguments do not match")
|
| 854 |
+
|
| 855 |
+
# Substitute original function with separated...
|
| 856 |
+
result = eq.lhs.subs(fun, functions).doit()
|
| 857 |
+
|
| 858 |
+
# Divide by terms when doing multiplicative separation
|
| 859 |
+
if not do_add:
|
| 860 |
+
eq = 0
|
| 861 |
+
for i in result.args:
|
| 862 |
+
eq += i/functions
|
| 863 |
+
result = eq
|
| 864 |
+
|
| 865 |
+
svar = subs_args[0]
|
| 866 |
+
dvar = subs_args[1:]
|
| 867 |
+
return _separate(result, svar, dvar)
|
| 868 |
+
|
| 869 |
+
|
| 870 |
+
def pde_separate_add(eq, fun, sep):
|
| 871 |
+
"""
|
| 872 |
+
Helper function for searching additive separable solutions.
|
| 873 |
+
|
| 874 |
+
Consider an equation of two independent variables x, y and a dependent
|
| 875 |
+
variable w, we look for the product of two functions depending on different
|
| 876 |
+
arguments:
|
| 877 |
+
|
| 878 |
+
`w(x, y, z) = X(x) + y(y, z)`
|
| 879 |
+
|
| 880 |
+
Examples
|
| 881 |
+
========
|
| 882 |
+
|
| 883 |
+
>>> from sympy import E, Eq, Function, pde_separate_add, Derivative as D
|
| 884 |
+
>>> from sympy.abc import x, t
|
| 885 |
+
>>> u, X, T = map(Function, 'uXT')
|
| 886 |
+
|
| 887 |
+
>>> eq = Eq(D(u(x, t), x), E**(u(x, t))*D(u(x, t), t))
|
| 888 |
+
>>> pde_separate_add(eq, u(x, t), [X(x), T(t)])
|
| 889 |
+
[exp(-X(x))*Derivative(X(x), x), exp(T(t))*Derivative(T(t), t)]
|
| 890 |
+
|
| 891 |
+
"""
|
| 892 |
+
return pde_separate(eq, fun, sep, strategy='add')
|
| 893 |
+
|
| 894 |
+
|
| 895 |
+
def pde_separate_mul(eq, fun, sep):
|
| 896 |
+
"""
|
| 897 |
+
Helper function for searching multiplicative separable solutions.
|
| 898 |
+
|
| 899 |
+
Consider an equation of two independent variables x, y and a dependent
|
| 900 |
+
variable w, we look for the product of two functions depending on different
|
| 901 |
+
arguments:
|
| 902 |
+
|
| 903 |
+
`w(x, y, z) = X(x)*u(y, z)`
|
| 904 |
+
|
| 905 |
+
Examples
|
| 906 |
+
========
|
| 907 |
+
|
| 908 |
+
>>> from sympy import Function, Eq, pde_separate_mul, Derivative as D
|
| 909 |
+
>>> from sympy.abc import x, y
|
| 910 |
+
>>> u, X, Y = map(Function, 'uXY')
|
| 911 |
+
|
| 912 |
+
>>> eq = Eq(D(u(x, y), x, 2), D(u(x, y), y, 2))
|
| 913 |
+
>>> pde_separate_mul(eq, u(x, y), [X(x), Y(y)])
|
| 914 |
+
[Derivative(X(x), (x, 2))/X(x), Derivative(Y(y), (y, 2))/Y(y)]
|
| 915 |
+
|
| 916 |
+
"""
|
| 917 |
+
return pde_separate(eq, fun, sep, strategy='mul')
|
| 918 |
+
|
| 919 |
+
|
| 920 |
+
def _separate(eq, dep, others):
|
| 921 |
+
"""Separate expression into two parts based on dependencies of variables."""
|
| 922 |
+
|
| 923 |
+
# FIRST PASS
|
| 924 |
+
# Extract derivatives depending our separable variable...
|
| 925 |
+
terms = set()
|
| 926 |
+
for term in eq.args:
|
| 927 |
+
if term.is_Mul:
|
| 928 |
+
for i in term.args:
|
| 929 |
+
if i.is_Derivative and not i.has(*others):
|
| 930 |
+
terms.add(term)
|
| 931 |
+
continue
|
| 932 |
+
elif term.is_Derivative and not term.has(*others):
|
| 933 |
+
terms.add(term)
|
| 934 |
+
# Find the factor that we need to divide by
|
| 935 |
+
div = set()
|
| 936 |
+
for term in terms:
|
| 937 |
+
ext, sep = term.expand().as_independent(dep)
|
| 938 |
+
# Failed?
|
| 939 |
+
if sep.has(*others):
|
| 940 |
+
return None
|
| 941 |
+
div.add(ext)
|
| 942 |
+
# FIXME: Find lcm() of all the divisors and divide with it, instead of
|
| 943 |
+
# current hack :(
|
| 944 |
+
# https://github.com/sympy/sympy/issues/4597
|
| 945 |
+
if len(div) > 0:
|
| 946 |
+
# double sum required or some tests will fail
|
| 947 |
+
eq = Add(*[simplify(Add(*[term/i for i in div])) for term in eq.args])
|
| 948 |
+
# SECOND PASS - separate the derivatives
|
| 949 |
+
div = set()
|
| 950 |
+
lhs = rhs = 0
|
| 951 |
+
for term in eq.args:
|
| 952 |
+
# Check, whether we have already term with independent variable...
|
| 953 |
+
if not term.has(*others):
|
| 954 |
+
lhs += term
|
| 955 |
+
continue
|
| 956 |
+
# ...otherwise, try to separate
|
| 957 |
+
temp, sep = term.expand().as_independent(dep)
|
| 958 |
+
# Failed?
|
| 959 |
+
if sep.has(*others):
|
| 960 |
+
return None
|
| 961 |
+
# Extract the divisors
|
| 962 |
+
div.add(sep)
|
| 963 |
+
rhs -= term.expand()
|
| 964 |
+
# Do the division
|
| 965 |
+
fulldiv = reduce(operator.add, div)
|
| 966 |
+
lhs = simplify(lhs/fulldiv).expand()
|
| 967 |
+
rhs = simplify(rhs/fulldiv).expand()
|
| 968 |
+
# ...and check whether we were successful :)
|
| 969 |
+
if lhs.has(*others) or rhs.has(dep):
|
| 970 |
+
return None
|
| 971 |
+
return [lhs, rhs]
|
evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/polysys.py
ADDED
|
@@ -0,0 +1,437 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Solvers of systems of polynomial equations. """
|
| 2 |
+
import itertools
|
| 3 |
+
|
| 4 |
+
from sympy.core import S
|
| 5 |
+
from sympy.core.sorting import default_sort_key
|
| 6 |
+
from sympy.polys import Poly, groebner, roots
|
| 7 |
+
from sympy.polys.polytools import parallel_poly_from_expr
|
| 8 |
+
from sympy.polys.polyerrors import (ComputationFailed,
|
| 9 |
+
PolificationFailed, CoercionFailed)
|
| 10 |
+
from sympy.simplify import rcollect
|
| 11 |
+
from sympy.utilities import postfixes
|
| 12 |
+
from sympy.utilities.misc import filldedent
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class SolveFailed(Exception):
|
| 16 |
+
"""Raised when solver's conditions were not met. """
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def solve_poly_system(seq, *gens, strict=False, **args):
|
| 20 |
+
"""
|
| 21 |
+
Return a list of solutions for the system of polynomial equations
|
| 22 |
+
or else None.
|
| 23 |
+
|
| 24 |
+
Parameters
|
| 25 |
+
==========
|
| 26 |
+
|
| 27 |
+
seq: a list/tuple/set
|
| 28 |
+
Listing all the equations that are needed to be solved
|
| 29 |
+
gens: generators
|
| 30 |
+
generators of the equations in seq for which we want the
|
| 31 |
+
solutions
|
| 32 |
+
strict: a boolean (default is False)
|
| 33 |
+
if strict is True, NotImplementedError will be raised if
|
| 34 |
+
the solution is known to be incomplete (which can occur if
|
| 35 |
+
not all solutions are expressible in radicals)
|
| 36 |
+
args: Keyword arguments
|
| 37 |
+
Special options for solving the equations.
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
Returns
|
| 41 |
+
=======
|
| 42 |
+
|
| 43 |
+
List[Tuple]
|
| 44 |
+
a list of tuples with elements being solutions for the
|
| 45 |
+
symbols in the order they were passed as gens
|
| 46 |
+
None
|
| 47 |
+
None is returned when the computed basis contains only the ground.
|
| 48 |
+
|
| 49 |
+
Examples
|
| 50 |
+
========
|
| 51 |
+
|
| 52 |
+
>>> from sympy import solve_poly_system
|
| 53 |
+
>>> from sympy.abc import x, y
|
| 54 |
+
|
| 55 |
+
>>> solve_poly_system([x*y - 2*y, 2*y**2 - x**2], x, y)
|
| 56 |
+
[(0, 0), (2, -sqrt(2)), (2, sqrt(2))]
|
| 57 |
+
|
| 58 |
+
>>> solve_poly_system([x**5 - x + y**3, y**2 - 1], x, y, strict=True)
|
| 59 |
+
Traceback (most recent call last):
|
| 60 |
+
...
|
| 61 |
+
UnsolvableFactorError
|
| 62 |
+
|
| 63 |
+
"""
|
| 64 |
+
try:
|
| 65 |
+
polys, opt = parallel_poly_from_expr(seq, *gens, **args)
|
| 66 |
+
except PolificationFailed as exc:
|
| 67 |
+
raise ComputationFailed('solve_poly_system', len(seq), exc)
|
| 68 |
+
|
| 69 |
+
if len(polys) == len(opt.gens) == 2:
|
| 70 |
+
f, g = polys
|
| 71 |
+
|
| 72 |
+
if all(i <= 2 for i in f.degree_list() + g.degree_list()):
|
| 73 |
+
try:
|
| 74 |
+
return solve_biquadratic(f, g, opt)
|
| 75 |
+
except SolveFailed:
|
| 76 |
+
pass
|
| 77 |
+
|
| 78 |
+
return solve_generic(polys, opt, strict=strict)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def solve_biquadratic(f, g, opt):
|
| 82 |
+
"""Solve a system of two bivariate quadratic polynomial equations.
|
| 83 |
+
|
| 84 |
+
Parameters
|
| 85 |
+
==========
|
| 86 |
+
|
| 87 |
+
f: a single Expr or Poly
|
| 88 |
+
First equation
|
| 89 |
+
g: a single Expr or Poly
|
| 90 |
+
Second Equation
|
| 91 |
+
opt: an Options object
|
| 92 |
+
For specifying keyword arguments and generators
|
| 93 |
+
|
| 94 |
+
Returns
|
| 95 |
+
=======
|
| 96 |
+
|
| 97 |
+
List[Tuple]
|
| 98 |
+
a list of tuples with elements being solutions for the
|
| 99 |
+
symbols in the order they were passed as gens
|
| 100 |
+
None
|
| 101 |
+
None is returned when the computed basis contains only the ground.
|
| 102 |
+
|
| 103 |
+
Examples
|
| 104 |
+
========
|
| 105 |
+
|
| 106 |
+
>>> from sympy import Options, Poly
|
| 107 |
+
>>> from sympy.abc import x, y
|
| 108 |
+
>>> from sympy.solvers.polysys import solve_biquadratic
|
| 109 |
+
>>> NewOption = Options((x, y), {'domain': 'ZZ'})
|
| 110 |
+
|
| 111 |
+
>>> a = Poly(y**2 - 4 + x, y, x, domain='ZZ')
|
| 112 |
+
>>> b = Poly(y*2 + 3*x - 7, y, x, domain='ZZ')
|
| 113 |
+
>>> solve_biquadratic(a, b, NewOption)
|
| 114 |
+
[(1/3, 3), (41/27, 11/9)]
|
| 115 |
+
|
| 116 |
+
>>> a = Poly(y + x**2 - 3, y, x, domain='ZZ')
|
| 117 |
+
>>> b = Poly(-y + x - 4, y, x, domain='ZZ')
|
| 118 |
+
>>> solve_biquadratic(a, b, NewOption)
|
| 119 |
+
[(7/2 - sqrt(29)/2, -sqrt(29)/2 - 1/2), (sqrt(29)/2 + 7/2, -1/2 + \
|
| 120 |
+
sqrt(29)/2)]
|
| 121 |
+
"""
|
| 122 |
+
G = groebner([f, g])
|
| 123 |
+
|
| 124 |
+
if len(G) == 1 and G[0].is_ground:
|
| 125 |
+
return None
|
| 126 |
+
|
| 127 |
+
if len(G) != 2:
|
| 128 |
+
raise SolveFailed
|
| 129 |
+
|
| 130 |
+
x, y = opt.gens
|
| 131 |
+
p, q = G
|
| 132 |
+
if not p.gcd(q).is_ground:
|
| 133 |
+
# not 0-dimensional
|
| 134 |
+
raise SolveFailed
|
| 135 |
+
|
| 136 |
+
p = Poly(p, x, expand=False)
|
| 137 |
+
p_roots = [rcollect(expr, y) for expr in roots(p).keys()]
|
| 138 |
+
|
| 139 |
+
q = q.ltrim(-1)
|
| 140 |
+
q_roots = list(roots(q).keys())
|
| 141 |
+
|
| 142 |
+
solutions = [(p_root.subs(y, q_root), q_root) for q_root, p_root in
|
| 143 |
+
itertools.product(q_roots, p_roots)]
|
| 144 |
+
|
| 145 |
+
return sorted(solutions, key=default_sort_key)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def solve_generic(polys, opt, strict=False):
|
| 149 |
+
"""
|
| 150 |
+
Solve a generic system of polynomial equations.
|
| 151 |
+
|
| 152 |
+
Returns all possible solutions over C[x_1, x_2, ..., x_m] of a
|
| 153 |
+
set F = { f_1, f_2, ..., f_n } of polynomial equations, using
|
| 154 |
+
Groebner basis approach. For now only zero-dimensional systems
|
| 155 |
+
are supported, which means F can have at most a finite number
|
| 156 |
+
of solutions. If the basis contains only the ground, None is
|
| 157 |
+
returned.
|
| 158 |
+
|
| 159 |
+
The algorithm works by the fact that, supposing G is the basis
|
| 160 |
+
of F with respect to an elimination order (here lexicographic
|
| 161 |
+
order is used), G and F generate the same ideal, they have the
|
| 162 |
+
same set of solutions. By the elimination property, if G is a
|
| 163 |
+
reduced, zero-dimensional Groebner basis, then there exists an
|
| 164 |
+
univariate polynomial in G (in its last variable). This can be
|
| 165 |
+
solved by computing its roots. Substituting all computed roots
|
| 166 |
+
for the last (eliminated) variable in other elements of G, new
|
| 167 |
+
polynomial system is generated. Applying the above procedure
|
| 168 |
+
recursively, a finite number of solutions can be found.
|
| 169 |
+
|
| 170 |
+
The ability of finding all solutions by this procedure depends
|
| 171 |
+
on the root finding algorithms. If no solutions were found, it
|
| 172 |
+
means only that roots() failed, but the system is solvable. To
|
| 173 |
+
overcome this difficulty use numerical algorithms instead.
|
| 174 |
+
|
| 175 |
+
Parameters
|
| 176 |
+
==========
|
| 177 |
+
|
| 178 |
+
polys: a list/tuple/set
|
| 179 |
+
Listing all the polynomial equations that are needed to be solved
|
| 180 |
+
opt: an Options object
|
| 181 |
+
For specifying keyword arguments and generators
|
| 182 |
+
strict: a boolean
|
| 183 |
+
If strict is True, NotImplementedError will be raised if the solution
|
| 184 |
+
is known to be incomplete
|
| 185 |
+
|
| 186 |
+
Returns
|
| 187 |
+
=======
|
| 188 |
+
|
| 189 |
+
List[Tuple]
|
| 190 |
+
a list of tuples with elements being solutions for the
|
| 191 |
+
symbols in the order they were passed as gens
|
| 192 |
+
None
|
| 193 |
+
None is returned when the computed basis contains only the ground.
|
| 194 |
+
|
| 195 |
+
References
|
| 196 |
+
==========
|
| 197 |
+
|
| 198 |
+
.. [Buchberger01] B. Buchberger, Groebner Bases: A Short
|
| 199 |
+
Introduction for Systems Theorists, In: R. Moreno-Diaz,
|
| 200 |
+
B. Buchberger, J.L. Freire, Proceedings of EUROCAST'01,
|
| 201 |
+
February, 2001
|
| 202 |
+
|
| 203 |
+
.. [Cox97] D. Cox, J. Little, D. O'Shea, Ideals, Varieties
|
| 204 |
+
and Algorithms, Springer, Second Edition, 1997, pp. 112
|
| 205 |
+
|
| 206 |
+
Raises
|
| 207 |
+
========
|
| 208 |
+
|
| 209 |
+
NotImplementedError
|
| 210 |
+
If the system is not zero-dimensional (does not have a finite
|
| 211 |
+
number of solutions)
|
| 212 |
+
|
| 213 |
+
UnsolvableFactorError
|
| 214 |
+
If ``strict`` is True and not all solution components are
|
| 215 |
+
expressible in radicals
|
| 216 |
+
|
| 217 |
+
Examples
|
| 218 |
+
========
|
| 219 |
+
|
| 220 |
+
>>> from sympy import Poly, Options
|
| 221 |
+
>>> from sympy.solvers.polysys import solve_generic
|
| 222 |
+
>>> from sympy.abc import x, y
|
| 223 |
+
>>> NewOption = Options((x, y), {'domain': 'ZZ'})
|
| 224 |
+
|
| 225 |
+
>>> a = Poly(x - y + 5, x, y, domain='ZZ')
|
| 226 |
+
>>> b = Poly(x + y - 3, x, y, domain='ZZ')
|
| 227 |
+
>>> solve_generic([a, b], NewOption)
|
| 228 |
+
[(-1, 4)]
|
| 229 |
+
|
| 230 |
+
>>> a = Poly(x - 2*y + 5, x, y, domain='ZZ')
|
| 231 |
+
>>> b = Poly(2*x - y - 3, x, y, domain='ZZ')
|
| 232 |
+
>>> solve_generic([a, b], NewOption)
|
| 233 |
+
[(11/3, 13/3)]
|
| 234 |
+
|
| 235 |
+
>>> a = Poly(x**2 + y, x, y, domain='ZZ')
|
| 236 |
+
>>> b = Poly(x + y*4, x, y, domain='ZZ')
|
| 237 |
+
>>> solve_generic([a, b], NewOption)
|
| 238 |
+
[(0, 0), (1/4, -1/16)]
|
| 239 |
+
|
| 240 |
+
>>> a = Poly(x**5 - x + y**3, x, y, domain='ZZ')
|
| 241 |
+
>>> b = Poly(y**2 - 1, x, y, domain='ZZ')
|
| 242 |
+
>>> solve_generic([a, b], NewOption, strict=True)
|
| 243 |
+
Traceback (most recent call last):
|
| 244 |
+
...
|
| 245 |
+
UnsolvableFactorError
|
| 246 |
+
|
| 247 |
+
"""
|
| 248 |
+
def _is_univariate(f):
|
| 249 |
+
"""Returns True if 'f' is univariate in its last variable. """
|
| 250 |
+
for monom in f.monoms():
|
| 251 |
+
if any(monom[:-1]):
|
| 252 |
+
return False
|
| 253 |
+
|
| 254 |
+
return True
|
| 255 |
+
|
| 256 |
+
def _subs_root(f, gen, zero):
|
| 257 |
+
"""Replace generator with a root so that the result is nice. """
|
| 258 |
+
p = f.as_expr({gen: zero})
|
| 259 |
+
|
| 260 |
+
if f.degree(gen) >= 2:
|
| 261 |
+
p = p.expand(deep=False)
|
| 262 |
+
|
| 263 |
+
return p
|
| 264 |
+
|
| 265 |
+
def _solve_reduced_system(system, gens, entry=False):
|
| 266 |
+
"""Recursively solves reduced polynomial systems. """
|
| 267 |
+
if len(system) == len(gens) == 1:
|
| 268 |
+
# the below line will produce UnsolvableFactorError if
|
| 269 |
+
# strict=True and the solution from `roots` is incomplete
|
| 270 |
+
zeros = list(roots(system[0], gens[-1], strict=strict).keys())
|
| 271 |
+
return [(zero,) for zero in zeros]
|
| 272 |
+
|
| 273 |
+
basis = groebner(system, gens, polys=True)
|
| 274 |
+
|
| 275 |
+
if len(basis) == 1 and basis[0].is_ground:
|
| 276 |
+
if not entry:
|
| 277 |
+
return []
|
| 278 |
+
else:
|
| 279 |
+
return None
|
| 280 |
+
|
| 281 |
+
univariate = list(filter(_is_univariate, basis))
|
| 282 |
+
|
| 283 |
+
if len(basis) < len(gens):
|
| 284 |
+
raise NotImplementedError(filldedent('''
|
| 285 |
+
only zero-dimensional systems supported
|
| 286 |
+
(finite number of solutions)
|
| 287 |
+
'''))
|
| 288 |
+
|
| 289 |
+
if len(univariate) == 1:
|
| 290 |
+
f = univariate.pop()
|
| 291 |
+
else:
|
| 292 |
+
raise NotImplementedError(filldedent('''
|
| 293 |
+
only zero-dimensional systems supported
|
| 294 |
+
(finite number of solutions)
|
| 295 |
+
'''))
|
| 296 |
+
|
| 297 |
+
gens = f.gens
|
| 298 |
+
gen = gens[-1]
|
| 299 |
+
|
| 300 |
+
# the below line will produce UnsolvableFactorError if
|
| 301 |
+
# strict=True and the solution from `roots` is incomplete
|
| 302 |
+
zeros = list(roots(f.ltrim(gen), strict=strict).keys())
|
| 303 |
+
|
| 304 |
+
if not zeros:
|
| 305 |
+
return []
|
| 306 |
+
|
| 307 |
+
if len(basis) == 1:
|
| 308 |
+
return [(zero,) for zero in zeros]
|
| 309 |
+
|
| 310 |
+
solutions = []
|
| 311 |
+
|
| 312 |
+
for zero in zeros:
|
| 313 |
+
new_system = []
|
| 314 |
+
new_gens = gens[:-1]
|
| 315 |
+
|
| 316 |
+
for b in basis[:-1]:
|
| 317 |
+
eq = _subs_root(b, gen, zero)
|
| 318 |
+
|
| 319 |
+
if eq is not S.Zero:
|
| 320 |
+
new_system.append(eq)
|
| 321 |
+
|
| 322 |
+
for solution in _solve_reduced_system(new_system, new_gens):
|
| 323 |
+
solutions.append(solution + (zero,))
|
| 324 |
+
|
| 325 |
+
if solutions and len(solutions[0]) != len(gens):
|
| 326 |
+
raise NotImplementedError(filldedent('''
|
| 327 |
+
only zero-dimensional systems supported
|
| 328 |
+
(finite number of solutions)
|
| 329 |
+
'''))
|
| 330 |
+
return solutions
|
| 331 |
+
|
| 332 |
+
try:
|
| 333 |
+
result = _solve_reduced_system(polys, opt.gens, entry=True)
|
| 334 |
+
except CoercionFailed:
|
| 335 |
+
raise NotImplementedError
|
| 336 |
+
|
| 337 |
+
if result is not None:
|
| 338 |
+
return sorted(result, key=default_sort_key)
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
def solve_triangulated(polys, *gens, **args):
|
| 342 |
+
"""
|
| 343 |
+
Solve a polynomial system using Gianni-Kalkbrenner algorithm.
|
| 344 |
+
|
| 345 |
+
The algorithm proceeds by computing one Groebner basis in the ground
|
| 346 |
+
domain and then by iteratively computing polynomial factorizations in
|
| 347 |
+
appropriately constructed algebraic extensions of the ground domain.
|
| 348 |
+
|
| 349 |
+
Parameters
|
| 350 |
+
==========
|
| 351 |
+
|
| 352 |
+
polys: a list/tuple/set
|
| 353 |
+
Listing all the equations that are needed to be solved
|
| 354 |
+
gens: generators
|
| 355 |
+
generators of the equations in polys for which we want the
|
| 356 |
+
solutions
|
| 357 |
+
args: Keyword arguments
|
| 358 |
+
Special options for solving the equations
|
| 359 |
+
|
| 360 |
+
Returns
|
| 361 |
+
=======
|
| 362 |
+
|
| 363 |
+
List[Tuple]
|
| 364 |
+
A List of tuples. Solutions for symbols that satisfy the
|
| 365 |
+
equations listed in polys
|
| 366 |
+
|
| 367 |
+
Examples
|
| 368 |
+
========
|
| 369 |
+
|
| 370 |
+
>>> from sympy import solve_triangulated
|
| 371 |
+
>>> from sympy.abc import x, y, z
|
| 372 |
+
|
| 373 |
+
>>> F = [x**2 + y + z - 1, x + y**2 + z - 1, x + y + z**2 - 1]
|
| 374 |
+
|
| 375 |
+
>>> solve_triangulated(F, x, y, z)
|
| 376 |
+
[(0, 0, 1), (0, 1, 0), (1, 0, 0)]
|
| 377 |
+
|
| 378 |
+
References
|
| 379 |
+
==========
|
| 380 |
+
|
| 381 |
+
1. Patrizia Gianni, Teo Mora, Algebraic Solution of System of
|
| 382 |
+
Polynomial Equations using Groebner Bases, AAECC-5 on Applied Algebra,
|
| 383 |
+
Algebraic Algorithms and Error-Correcting Codes, LNCS 356 247--257, 1989
|
| 384 |
+
|
| 385 |
+
"""
|
| 386 |
+
G = groebner(polys, gens, polys=True)
|
| 387 |
+
G = list(reversed(G))
|
| 388 |
+
|
| 389 |
+
domain = args.get('domain')
|
| 390 |
+
|
| 391 |
+
if domain is not None:
|
| 392 |
+
for i, g in enumerate(G):
|
| 393 |
+
G[i] = g.set_domain(domain)
|
| 394 |
+
|
| 395 |
+
f, G = G[0].ltrim(-1), G[1:]
|
| 396 |
+
dom = f.get_domain()
|
| 397 |
+
|
| 398 |
+
zeros = f.ground_roots()
|
| 399 |
+
solutions = {((zero,), dom) for zero in zeros}
|
| 400 |
+
|
| 401 |
+
var_seq = reversed(gens[:-1])
|
| 402 |
+
vars_seq = postfixes(gens[1:])
|
| 403 |
+
|
| 404 |
+
for var, vars in zip(var_seq, vars_seq):
|
| 405 |
+
_solutions = set()
|
| 406 |
+
|
| 407 |
+
for values, dom in solutions:
|
| 408 |
+
H, mapping = [], list(zip(vars, values))
|
| 409 |
+
|
| 410 |
+
for g in G:
|
| 411 |
+
_vars = (var,) + vars
|
| 412 |
+
|
| 413 |
+
if g.has_only_gens(*_vars) and g.degree(var) != 0:
|
| 414 |
+
h = g.ltrim(var).eval(dict(mapping))
|
| 415 |
+
|
| 416 |
+
if g.degree(var) == h.degree():
|
| 417 |
+
H.append(h)
|
| 418 |
+
|
| 419 |
+
p = min(H, key=lambda h: h.degree())
|
| 420 |
+
zeros = p.ground_roots()
|
| 421 |
+
|
| 422 |
+
for zero in zeros:
|
| 423 |
+
if not zero.is_Rational:
|
| 424 |
+
dom_zero = dom.algebraic_field(zero)
|
| 425 |
+
else:
|
| 426 |
+
dom_zero = dom
|
| 427 |
+
|
| 428 |
+
_solutions.add(((zero,) + values, dom_zero))
|
| 429 |
+
|
| 430 |
+
solutions = _solutions
|
| 431 |
+
|
| 432 |
+
solutions = list(solutions)
|
| 433 |
+
|
| 434 |
+
for i, (solution, _) in enumerate(solutions):
|
| 435 |
+
solutions[i] = solution
|
| 436 |
+
|
| 437 |
+
return sorted(solutions, key=default_sort_key)
|
evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/recurr.py
ADDED
|
@@ -0,0 +1,843 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r"""
|
| 2 |
+
This module is intended for solving recurrences or, in other words,
|
| 3 |
+
difference equations. Currently supported are linear, inhomogeneous
|
| 4 |
+
equations with polynomial or rational coefficients.
|
| 5 |
+
|
| 6 |
+
The solutions are obtained among polynomials, rational functions,
|
| 7 |
+
hypergeometric terms, or combinations of hypergeometric term which
|
| 8 |
+
are pairwise dissimilar.
|
| 9 |
+
|
| 10 |
+
``rsolve_X`` functions were meant as a low level interface
|
| 11 |
+
for ``rsolve`` which would use Mathematica's syntax.
|
| 12 |
+
|
| 13 |
+
Given a recurrence relation:
|
| 14 |
+
|
| 15 |
+
.. math:: a_{k}(n) y(n+k) + a_{k-1}(n) y(n+k-1) +
|
| 16 |
+
... + a_{0}(n) y(n) = f(n)
|
| 17 |
+
|
| 18 |
+
where `k > 0` and `a_{i}(n)` are polynomials in `n`. To use
|
| 19 |
+
``rsolve_X`` we need to put all coefficients in to a list ``L`` of
|
| 20 |
+
`k+1` elements the following way:
|
| 21 |
+
|
| 22 |
+
``L = [a_{0}(n), ..., a_{k-1}(n), a_{k}(n)]``
|
| 23 |
+
|
| 24 |
+
where ``L[i]``, for `i=0, \ldots, k`, maps to
|
| 25 |
+
`a_{i}(n) y(n+i)` (`y(n+i)` is implicit).
|
| 26 |
+
|
| 27 |
+
For example if we would like to compute `m`-th Bernoulli polynomial
|
| 28 |
+
up to a constant (example was taken from rsolve_poly docstring),
|
| 29 |
+
then we would use `b(n+1) - b(n) = m n^{m-1}` recurrence, which
|
| 30 |
+
has solution `b(n) = B_m + C`.
|
| 31 |
+
|
| 32 |
+
Then ``L = [-1, 1]`` and `f(n) = m n^(m-1)` and finally for `m=4`:
|
| 33 |
+
|
| 34 |
+
>>> from sympy import Symbol, bernoulli, rsolve_poly
|
| 35 |
+
>>> n = Symbol('n', integer=True)
|
| 36 |
+
|
| 37 |
+
>>> rsolve_poly([-1, 1], 4*n**3, n)
|
| 38 |
+
C0 + n**4 - 2*n**3 + n**2
|
| 39 |
+
|
| 40 |
+
>>> bernoulli(4, n)
|
| 41 |
+
n**4 - 2*n**3 + n**2 - 1/30
|
| 42 |
+
|
| 43 |
+
For the sake of completeness, `f(n)` can be:
|
| 44 |
+
|
| 45 |
+
[1] a polynomial -> rsolve_poly
|
| 46 |
+
[2] a rational function -> rsolve_ratio
|
| 47 |
+
[3] a hypergeometric function -> rsolve_hyper
|
| 48 |
+
"""
|
| 49 |
+
from collections import defaultdict
|
| 50 |
+
|
| 51 |
+
from sympy.concrete import product
|
| 52 |
+
from sympy.core.singleton import S
|
| 53 |
+
from sympy.core.numbers import Rational, I
|
| 54 |
+
from sympy.core.symbol import Symbol, Wild, Dummy
|
| 55 |
+
from sympy.core.relational import Equality
|
| 56 |
+
from sympy.core.add import Add
|
| 57 |
+
from sympy.core.mul import Mul
|
| 58 |
+
from sympy.core.sorting import default_sort_key
|
| 59 |
+
from sympy.core.sympify import sympify
|
| 60 |
+
|
| 61 |
+
from sympy.simplify import simplify, hypersimp, hypersimilar # type: ignore
|
| 62 |
+
from sympy.solvers import solve, solve_undetermined_coeffs
|
| 63 |
+
from sympy.polys import Poly, quo, gcd, lcm, roots, resultant
|
| 64 |
+
from sympy.functions import binomial, factorial, FallingFactorial, RisingFactorial
|
| 65 |
+
from sympy.matrices import Matrix, casoratian
|
| 66 |
+
from sympy.utilities.iterables import numbered_symbols
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def rsolve_poly(coeffs, f, n, shift=0, **hints):
|
| 70 |
+
r"""
|
| 71 |
+
Given linear recurrence operator `\operatorname{L}` of order
|
| 72 |
+
`k` with polynomial coefficients and inhomogeneous equation
|
| 73 |
+
`\operatorname{L} y = f`, where `f` is a polynomial, we seek for
|
| 74 |
+
all polynomial solutions over field `K` of characteristic zero.
|
| 75 |
+
|
| 76 |
+
The algorithm performs two basic steps:
|
| 77 |
+
|
| 78 |
+
(1) Compute degree `N` of the general polynomial solution.
|
| 79 |
+
(2) Find all polynomials of degree `N` or less
|
| 80 |
+
of `\operatorname{L} y = f`.
|
| 81 |
+
|
| 82 |
+
There are two methods for computing the polynomial solutions.
|
| 83 |
+
If the degree bound is relatively small, i.e. it's smaller than
|
| 84 |
+
or equal to the order of the recurrence, then naive method of
|
| 85 |
+
undetermined coefficients is being used. This gives a system
|
| 86 |
+
of algebraic equations with `N+1` unknowns.
|
| 87 |
+
|
| 88 |
+
In the other case, the algorithm performs transformation of the
|
| 89 |
+
initial equation to an equivalent one for which the system of
|
| 90 |
+
algebraic equations has only `r` indeterminates. This method is
|
| 91 |
+
quite sophisticated (in comparison with the naive one) and was
|
| 92 |
+
invented together by Abramov, Bronstein and Petkovsek.
|
| 93 |
+
|
| 94 |
+
It is possible to generalize the algorithm implemented here to
|
| 95 |
+
the case of linear q-difference and differential equations.
|
| 96 |
+
|
| 97 |
+
Lets say that we would like to compute `m`-th Bernoulli polynomial
|
| 98 |
+
up to a constant. For this we can use `b(n+1) - b(n) = m n^{m-1}`
|
| 99 |
+
recurrence, which has solution `b(n) = B_m + C`. For example:
|
| 100 |
+
|
| 101 |
+
>>> from sympy import Symbol, rsolve_poly
|
| 102 |
+
>>> n = Symbol('n', integer=True)
|
| 103 |
+
|
| 104 |
+
>>> rsolve_poly([-1, 1], 4*n**3, n)
|
| 105 |
+
C0 + n**4 - 2*n**3 + n**2
|
| 106 |
+
|
| 107 |
+
References
|
| 108 |
+
==========
|
| 109 |
+
|
| 110 |
+
.. [1] S. A. Abramov, M. Bronstein and M. Petkovsek, On polynomial
|
| 111 |
+
solutions of linear operator equations, in: T. Levelt, ed.,
|
| 112 |
+
Proc. ISSAC '95, ACM Press, New York, 1995, 290-296.
|
| 113 |
+
|
| 114 |
+
.. [2] M. Petkovsek, Hypergeometric solutions of linear recurrences
|
| 115 |
+
with polynomial coefficients, J. Symbolic Computation,
|
| 116 |
+
14 (1992), 243-264.
|
| 117 |
+
|
| 118 |
+
.. [3] M. Petkovsek, H. S. Wilf, D. Zeilberger, A = B, 1996.
|
| 119 |
+
|
| 120 |
+
"""
|
| 121 |
+
f = sympify(f)
|
| 122 |
+
|
| 123 |
+
if not f.is_polynomial(n):
|
| 124 |
+
return None
|
| 125 |
+
|
| 126 |
+
homogeneous = f.is_zero
|
| 127 |
+
|
| 128 |
+
r = len(coeffs) - 1
|
| 129 |
+
|
| 130 |
+
coeffs = [Poly(coeff, n) for coeff in coeffs]
|
| 131 |
+
|
| 132 |
+
polys = [Poly(0, n)]*(r + 1)
|
| 133 |
+
terms = [(S.Zero, S.NegativeInfinity)]*(r + 1)
|
| 134 |
+
|
| 135 |
+
for i in range(r + 1):
|
| 136 |
+
for j in range(i, r + 1):
|
| 137 |
+
polys[i] += coeffs[j]*(binomial(j, i).as_poly(n))
|
| 138 |
+
|
| 139 |
+
if not polys[i].is_zero:
|
| 140 |
+
(exp,), coeff = polys[i].LT()
|
| 141 |
+
terms[i] = (coeff, exp)
|
| 142 |
+
|
| 143 |
+
d = b = terms[0][1]
|
| 144 |
+
|
| 145 |
+
for i in range(1, r + 1):
|
| 146 |
+
if terms[i][1] > d:
|
| 147 |
+
d = terms[i][1]
|
| 148 |
+
|
| 149 |
+
if terms[i][1] - i > b:
|
| 150 |
+
b = terms[i][1] - i
|
| 151 |
+
|
| 152 |
+
d, b = int(d), int(b)
|
| 153 |
+
|
| 154 |
+
x = Dummy('x')
|
| 155 |
+
|
| 156 |
+
degree_poly = S.Zero
|
| 157 |
+
|
| 158 |
+
for i in range(r + 1):
|
| 159 |
+
if terms[i][1] - i == b:
|
| 160 |
+
degree_poly += terms[i][0]*FallingFactorial(x, i)
|
| 161 |
+
|
| 162 |
+
nni_roots = list(roots(degree_poly, x, filter='Z',
|
| 163 |
+
predicate=lambda r: r >= 0).keys())
|
| 164 |
+
|
| 165 |
+
if nni_roots:
|
| 166 |
+
N = [max(nni_roots)]
|
| 167 |
+
else:
|
| 168 |
+
N = []
|
| 169 |
+
|
| 170 |
+
if homogeneous:
|
| 171 |
+
N += [-b - 1]
|
| 172 |
+
else:
|
| 173 |
+
N += [f.as_poly(n).degree() - b, -b - 1]
|
| 174 |
+
|
| 175 |
+
N = int(max(N))
|
| 176 |
+
|
| 177 |
+
if N < 0:
|
| 178 |
+
if homogeneous:
|
| 179 |
+
if hints.get('symbols', False):
|
| 180 |
+
return (S.Zero, [])
|
| 181 |
+
else:
|
| 182 |
+
return S.Zero
|
| 183 |
+
else:
|
| 184 |
+
return None
|
| 185 |
+
|
| 186 |
+
if N <= r:
|
| 187 |
+
C = []
|
| 188 |
+
y = E = S.Zero
|
| 189 |
+
|
| 190 |
+
for i in range(N + 1):
|
| 191 |
+
C.append(Symbol('C' + str(i + shift)))
|
| 192 |
+
y += C[i] * n**i
|
| 193 |
+
|
| 194 |
+
for i in range(r + 1):
|
| 195 |
+
E += coeffs[i].as_expr()*y.subs(n, n + i)
|
| 196 |
+
|
| 197 |
+
solutions = solve_undetermined_coeffs(E - f, C, n)
|
| 198 |
+
|
| 199 |
+
if solutions is not None:
|
| 200 |
+
_C = C
|
| 201 |
+
C = [c for c in C if (c not in solutions)]
|
| 202 |
+
result = y.subs(solutions)
|
| 203 |
+
else:
|
| 204 |
+
return None # TBD
|
| 205 |
+
else:
|
| 206 |
+
A = r
|
| 207 |
+
U = N + A + b + 1
|
| 208 |
+
|
| 209 |
+
nni_roots = list(roots(polys[r], filter='Z',
|
| 210 |
+
predicate=lambda r: r >= 0).keys())
|
| 211 |
+
|
| 212 |
+
if nni_roots != []:
|
| 213 |
+
a = max(nni_roots) + 1
|
| 214 |
+
else:
|
| 215 |
+
a = S.Zero
|
| 216 |
+
|
| 217 |
+
def _zero_vector(k):
|
| 218 |
+
return [S.Zero] * k
|
| 219 |
+
|
| 220 |
+
def _one_vector(k):
|
| 221 |
+
return [S.One] * k
|
| 222 |
+
|
| 223 |
+
def _delta(p, k):
|
| 224 |
+
B = S.One
|
| 225 |
+
D = p.subs(n, a + k)
|
| 226 |
+
|
| 227 |
+
for i in range(1, k + 1):
|
| 228 |
+
B *= Rational(i - k - 1, i)
|
| 229 |
+
D += B * p.subs(n, a + k - i)
|
| 230 |
+
|
| 231 |
+
return D
|
| 232 |
+
|
| 233 |
+
alpha = {}
|
| 234 |
+
|
| 235 |
+
for i in range(-A, d + 1):
|
| 236 |
+
I = _one_vector(d + 1)
|
| 237 |
+
|
| 238 |
+
for k in range(1, d + 1):
|
| 239 |
+
I[k] = I[k - 1] * (x + i - k + 1)/k
|
| 240 |
+
|
| 241 |
+
alpha[i] = S.Zero
|
| 242 |
+
|
| 243 |
+
for j in range(A + 1):
|
| 244 |
+
for k in range(d + 1):
|
| 245 |
+
B = binomial(k, i + j)
|
| 246 |
+
D = _delta(polys[j].as_expr(), k)
|
| 247 |
+
|
| 248 |
+
alpha[i] += I[k]*B*D
|
| 249 |
+
|
| 250 |
+
V = Matrix(U, A, lambda i, j: int(i == j))
|
| 251 |
+
|
| 252 |
+
if homogeneous:
|
| 253 |
+
for i in range(A, U):
|
| 254 |
+
v = _zero_vector(A)
|
| 255 |
+
|
| 256 |
+
for k in range(1, A + b + 1):
|
| 257 |
+
if i - k < 0:
|
| 258 |
+
break
|
| 259 |
+
|
| 260 |
+
B = alpha[k - A].subs(x, i - k)
|
| 261 |
+
|
| 262 |
+
for j in range(A):
|
| 263 |
+
v[j] += B * V[i - k, j]
|
| 264 |
+
|
| 265 |
+
denom = alpha[-A].subs(x, i)
|
| 266 |
+
|
| 267 |
+
for j in range(A):
|
| 268 |
+
V[i, j] = -v[j] / denom
|
| 269 |
+
else:
|
| 270 |
+
G = _zero_vector(U)
|
| 271 |
+
|
| 272 |
+
for i in range(A, U):
|
| 273 |
+
v = _zero_vector(A)
|
| 274 |
+
g = S.Zero
|
| 275 |
+
|
| 276 |
+
for k in range(1, A + b + 1):
|
| 277 |
+
if i - k < 0:
|
| 278 |
+
break
|
| 279 |
+
|
| 280 |
+
B = alpha[k - A].subs(x, i - k)
|
| 281 |
+
|
| 282 |
+
for j in range(A):
|
| 283 |
+
v[j] += B * V[i - k, j]
|
| 284 |
+
|
| 285 |
+
g += B * G[i - k]
|
| 286 |
+
|
| 287 |
+
denom = alpha[-A].subs(x, i)
|
| 288 |
+
|
| 289 |
+
for j in range(A):
|
| 290 |
+
V[i, j] = -v[j] / denom
|
| 291 |
+
|
| 292 |
+
G[i] = (_delta(f, i - A) - g) / denom
|
| 293 |
+
|
| 294 |
+
P, Q = _one_vector(U), _zero_vector(A)
|
| 295 |
+
|
| 296 |
+
for i in range(1, U):
|
| 297 |
+
P[i] = (P[i - 1] * (n - a - i + 1)/i).expand()
|
| 298 |
+
|
| 299 |
+
for i in range(A):
|
| 300 |
+
Q[i] = Add(*[(v*p).expand() for v, p in zip(V[:, i], P)])
|
| 301 |
+
|
| 302 |
+
if not homogeneous:
|
| 303 |
+
h = Add(*[(g*p).expand() for g, p in zip(G, P)])
|
| 304 |
+
|
| 305 |
+
C = [Symbol('C' + str(i + shift)) for i in range(A)]
|
| 306 |
+
|
| 307 |
+
g = lambda i: Add(*[c*_delta(q, i) for c, q in zip(C, Q)])
|
| 308 |
+
|
| 309 |
+
if homogeneous:
|
| 310 |
+
E = [g(i) for i in range(N + 1, U)]
|
| 311 |
+
else:
|
| 312 |
+
E = [g(i) + _delta(h, i) for i in range(N + 1, U)]
|
| 313 |
+
|
| 314 |
+
if E != []:
|
| 315 |
+
solutions = solve(E, *C)
|
| 316 |
+
|
| 317 |
+
if not solutions:
|
| 318 |
+
if homogeneous:
|
| 319 |
+
if hints.get('symbols', False):
|
| 320 |
+
return (S.Zero, [])
|
| 321 |
+
else:
|
| 322 |
+
return S.Zero
|
| 323 |
+
else:
|
| 324 |
+
return None
|
| 325 |
+
else:
|
| 326 |
+
solutions = {}
|
| 327 |
+
|
| 328 |
+
if homogeneous:
|
| 329 |
+
result = S.Zero
|
| 330 |
+
else:
|
| 331 |
+
result = h
|
| 332 |
+
|
| 333 |
+
_C = C[:]
|
| 334 |
+
for c, q in list(zip(C, Q)):
|
| 335 |
+
if c in solutions:
|
| 336 |
+
s = solutions[c]*q
|
| 337 |
+
C.remove(c)
|
| 338 |
+
else:
|
| 339 |
+
s = c*q
|
| 340 |
+
|
| 341 |
+
result += s.expand()
|
| 342 |
+
|
| 343 |
+
if C != _C:
|
| 344 |
+
# renumber so they are contiguous
|
| 345 |
+
result = result.xreplace(dict(zip(C, _C)))
|
| 346 |
+
C = _C[:len(C)]
|
| 347 |
+
|
| 348 |
+
if hints.get('symbols', False):
|
| 349 |
+
return (result, C)
|
| 350 |
+
else:
|
| 351 |
+
return result
|
| 352 |
+
|
| 353 |
+
|
| 354 |
+
def rsolve_ratio(coeffs, f, n, **hints):
|
| 355 |
+
r"""
|
| 356 |
+
Given linear recurrence operator `\operatorname{L}` of order `k`
|
| 357 |
+
with polynomial coefficients and inhomogeneous equation
|
| 358 |
+
`\operatorname{L} y = f`, where `f` is a polynomial, we seek
|
| 359 |
+
for all rational solutions over field `K` of characteristic zero.
|
| 360 |
+
|
| 361 |
+
This procedure accepts only polynomials, however if you are
|
| 362 |
+
interested in solving recurrence with rational coefficients
|
| 363 |
+
then use ``rsolve`` which will pre-process the given equation
|
| 364 |
+
and run this procedure with polynomial arguments.
|
| 365 |
+
|
| 366 |
+
The algorithm performs two basic steps:
|
| 367 |
+
|
| 368 |
+
(1) Compute polynomial `v(n)` which can be used as universal
|
| 369 |
+
denominator of any rational solution of equation
|
| 370 |
+
`\operatorname{L} y = f`.
|
| 371 |
+
|
| 372 |
+
(2) Construct new linear difference equation by substitution
|
| 373 |
+
`y(n) = u(n)/v(n)` and solve it for `u(n)` finding all its
|
| 374 |
+
polynomial solutions. Return ``None`` if none were found.
|
| 375 |
+
|
| 376 |
+
The algorithm implemented here is a revised version of the original
|
| 377 |
+
Abramov's algorithm, developed in 1989. The new approach is much
|
| 378 |
+
simpler to implement and has better overall efficiency. This
|
| 379 |
+
method can be easily adapted to the q-difference equations case.
|
| 380 |
+
|
| 381 |
+
Besides finding rational solutions alone, this functions is
|
| 382 |
+
an important part of Hyper algorithm where it is used to find
|
| 383 |
+
a particular solution for the inhomogeneous part of a recurrence.
|
| 384 |
+
|
| 385 |
+
Examples
|
| 386 |
+
========
|
| 387 |
+
|
| 388 |
+
>>> from sympy.abc import x
|
| 389 |
+
>>> from sympy.solvers.recurr import rsolve_ratio
|
| 390 |
+
>>> rsolve_ratio([-2*x**3 + x**2 + 2*x - 1, 2*x**3 + x**2 - 6*x,
|
| 391 |
+
... - 2*x**3 - 11*x**2 - 18*x - 9, 2*x**3 + 13*x**2 + 22*x + 8], 0, x)
|
| 392 |
+
C0*(2*x - 3)/(2*(x**2 - 1))
|
| 393 |
+
|
| 394 |
+
References
|
| 395 |
+
==========
|
| 396 |
+
|
| 397 |
+
.. [1] S. A. Abramov, Rational solutions of linear difference
|
| 398 |
+
and q-difference equations with polynomial coefficients,
|
| 399 |
+
in: T. Levelt, ed., Proc. ISSAC '95, ACM Press, New York,
|
| 400 |
+
1995, 285-289
|
| 401 |
+
|
| 402 |
+
See Also
|
| 403 |
+
========
|
| 404 |
+
|
| 405 |
+
rsolve_hyper
|
| 406 |
+
"""
|
| 407 |
+
f = sympify(f)
|
| 408 |
+
|
| 409 |
+
if not f.is_polynomial(n):
|
| 410 |
+
return None
|
| 411 |
+
|
| 412 |
+
coeffs = list(map(sympify, coeffs))
|
| 413 |
+
|
| 414 |
+
r = len(coeffs) - 1
|
| 415 |
+
|
| 416 |
+
A, B = coeffs[r], coeffs[0]
|
| 417 |
+
A = A.subs(n, n - r).expand()
|
| 418 |
+
|
| 419 |
+
h = Dummy('h')
|
| 420 |
+
|
| 421 |
+
res = resultant(A, B.subs(n, n + h), n)
|
| 422 |
+
|
| 423 |
+
if not res.is_polynomial(h):
|
| 424 |
+
p, q = res.as_numer_denom()
|
| 425 |
+
res = quo(p, q, h)
|
| 426 |
+
|
| 427 |
+
nni_roots = list(roots(res, h, filter='Z',
|
| 428 |
+
predicate=lambda r: r >= 0).keys())
|
| 429 |
+
|
| 430 |
+
if not nni_roots:
|
| 431 |
+
return rsolve_poly(coeffs, f, n, **hints)
|
| 432 |
+
else:
|
| 433 |
+
C, numers = S.One, [S.Zero]*(r + 1)
|
| 434 |
+
|
| 435 |
+
for i in range(int(max(nni_roots)), -1, -1):
|
| 436 |
+
d = gcd(A, B.subs(n, n + i), n)
|
| 437 |
+
|
| 438 |
+
A = quo(A, d, n)
|
| 439 |
+
B = quo(B, d.subs(n, n - i), n)
|
| 440 |
+
|
| 441 |
+
C *= Mul(*[d.subs(n, n - j) for j in range(i + 1)])
|
| 442 |
+
|
| 443 |
+
denoms = [C.subs(n, n + i) for i in range(r + 1)]
|
| 444 |
+
|
| 445 |
+
for i in range(r + 1):
|
| 446 |
+
g = gcd(coeffs[i], denoms[i], n)
|
| 447 |
+
|
| 448 |
+
numers[i] = quo(coeffs[i], g, n)
|
| 449 |
+
denoms[i] = quo(denoms[i], g, n)
|
| 450 |
+
|
| 451 |
+
for i in range(r + 1):
|
| 452 |
+
numers[i] *= Mul(*(denoms[:i] + denoms[i + 1:]))
|
| 453 |
+
|
| 454 |
+
result = rsolve_poly(numers, f * Mul(*denoms), n, **hints)
|
| 455 |
+
|
| 456 |
+
if result is not None:
|
| 457 |
+
if hints.get('symbols', False):
|
| 458 |
+
return (simplify(result[0] / C), result[1])
|
| 459 |
+
else:
|
| 460 |
+
return simplify(result / C)
|
| 461 |
+
else:
|
| 462 |
+
return None
|
| 463 |
+
|
| 464 |
+
|
| 465 |
+
def rsolve_hyper(coeffs, f, n, **hints):
|
| 466 |
+
r"""
|
| 467 |
+
Given linear recurrence operator `\operatorname{L}` of order `k`
|
| 468 |
+
with polynomial coefficients and inhomogeneous equation
|
| 469 |
+
`\operatorname{L} y = f` we seek for all hypergeometric solutions
|
| 470 |
+
over field `K` of characteristic zero.
|
| 471 |
+
|
| 472 |
+
The inhomogeneous part can be either hypergeometric or a sum
|
| 473 |
+
of a fixed number of pairwise dissimilar hypergeometric terms.
|
| 474 |
+
|
| 475 |
+
The algorithm performs three basic steps:
|
| 476 |
+
|
| 477 |
+
(1) Group together similar hypergeometric terms in the
|
| 478 |
+
inhomogeneous part of `\operatorname{L} y = f`, and find
|
| 479 |
+
particular solution using Abramov's algorithm.
|
| 480 |
+
|
| 481 |
+
(2) Compute generating set of `\operatorname{L}` and find basis
|
| 482 |
+
in it, so that all solutions are linearly independent.
|
| 483 |
+
|
| 484 |
+
(3) Form final solution with the number of arbitrary
|
| 485 |
+
constants equal to dimension of basis of `\operatorname{L}`.
|
| 486 |
+
|
| 487 |
+
Term `a(n)` is hypergeometric if it is annihilated by first order
|
| 488 |
+
linear difference equations with polynomial coefficients or, in
|
| 489 |
+
simpler words, if consecutive term ratio is a rational function.
|
| 490 |
+
|
| 491 |
+
The output of this procedure is a linear combination of fixed
|
| 492 |
+
number of hypergeometric terms. However the underlying method
|
| 493 |
+
can generate larger class of solutions - D'Alembertian terms.
|
| 494 |
+
|
| 495 |
+
Note also that this method not only computes the kernel of the
|
| 496 |
+
inhomogeneous equation, but also reduces in to a basis so that
|
| 497 |
+
solutions generated by this procedure are linearly independent
|
| 498 |
+
|
| 499 |
+
Examples
|
| 500 |
+
========
|
| 501 |
+
|
| 502 |
+
>>> from sympy.solvers import rsolve_hyper
|
| 503 |
+
>>> from sympy.abc import x
|
| 504 |
+
|
| 505 |
+
>>> rsolve_hyper([-1, -1, 1], 0, x)
|
| 506 |
+
C0*(1/2 - sqrt(5)/2)**x + C1*(1/2 + sqrt(5)/2)**x
|
| 507 |
+
|
| 508 |
+
>>> rsolve_hyper([-1, 1], 1 + x, x)
|
| 509 |
+
C0 + x*(x + 1)/2
|
| 510 |
+
|
| 511 |
+
References
|
| 512 |
+
==========
|
| 513 |
+
|
| 514 |
+
.. [1] M. Petkovsek, Hypergeometric solutions of linear recurrences
|
| 515 |
+
with polynomial coefficients, J. Symbolic Computation,
|
| 516 |
+
14 (1992), 243-264.
|
| 517 |
+
|
| 518 |
+
.. [2] M. Petkovsek, H. S. Wilf, D. Zeilberger, A = B, 1996.
|
| 519 |
+
"""
|
| 520 |
+
coeffs = list(map(sympify, coeffs))
|
| 521 |
+
|
| 522 |
+
f = sympify(f)
|
| 523 |
+
|
| 524 |
+
r, kernel, symbols = len(coeffs) - 1, [], set()
|
| 525 |
+
|
| 526 |
+
if not f.is_zero:
|
| 527 |
+
if f.is_Add:
|
| 528 |
+
similar = {}
|
| 529 |
+
|
| 530 |
+
for g in f.expand().args:
|
| 531 |
+
if not g.is_hypergeometric(n):
|
| 532 |
+
return None
|
| 533 |
+
|
| 534 |
+
for h in similar.keys():
|
| 535 |
+
if hypersimilar(g, h, n):
|
| 536 |
+
similar[h] += g
|
| 537 |
+
break
|
| 538 |
+
else:
|
| 539 |
+
similar[g] = S.Zero
|
| 540 |
+
|
| 541 |
+
inhomogeneous = [g + h for g, h in similar.items()]
|
| 542 |
+
elif f.is_hypergeometric(n):
|
| 543 |
+
inhomogeneous = [f]
|
| 544 |
+
else:
|
| 545 |
+
return None
|
| 546 |
+
|
| 547 |
+
for i, g in enumerate(inhomogeneous):
|
| 548 |
+
coeff, polys = S.One, coeffs[:]
|
| 549 |
+
denoms = [S.One]*(r + 1)
|
| 550 |
+
|
| 551 |
+
s = hypersimp(g, n)
|
| 552 |
+
|
| 553 |
+
for j in range(1, r + 1):
|
| 554 |
+
coeff *= s.subs(n, n + j - 1)
|
| 555 |
+
|
| 556 |
+
p, q = coeff.as_numer_denom()
|
| 557 |
+
|
| 558 |
+
polys[j] *= p
|
| 559 |
+
denoms[j] = q
|
| 560 |
+
|
| 561 |
+
for j in range(r + 1):
|
| 562 |
+
polys[j] *= Mul(*(denoms[:j] + denoms[j + 1:]))
|
| 563 |
+
|
| 564 |
+
# FIXME: The call to rsolve_ratio below should suffice (rsolve_poly
|
| 565 |
+
# call can be removed) but the XFAIL test_rsolve_ratio_missed must
|
| 566 |
+
# be fixed first.
|
| 567 |
+
R = rsolve_ratio(polys, Mul(*denoms), n, symbols=True)
|
| 568 |
+
if R is not None:
|
| 569 |
+
R, syms = R
|
| 570 |
+
if syms:
|
| 571 |
+
R = R.subs(zip(syms, [0]*len(syms)))
|
| 572 |
+
else:
|
| 573 |
+
R = rsolve_poly(polys, Mul(*denoms), n)
|
| 574 |
+
|
| 575 |
+
if R:
|
| 576 |
+
inhomogeneous[i] *= R
|
| 577 |
+
else:
|
| 578 |
+
return None
|
| 579 |
+
|
| 580 |
+
result = Add(*inhomogeneous)
|
| 581 |
+
result = simplify(result)
|
| 582 |
+
else:
|
| 583 |
+
result = S.Zero
|
| 584 |
+
|
| 585 |
+
Z = Dummy('Z')
|
| 586 |
+
|
| 587 |
+
p, q = coeffs[0], coeffs[r].subs(n, n - r + 1)
|
| 588 |
+
|
| 589 |
+
p_factors = list(roots(p, n).keys())
|
| 590 |
+
q_factors = list(roots(q, n).keys())
|
| 591 |
+
|
| 592 |
+
factors = [(S.One, S.One)]
|
| 593 |
+
|
| 594 |
+
for p in p_factors:
|
| 595 |
+
for q in q_factors:
|
| 596 |
+
if p.is_integer and q.is_integer and p <= q:
|
| 597 |
+
continue
|
| 598 |
+
else:
|
| 599 |
+
factors += [(n - p, n - q)]
|
| 600 |
+
|
| 601 |
+
p = [(n - p, S.One) for p in p_factors]
|
| 602 |
+
q = [(S.One, n - q) for q in q_factors]
|
| 603 |
+
|
| 604 |
+
factors = p + factors + q
|
| 605 |
+
|
| 606 |
+
for A, B in factors:
|
| 607 |
+
polys, degrees = [], []
|
| 608 |
+
D = A*B.subs(n, n + r - 1)
|
| 609 |
+
|
| 610 |
+
for i in range(r + 1):
|
| 611 |
+
a = Mul(*[A.subs(n, n + j) for j in range(i)])
|
| 612 |
+
b = Mul(*[B.subs(n, n + j) for j in range(i, r)])
|
| 613 |
+
|
| 614 |
+
poly = quo(coeffs[i]*a*b, D, n)
|
| 615 |
+
polys.append(poly.as_poly(n))
|
| 616 |
+
|
| 617 |
+
if not poly.is_zero:
|
| 618 |
+
degrees.append(polys[i].degree())
|
| 619 |
+
|
| 620 |
+
if degrees:
|
| 621 |
+
d, poly = max(degrees), S.Zero
|
| 622 |
+
else:
|
| 623 |
+
return None
|
| 624 |
+
|
| 625 |
+
for i in range(r + 1):
|
| 626 |
+
coeff = polys[i].nth(d)
|
| 627 |
+
|
| 628 |
+
if coeff is not S.Zero:
|
| 629 |
+
poly += coeff * Z**i
|
| 630 |
+
|
| 631 |
+
for z in roots(poly, Z).keys():
|
| 632 |
+
if z.is_zero:
|
| 633 |
+
continue
|
| 634 |
+
|
| 635 |
+
recurr_coeffs = [polys[i].as_expr()*z**i for i in range(r + 1)]
|
| 636 |
+
if d == 0 and 0 != Add(*[recurr_coeffs[j]*j for j in range(1, r + 1)]):
|
| 637 |
+
# faster inline check (than calling rsolve_poly) for a
|
| 638 |
+
# constant solution to a constant coefficient recurrence.
|
| 639 |
+
sol = [Symbol("C" + str(len(symbols)))]
|
| 640 |
+
else:
|
| 641 |
+
sol, syms = rsolve_poly(recurr_coeffs, 0, n, len(symbols), symbols=True)
|
| 642 |
+
sol = sol.collect(syms)
|
| 643 |
+
sol = [sol.coeff(s) for s in syms]
|
| 644 |
+
|
| 645 |
+
for C in sol:
|
| 646 |
+
ratio = z * A * C.subs(n, n + 1) / B / C
|
| 647 |
+
ratio = simplify(ratio)
|
| 648 |
+
# If there is a nonnegative root in the denominator of the ratio,
|
| 649 |
+
# this indicates that the term y(n_root) is zero, and one should
|
| 650 |
+
# start the product with the term y(n_root + 1).
|
| 651 |
+
n0 = 0
|
| 652 |
+
for n_root in roots(ratio.as_numer_denom()[1], n).keys():
|
| 653 |
+
if n_root.has(I):
|
| 654 |
+
return None
|
| 655 |
+
elif (n0 < (n_root + 1)) == True:
|
| 656 |
+
n0 = n_root + 1
|
| 657 |
+
K = product(ratio, (n, n0, n - 1))
|
| 658 |
+
if K.has(factorial, FallingFactorial, RisingFactorial):
|
| 659 |
+
K = simplify(K)
|
| 660 |
+
|
| 661 |
+
if casoratian(kernel + [K], n, zero=False) != 0:
|
| 662 |
+
kernel.append(K)
|
| 663 |
+
|
| 664 |
+
kernel.sort(key=default_sort_key)
|
| 665 |
+
sk = list(zip(numbered_symbols('C'), kernel))
|
| 666 |
+
|
| 667 |
+
for C, ker in sk:
|
| 668 |
+
result += C * ker
|
| 669 |
+
|
| 670 |
+
if hints.get('symbols', False):
|
| 671 |
+
# XXX: This returns the symbols in a non-deterministic order
|
| 672 |
+
symbols |= {s for s, k in sk}
|
| 673 |
+
return (result, list(symbols))
|
| 674 |
+
else:
|
| 675 |
+
return result
|
| 676 |
+
|
| 677 |
+
|
| 678 |
+
def rsolve(f, y, init=None):
|
| 679 |
+
r"""
|
| 680 |
+
Solve univariate recurrence with rational coefficients.
|
| 681 |
+
|
| 682 |
+
Given `k`-th order linear recurrence `\operatorname{L} y = f`,
|
| 683 |
+
or equivalently:
|
| 684 |
+
|
| 685 |
+
.. math:: a_{k}(n) y(n+k) + a_{k-1}(n) y(n+k-1) +
|
| 686 |
+
\cdots + a_{0}(n) y(n) = f(n)
|
| 687 |
+
|
| 688 |
+
where `a_{i}(n)`, for `i=0, \ldots, k`, are polynomials or rational
|
| 689 |
+
functions in `n`, and `f` is a hypergeometric function or a sum
|
| 690 |
+
of a fixed number of pairwise dissimilar hypergeometric terms in
|
| 691 |
+
`n`, finds all solutions or returns ``None``, if none were found.
|
| 692 |
+
|
| 693 |
+
Initial conditions can be given as a dictionary in two forms:
|
| 694 |
+
|
| 695 |
+
(1) ``{ n_0 : v_0, n_1 : v_1, ..., n_m : v_m}``
|
| 696 |
+
(2) ``{y(n_0) : v_0, y(n_1) : v_1, ..., y(n_m) : v_m}``
|
| 697 |
+
|
| 698 |
+
or as a list ``L`` of values:
|
| 699 |
+
|
| 700 |
+
``L = [v_0, v_1, ..., v_m]``
|
| 701 |
+
|
| 702 |
+
where ``L[i] = v_i``, for `i=0, \ldots, m`, maps to `y(n_i)`.
|
| 703 |
+
|
| 704 |
+
Examples
|
| 705 |
+
========
|
| 706 |
+
|
| 707 |
+
Lets consider the following recurrence:
|
| 708 |
+
|
| 709 |
+
.. math:: (n - 1) y(n + 2) - (n^2 + 3 n - 2) y(n + 1) +
|
| 710 |
+
2 n (n + 1) y(n) = 0
|
| 711 |
+
|
| 712 |
+
>>> from sympy import Function, rsolve
|
| 713 |
+
>>> from sympy.abc import n
|
| 714 |
+
>>> y = Function('y')
|
| 715 |
+
|
| 716 |
+
>>> f = (n - 1)*y(n + 2) - (n**2 + 3*n - 2)*y(n + 1) + 2*n*(n + 1)*y(n)
|
| 717 |
+
|
| 718 |
+
>>> rsolve(f, y(n))
|
| 719 |
+
2**n*C0 + C1*factorial(n)
|
| 720 |
+
|
| 721 |
+
>>> rsolve(f, y(n), {y(0):0, y(1):3})
|
| 722 |
+
3*2**n - 3*factorial(n)
|
| 723 |
+
|
| 724 |
+
See Also
|
| 725 |
+
========
|
| 726 |
+
|
| 727 |
+
rsolve_poly, rsolve_ratio, rsolve_hyper
|
| 728 |
+
|
| 729 |
+
"""
|
| 730 |
+
if isinstance(f, Equality):
|
| 731 |
+
f = f.lhs - f.rhs
|
| 732 |
+
|
| 733 |
+
n = y.args[0]
|
| 734 |
+
k = Wild('k', exclude=(n,))
|
| 735 |
+
|
| 736 |
+
# Preprocess user input to allow things like
|
| 737 |
+
# y(n) + a*(y(n + 1) + y(n - 1))/2
|
| 738 |
+
f = f.expand().collect(y.func(Wild('m', integer=True)))
|
| 739 |
+
|
| 740 |
+
h_part = defaultdict(list)
|
| 741 |
+
i_part = []
|
| 742 |
+
for g in Add.make_args(f):
|
| 743 |
+
coeff, dep = g.as_coeff_mul(y.func)
|
| 744 |
+
if not dep:
|
| 745 |
+
i_part.append(coeff)
|
| 746 |
+
continue
|
| 747 |
+
for h in dep:
|
| 748 |
+
if h.is_Function and h.func == y.func:
|
| 749 |
+
result = h.args[0].match(n + k)
|
| 750 |
+
if result is not None:
|
| 751 |
+
h_part[int(result[k])].append(coeff)
|
| 752 |
+
continue
|
| 753 |
+
raise ValueError(
|
| 754 |
+
"'%s(%s + k)' expected, got '%s'" % (y.func, n, h))
|
| 755 |
+
for k in h_part:
|
| 756 |
+
h_part[k] = Add(*h_part[k])
|
| 757 |
+
h_part.default_factory = lambda: 0
|
| 758 |
+
i_part = Add(*i_part)
|
| 759 |
+
|
| 760 |
+
for k, coeff in h_part.items():
|
| 761 |
+
h_part[k] = simplify(coeff)
|
| 762 |
+
|
| 763 |
+
common = S.One
|
| 764 |
+
|
| 765 |
+
if not i_part.is_zero and not i_part.is_hypergeometric(n) and \
|
| 766 |
+
not (i_part.is_Add and all((x.is_hypergeometric(n) for x in i_part.expand().args))):
|
| 767 |
+
raise ValueError("The independent term should be a sum of hypergeometric functions, got '%s'" % i_part)
|
| 768 |
+
|
| 769 |
+
for coeff in h_part.values():
|
| 770 |
+
if coeff.is_rational_function(n):
|
| 771 |
+
if not coeff.is_polynomial(n):
|
| 772 |
+
common = lcm(common, coeff.as_numer_denom()[1], n)
|
| 773 |
+
else:
|
| 774 |
+
raise ValueError(
|
| 775 |
+
"Polynomial or rational function expected, got '%s'" % coeff)
|
| 776 |
+
|
| 777 |
+
i_numer, i_denom = i_part.as_numer_denom()
|
| 778 |
+
|
| 779 |
+
if i_denom.is_polynomial(n):
|
| 780 |
+
common = lcm(common, i_denom, n)
|
| 781 |
+
|
| 782 |
+
if common is not S.One:
|
| 783 |
+
for k, coeff in h_part.items():
|
| 784 |
+
numer, denom = coeff.as_numer_denom()
|
| 785 |
+
h_part[k] = numer*quo(common, denom, n)
|
| 786 |
+
|
| 787 |
+
i_part = i_numer*quo(common, i_denom, n)
|
| 788 |
+
|
| 789 |
+
K_min = min(h_part.keys())
|
| 790 |
+
|
| 791 |
+
if K_min < 0:
|
| 792 |
+
K = abs(K_min)
|
| 793 |
+
|
| 794 |
+
H_part = defaultdict(lambda: S.Zero)
|
| 795 |
+
i_part = i_part.subs(n, n + K).expand()
|
| 796 |
+
common = common.subs(n, n + K).expand()
|
| 797 |
+
|
| 798 |
+
for k, coeff in h_part.items():
|
| 799 |
+
H_part[k + K] = coeff.subs(n, n + K).expand()
|
| 800 |
+
else:
|
| 801 |
+
H_part = h_part
|
| 802 |
+
|
| 803 |
+
K_max = max(H_part.keys())
|
| 804 |
+
coeffs = [H_part[i] for i in range(K_max + 1)]
|
| 805 |
+
|
| 806 |
+
result = rsolve_hyper(coeffs, -i_part, n, symbols=True)
|
| 807 |
+
|
| 808 |
+
if result is None:
|
| 809 |
+
return None
|
| 810 |
+
|
| 811 |
+
solution, symbols = result
|
| 812 |
+
|
| 813 |
+
if init in ({}, []):
|
| 814 |
+
init = None
|
| 815 |
+
|
| 816 |
+
if symbols and init is not None:
|
| 817 |
+
if isinstance(init, list):
|
| 818 |
+
init = {i: init[i] for i in range(len(init))}
|
| 819 |
+
|
| 820 |
+
equations = []
|
| 821 |
+
|
| 822 |
+
for k, v in init.items():
|
| 823 |
+
try:
|
| 824 |
+
i = int(k)
|
| 825 |
+
except TypeError:
|
| 826 |
+
if k.is_Function and k.func == y.func:
|
| 827 |
+
i = int(k.args[0])
|
| 828 |
+
else:
|
| 829 |
+
raise ValueError("Integer or term expected, got '%s'" % k)
|
| 830 |
+
|
| 831 |
+
eq = solution.subs(n, i) - v
|
| 832 |
+
if eq.has(S.NaN):
|
| 833 |
+
eq = solution.limit(n, i) - v
|
| 834 |
+
equations.append(eq)
|
| 835 |
+
|
| 836 |
+
result = solve(equations, *symbols)
|
| 837 |
+
|
| 838 |
+
if not result:
|
| 839 |
+
return None
|
| 840 |
+
else:
|
| 841 |
+
solution = solution.subs(result)
|
| 842 |
+
|
| 843 |
+
return solution
|
evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/simplex.py
ADDED
|
@@ -0,0 +1,1141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tools for optimizing a linear function for a given simplex.
|
| 2 |
+
|
| 3 |
+
For the linear objective function ``f`` with linear constraints
|
| 4 |
+
expressed using `Le`, `Ge` or `Eq` can be found with ``lpmin`` or
|
| 5 |
+
``lpmax``. The symbols are **unbounded** unless specifically
|
| 6 |
+
constrained.
|
| 7 |
+
|
| 8 |
+
As an alternative, the matrices describing the objective and the
|
| 9 |
+
constraints, and an optional list of bounds can be passed to
|
| 10 |
+
``linprog`` which will solve for the minimization of ``C*x``
|
| 11 |
+
under constraints ``A*x <= b`` and/or ``Aeq*x = beq``, and
|
| 12 |
+
individual bounds for variables given as ``(lo, hi)``. The values
|
| 13 |
+
returned are **nonnegative** unless bounds are provided that
|
| 14 |
+
indicate otherwise.
|
| 15 |
+
|
| 16 |
+
Errors that might be raised are UnboundedLPError when there is no
|
| 17 |
+
finite solution for the system or InfeasibleLPError when the
|
| 18 |
+
constraints represent impossible conditions (i.e. a non-existant
|
| 19 |
+
simplex).
|
| 20 |
+
|
| 21 |
+
Here is a simple 1-D system: minimize `x` given that ``x >= 1``.
|
| 22 |
+
|
| 23 |
+
>>> from sympy.solvers.simplex import lpmin, linprog
|
| 24 |
+
>>> from sympy.abc import x
|
| 25 |
+
|
| 26 |
+
The function and a list with the constraint is passed directly
|
| 27 |
+
to `lpmin`:
|
| 28 |
+
|
| 29 |
+
>>> lpmin(x, [x >= 1])
|
| 30 |
+
(1, {x: 1})
|
| 31 |
+
|
| 32 |
+
For `linprog` the matrix for the objective is `[1]` and the
|
| 33 |
+
uivariate constraint can be passed as a bound with None acting
|
| 34 |
+
as infinity:
|
| 35 |
+
|
| 36 |
+
>>> linprog([1], bounds=(1, None))
|
| 37 |
+
(1, [1])
|
| 38 |
+
|
| 39 |
+
Or the matrices, corresponding to ``x >= 1`` expressed as
|
| 40 |
+
``-x <= -1`` as required by the routine, can be passed:
|
| 41 |
+
|
| 42 |
+
>>> linprog([1], [-1], [-1])
|
| 43 |
+
(1, [1])
|
| 44 |
+
|
| 45 |
+
If there is no limit for the objective, an error is raised.
|
| 46 |
+
In this case there is a valid region of interest (simplex)
|
| 47 |
+
but no limit to how small ``x`` can be:
|
| 48 |
+
|
| 49 |
+
>>> lpmin(x, [])
|
| 50 |
+
Traceback (most recent call last):
|
| 51 |
+
...
|
| 52 |
+
sympy.solvers.simplex.UnboundedLPError:
|
| 53 |
+
Objective function can assume arbitrarily large values!
|
| 54 |
+
|
| 55 |
+
An error is raised if there is no possible solution:
|
| 56 |
+
|
| 57 |
+
>>> lpmin(x,[x<=1,x>=2])
|
| 58 |
+
Traceback (most recent call last):
|
| 59 |
+
...
|
| 60 |
+
sympy.solvers.simplex.InfeasibleLPError:
|
| 61 |
+
Inconsistent/False constraint
|
| 62 |
+
"""
|
| 63 |
+
|
| 64 |
+
from sympy.core import sympify
|
| 65 |
+
from sympy.core.exprtools import factor_terms
|
| 66 |
+
from sympy.core.relational import Le, Ge, Eq
|
| 67 |
+
from sympy.core.singleton import S
|
| 68 |
+
from sympy.core.symbol import Dummy
|
| 69 |
+
from sympy.core.sorting import ordered
|
| 70 |
+
from sympy.functions.elementary.complexes import sign
|
| 71 |
+
from sympy.matrices.dense import Matrix, zeros
|
| 72 |
+
from sympy.solvers.solveset import linear_eq_to_matrix
|
| 73 |
+
from sympy.utilities.iterables import numbered_symbols
|
| 74 |
+
from sympy.utilities.misc import filldedent
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class UnboundedLPError(Exception):
|
| 78 |
+
"""
|
| 79 |
+
A linear programing problem is said to be unbounded if its objective
|
| 80 |
+
function can assume arbitrarily large values.
|
| 81 |
+
|
| 82 |
+
Example
|
| 83 |
+
=======
|
| 84 |
+
|
| 85 |
+
Suppose you want to maximize
|
| 86 |
+
2x
|
| 87 |
+
subject to
|
| 88 |
+
x >= 0
|
| 89 |
+
|
| 90 |
+
There's no upper limit that 2x can take.
|
| 91 |
+
"""
|
| 92 |
+
|
| 93 |
+
pass
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
class InfeasibleLPError(Exception):
|
| 97 |
+
"""
|
| 98 |
+
A linear programing problem is considered infeasible if its
|
| 99 |
+
constraint set is empty. That is, if the set of all vectors
|
| 100 |
+
satisfying the contraints is empty, then the problem is infeasible.
|
| 101 |
+
|
| 102 |
+
Example
|
| 103 |
+
=======
|
| 104 |
+
|
| 105 |
+
Suppose you want to maximize
|
| 106 |
+
x
|
| 107 |
+
subject to
|
| 108 |
+
x >= 10
|
| 109 |
+
x <= 9
|
| 110 |
+
|
| 111 |
+
No x can satisfy those constraints.
|
| 112 |
+
"""
|
| 113 |
+
|
| 114 |
+
pass
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def _pivot(M, i, j):
|
| 118 |
+
"""
|
| 119 |
+
The pivot element `M[i, j]` is inverted and the rest of the matrix
|
| 120 |
+
modified and returned as a new matrix; original is left unmodified.
|
| 121 |
+
|
| 122 |
+
Example
|
| 123 |
+
=======
|
| 124 |
+
|
| 125 |
+
>>> from sympy.matrices.dense import Matrix
|
| 126 |
+
>>> from sympy.solvers.simplex import _pivot
|
| 127 |
+
>>> from sympy import var
|
| 128 |
+
>>> Matrix(3, 3, var('a:i'))
|
| 129 |
+
Matrix([
|
| 130 |
+
[a, b, c],
|
| 131 |
+
[d, e, f],
|
| 132 |
+
[g, h, i]])
|
| 133 |
+
>>> _pivot(_, 1, 0)
|
| 134 |
+
Matrix([
|
| 135 |
+
[-a/d, -a*e/d + b, -a*f/d + c],
|
| 136 |
+
[ 1/d, e/d, f/d],
|
| 137 |
+
[-g/d, h - e*g/d, i - f*g/d]])
|
| 138 |
+
"""
|
| 139 |
+
Mi, Mj, Mij = M[i, :], M[:, j], M[i, j]
|
| 140 |
+
if Mij == 0:
|
| 141 |
+
raise ZeroDivisionError(
|
| 142 |
+
"Tried to pivot about zero-valued entry.")
|
| 143 |
+
A = M - Mj * (Mi / Mij)
|
| 144 |
+
A[i, :] = Mi / Mij
|
| 145 |
+
A[:, j] = -Mj / Mij
|
| 146 |
+
A[i, j] = 1 / Mij
|
| 147 |
+
return A
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def _choose_pivot_row(A, B, candidate_rows, pivot_col, Y):
|
| 151 |
+
# Choose row with smallest ratio
|
| 152 |
+
# If there are ties, pick using Bland's rule
|
| 153 |
+
return min(candidate_rows, key=lambda i: (B[i] / A[i, pivot_col], Y[i]))
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def _simplex(A, B, C, D=None, dual=False):
|
| 157 |
+
"""Return ``(o, x, y)`` obtained from the two-phase simplex method
|
| 158 |
+
using Bland's rule: ``o`` is the minimum value of primal,
|
| 159 |
+
``Cx - D``, under constraints ``Ax <= B`` (with ``x >= 0``) and
|
| 160 |
+
the maximum of the dual, ``y^{T}B - D``, under constraints
|
| 161 |
+
``A^{T}*y >= C^{T}`` (with ``y >= 0``). To compute the dual of
|
| 162 |
+
the system, pass `dual=True` and ``(o, y, x)`` will be returned.
|
| 163 |
+
|
| 164 |
+
Note: the nonnegative constraints for ``x`` and ``y`` supercede
|
| 165 |
+
any values of ``A`` and ``B`` that are inconsistent with that
|
| 166 |
+
assumption, so if a constraint of ``x >= -1`` is represented
|
| 167 |
+
in ``A`` and ``B``, no value will be obtained that is negative; if
|
| 168 |
+
a constraint of ``x <= -1`` is represented, an error will be
|
| 169 |
+
raised since no solution is possible.
|
| 170 |
+
|
| 171 |
+
This routine relies on the ability of determining whether an
|
| 172 |
+
expression is 0 or not. This is guaranteed if the input contains
|
| 173 |
+
only Float or Rational entries. It will raise a TypeError if
|
| 174 |
+
a relationship does not evaluate to True or False.
|
| 175 |
+
|
| 176 |
+
Examples
|
| 177 |
+
========
|
| 178 |
+
|
| 179 |
+
>>> from sympy.solvers.simplex import _simplex
|
| 180 |
+
>>> from sympy import Matrix
|
| 181 |
+
|
| 182 |
+
Consider the simple minimization of ``f = x + y + 1`` under the
|
| 183 |
+
constraint that ``y + 2*x >= 4``. This is the "standard form" of
|
| 184 |
+
a minimization.
|
| 185 |
+
|
| 186 |
+
In the nonnegative quadrant, this inequality describes a area above
|
| 187 |
+
a triangle with vertices at (0, 4), (0, 0) and (2, 0). The minimum
|
| 188 |
+
of ``f`` occurs at (2, 0). Define A, B, C, D for the standard
|
| 189 |
+
minimization:
|
| 190 |
+
|
| 191 |
+
>>> A = Matrix([[2, 1]])
|
| 192 |
+
>>> B = Matrix([4])
|
| 193 |
+
>>> C = Matrix([[1, 1]])
|
| 194 |
+
>>> D = Matrix([-1])
|
| 195 |
+
|
| 196 |
+
Confirm that this is the system of interest:
|
| 197 |
+
|
| 198 |
+
>>> from sympy.abc import x, y
|
| 199 |
+
>>> X = Matrix([x, y])
|
| 200 |
+
>>> (C*X - D)[0]
|
| 201 |
+
x + y + 1
|
| 202 |
+
>>> [i >= j for i, j in zip(A*X, B)]
|
| 203 |
+
[2*x + y >= 4]
|
| 204 |
+
|
| 205 |
+
Since `_simplex` will do a minimization for constraints given as
|
| 206 |
+
``A*x <= B``, the signs of ``A`` and ``B`` must be negated since
|
| 207 |
+
the currently correspond to a greater-than inequality:
|
| 208 |
+
|
| 209 |
+
>>> _simplex(-A, -B, C, D)
|
| 210 |
+
(3, [2, 0], [1/2])
|
| 211 |
+
|
| 212 |
+
The dual of minimizing ``f`` is maximizing ``F = c*y - d`` for
|
| 213 |
+
``a*y <= b`` where ``a``, ``b``, ``c``, ``d`` are derived from the
|
| 214 |
+
transpose of the matrix representation of the standard minimization:
|
| 215 |
+
|
| 216 |
+
>>> tr = lambda a, b, c, d: [i.T for i in (a, c, b, d)]
|
| 217 |
+
>>> a, b, c, d = tr(A, B, C, D)
|
| 218 |
+
|
| 219 |
+
This time ``a*x <= b`` is the expected inequality for the `_simplex`
|
| 220 |
+
method, but to maximize ``F``, the sign of ``c`` and ``d`` must be
|
| 221 |
+
changed (so that minimizing the negative will give the negative of
|
| 222 |
+
the maximum of ``F``):
|
| 223 |
+
|
| 224 |
+
>>> _simplex(a, b, -c, -d)
|
| 225 |
+
(-3, [1/2], [2, 0])
|
| 226 |
+
|
| 227 |
+
The negative of ``F`` and the min of ``f`` are the same. The dual
|
| 228 |
+
point `[1/2]` is the value of ``y`` that minimized ``F = c*y - d``
|
| 229 |
+
under constraints a*x <= b``:
|
| 230 |
+
|
| 231 |
+
>>> y = Matrix(['y'])
|
| 232 |
+
>>> (c*y - d)[0]
|
| 233 |
+
4*y + 1
|
| 234 |
+
>>> [i <= j for i, j in zip(a*y,b)]
|
| 235 |
+
[2*y <= 1, y <= 1]
|
| 236 |
+
|
| 237 |
+
In this 1-dimensional dual system, the more restrictive contraint is
|
| 238 |
+
the first which limits ``y`` between 0 and 1/2 and the maximum of
|
| 239 |
+
``F`` is attained at the nonzero value, hence is ``4*(1/2) + 1 = 3``.
|
| 240 |
+
|
| 241 |
+
In this case the values for ``x`` and ``y`` were the same when the
|
| 242 |
+
dual representation was solved. This is not always the case (though
|
| 243 |
+
the value of the function will be the same).
|
| 244 |
+
|
| 245 |
+
>>> l = [[1, 1], [-1, 1], [0, 1], [-1, 0]], [5, 1, 2, -1], [[1, 1]], [-1]
|
| 246 |
+
>>> A, B, C, D = [Matrix(i) for i in l]
|
| 247 |
+
>>> _simplex(A, B, -C, -D)
|
| 248 |
+
(-6, [3, 2], [1, 0, 0, 0])
|
| 249 |
+
>>> _simplex(A, B, -C, -D, dual=True) # [5, 0] != [3, 2]
|
| 250 |
+
(-6, [1, 0, 0, 0], [5, 0])
|
| 251 |
+
|
| 252 |
+
In both cases the function has the same value:
|
| 253 |
+
|
| 254 |
+
>>> Matrix(C)*Matrix([3, 2]) == Matrix(C)*Matrix([5, 0])
|
| 255 |
+
True
|
| 256 |
+
|
| 257 |
+
See Also
|
| 258 |
+
========
|
| 259 |
+
_lp - poses min/max problem in form compatible with _simplex
|
| 260 |
+
lpmin - minimization which calls _lp
|
| 261 |
+
lpmax - maximimzation which calls _lp
|
| 262 |
+
|
| 263 |
+
References
|
| 264 |
+
==========
|
| 265 |
+
|
| 266 |
+
.. [1] Thomas S. Ferguson, LINEAR PROGRAMMING: A Concise Introduction
|
| 267 |
+
web.tecnico.ulisboa.pt/mcasquilho/acad/or/ftp/FergusonUCLA_lp.pdf
|
| 268 |
+
|
| 269 |
+
"""
|
| 270 |
+
A, B, C, D = [Matrix(i) for i in (A, B, C, D or [0])]
|
| 271 |
+
if dual:
|
| 272 |
+
_o, d, p = _simplex(-A.T, C.T, B.T, -D)
|
| 273 |
+
return -_o, d, p
|
| 274 |
+
|
| 275 |
+
if A and B:
|
| 276 |
+
M = Matrix([[A, B], [C, D]])
|
| 277 |
+
else:
|
| 278 |
+
if A or B:
|
| 279 |
+
raise ValueError("must give A and B")
|
| 280 |
+
# no constraints given
|
| 281 |
+
M = Matrix([[C, D]])
|
| 282 |
+
n = M.cols - 1
|
| 283 |
+
m = M.rows - 1
|
| 284 |
+
|
| 285 |
+
if not all(i.is_Float or i.is_Rational for i in M):
|
| 286 |
+
# with literal Float and Rational we are guaranteed the
|
| 287 |
+
# ability of determining whether an expression is 0 or not
|
| 288 |
+
raise TypeError(filldedent("""
|
| 289 |
+
Only rationals and floats are allowed.
|
| 290 |
+
"""
|
| 291 |
+
)
|
| 292 |
+
)
|
| 293 |
+
|
| 294 |
+
# x variables have priority over y variables during Bland's rule
|
| 295 |
+
# since False < True
|
| 296 |
+
X = [(False, j) for j in range(n)]
|
| 297 |
+
Y = [(True, i) for i in range(m)]
|
| 298 |
+
|
| 299 |
+
# Phase 1: find a feasible solution or determine none exist
|
| 300 |
+
|
| 301 |
+
## keep track of last pivot row and column
|
| 302 |
+
last = None
|
| 303 |
+
|
| 304 |
+
while True:
|
| 305 |
+
B = M[:-1, -1]
|
| 306 |
+
A = M[:-1, :-1]
|
| 307 |
+
if all(B[i] >= 0 for i in range(B.rows)):
|
| 308 |
+
# We have found a feasible solution
|
| 309 |
+
break
|
| 310 |
+
|
| 311 |
+
# Find k: first row with a negative rightmost entry
|
| 312 |
+
for k in range(B.rows):
|
| 313 |
+
if B[k] < 0:
|
| 314 |
+
break # use current value of k below
|
| 315 |
+
else:
|
| 316 |
+
pass # error will raise below
|
| 317 |
+
|
| 318 |
+
# Choose pivot column, c
|
| 319 |
+
piv_cols = [_ for _ in range(A.cols) if A[k, _] < 0]
|
| 320 |
+
if not piv_cols:
|
| 321 |
+
raise InfeasibleLPError(filldedent("""
|
| 322 |
+
The constraint set is empty!"""))
|
| 323 |
+
_, c = min((X[i], i) for i in piv_cols) # Bland's rule
|
| 324 |
+
|
| 325 |
+
# Choose pivot row, r
|
| 326 |
+
piv_rows = [_ for _ in range(A.rows) if A[_, c] > 0 and B[_] > 0]
|
| 327 |
+
piv_rows.append(k)
|
| 328 |
+
r = _choose_pivot_row(A, B, piv_rows, c, Y)
|
| 329 |
+
|
| 330 |
+
# check for oscillation
|
| 331 |
+
if (r, c) == last:
|
| 332 |
+
# Not sure what to do here; it looks like there will be
|
| 333 |
+
# oscillations; see o1 test added at this commit to
|
| 334 |
+
# see a system with no solution and the o2 for one
|
| 335 |
+
# with a solution. In the case of o2, the solution
|
| 336 |
+
# from linprog is the same as the one from lpmin, but
|
| 337 |
+
# the matrices created in the lpmin case are different
|
| 338 |
+
# than those created without replacements in linprog and
|
| 339 |
+
# the matrices in the linprog case lead to oscillations.
|
| 340 |
+
# If the matrices could be re-written in linprog like
|
| 341 |
+
# lpmin does, this behavior could be avoided and then
|
| 342 |
+
# perhaps the oscillating case would only occur when
|
| 343 |
+
# there is no solution. For now, the output is checked
|
| 344 |
+
# before exit if oscillations were detected and an
|
| 345 |
+
# error is raised there if the solution was invalid.
|
| 346 |
+
#
|
| 347 |
+
# cf section 6 of Ferguson for a non-cycling modification
|
| 348 |
+
last = True
|
| 349 |
+
break
|
| 350 |
+
last = r, c
|
| 351 |
+
|
| 352 |
+
M = _pivot(M, r, c)
|
| 353 |
+
X[c], Y[r] = Y[r], X[c]
|
| 354 |
+
|
| 355 |
+
# Phase 2: from a feasible solution, pivot to optimal
|
| 356 |
+
while True:
|
| 357 |
+
B = M[:-1, -1]
|
| 358 |
+
A = M[:-1, :-1]
|
| 359 |
+
C = M[-1, :-1]
|
| 360 |
+
|
| 361 |
+
# Choose a pivot column, c
|
| 362 |
+
piv_cols = []
|
| 363 |
+
piv_cols = [_ for _ in range(n) if C[_] < 0]
|
| 364 |
+
if not piv_cols:
|
| 365 |
+
break
|
| 366 |
+
_, c = min((X[i], i) for i in piv_cols) # Bland's rule
|
| 367 |
+
|
| 368 |
+
# Choose a pivot row, r
|
| 369 |
+
piv_rows = [_ for _ in range(m) if A[_, c] > 0]
|
| 370 |
+
if not piv_rows:
|
| 371 |
+
raise UnboundedLPError(filldedent("""
|
| 372 |
+
Objective function can assume
|
| 373 |
+
arbitrarily large values!"""))
|
| 374 |
+
r = _choose_pivot_row(A, B, piv_rows, c, Y)
|
| 375 |
+
|
| 376 |
+
M = _pivot(M, r, c)
|
| 377 |
+
X[c], Y[r] = Y[r], X[c]
|
| 378 |
+
|
| 379 |
+
argmax = [None] * n
|
| 380 |
+
argmin_dual = [None] * m
|
| 381 |
+
|
| 382 |
+
for i, (v, n) in enumerate(X):
|
| 383 |
+
if v == False:
|
| 384 |
+
argmax[n] = 0
|
| 385 |
+
else:
|
| 386 |
+
argmin_dual[n] = M[-1, i]
|
| 387 |
+
|
| 388 |
+
for i, (v, n) in enumerate(Y):
|
| 389 |
+
if v == True:
|
| 390 |
+
argmin_dual[n] = 0
|
| 391 |
+
else:
|
| 392 |
+
argmax[n] = M[i, -1]
|
| 393 |
+
|
| 394 |
+
if last and not all(i >= 0 for i in argmax + argmin_dual):
|
| 395 |
+
raise InfeasibleLPError(filldedent("""
|
| 396 |
+
Oscillating system led to invalid solution.
|
| 397 |
+
If you believe there was a valid solution, please
|
| 398 |
+
report this as a bug."""))
|
| 399 |
+
return -M[-1, -1], argmax, argmin_dual
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
## routines that use _simplex or support those that do
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
def _abcd(M, list=False):
|
| 406 |
+
"""return parts of M as matrices or lists
|
| 407 |
+
|
| 408 |
+
Examples
|
| 409 |
+
========
|
| 410 |
+
|
| 411 |
+
>>> from sympy import Matrix
|
| 412 |
+
>>> from sympy.solvers.simplex import _abcd
|
| 413 |
+
|
| 414 |
+
>>> m = Matrix(3, 3, range(9)); m
|
| 415 |
+
Matrix([
|
| 416 |
+
[0, 1, 2],
|
| 417 |
+
[3, 4, 5],
|
| 418 |
+
[6, 7, 8]])
|
| 419 |
+
>>> a, b, c, d = _abcd(m)
|
| 420 |
+
>>> a
|
| 421 |
+
Matrix([
|
| 422 |
+
[0, 1],
|
| 423 |
+
[3, 4]])
|
| 424 |
+
>>> b
|
| 425 |
+
Matrix([
|
| 426 |
+
[2],
|
| 427 |
+
[5]])
|
| 428 |
+
>>> c
|
| 429 |
+
Matrix([[6, 7]])
|
| 430 |
+
>>> d
|
| 431 |
+
Matrix([[8]])
|
| 432 |
+
|
| 433 |
+
The matrices can be returned as compact lists, too:
|
| 434 |
+
|
| 435 |
+
>>> L = a, b, c, d = _abcd(m, list=True); L
|
| 436 |
+
([[0, 1], [3, 4]], [2, 5], [[6, 7]], [8])
|
| 437 |
+
"""
|
| 438 |
+
|
| 439 |
+
def aslist(i):
|
| 440 |
+
l = i.tolist()
|
| 441 |
+
if len(l[0]) == 1: # col vector
|
| 442 |
+
return [i[0] for i in l]
|
| 443 |
+
return l
|
| 444 |
+
|
| 445 |
+
m = M[:-1, :-1], M[:-1, -1], M[-1, :-1], M[-1:, -1:]
|
| 446 |
+
if not list:
|
| 447 |
+
return m
|
| 448 |
+
return tuple([aslist(i) for i in m])
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
def _m(a, b, c, d=None):
|
| 452 |
+
"""return Matrix([[a, b], [c, d]]) from matrices
|
| 453 |
+
in Matrix or list form.
|
| 454 |
+
|
| 455 |
+
Examples
|
| 456 |
+
========
|
| 457 |
+
|
| 458 |
+
>>> from sympy import Matrix
|
| 459 |
+
>>> from sympy.solvers.simplex import _abcd, _m
|
| 460 |
+
>>> m = Matrix(3, 3, range(9))
|
| 461 |
+
>>> L = _abcd(m, list=True); L
|
| 462 |
+
([[0, 1], [3, 4]], [2, 5], [[6, 7]], [8])
|
| 463 |
+
>>> _abcd(m)
|
| 464 |
+
(Matrix([
|
| 465 |
+
[0, 1],
|
| 466 |
+
[3, 4]]), Matrix([
|
| 467 |
+
[2],
|
| 468 |
+
[5]]), Matrix([[6, 7]]), Matrix([[8]]))
|
| 469 |
+
>>> assert m == _m(*L) == _m(*_)
|
| 470 |
+
"""
|
| 471 |
+
a, b, c, d = [Matrix(i) for i in (a, b, c, d or [0])]
|
| 472 |
+
return Matrix([[a, b], [c, d]])
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
def _primal_dual(M, factor=True):
|
| 476 |
+
"""return primal and dual function and constraints
|
| 477 |
+
assuming that ``M = Matrix([[A, b], [c, d]])`` and the
|
| 478 |
+
function ``c*x - d`` is being minimized with ``Ax >= b``
|
| 479 |
+
for nonnegative values of ``x``. The dual and its
|
| 480 |
+
constraints will be for maximizing `b.T*y - d` subject
|
| 481 |
+
to ``A.T*y <= c.T``.
|
| 482 |
+
|
| 483 |
+
Examples
|
| 484 |
+
========
|
| 485 |
+
|
| 486 |
+
>>> from sympy.solvers.simplex import _primal_dual, lpmin, lpmax
|
| 487 |
+
>>> from sympy import Matrix
|
| 488 |
+
|
| 489 |
+
The following matrix represents the primal task of
|
| 490 |
+
minimizing x + y + 7 for y >= x + 1 and y >= -2*x + 3.
|
| 491 |
+
The dual task seeks to maximize x + 3*y + 7 with
|
| 492 |
+
2*y - x <= 1 and and x + y <= 1:
|
| 493 |
+
|
| 494 |
+
>>> M = Matrix([
|
| 495 |
+
... [-1, 1, 1],
|
| 496 |
+
... [ 2, 1, 3],
|
| 497 |
+
... [ 1, 1, -7]])
|
| 498 |
+
>>> p, d = _primal_dual(M)
|
| 499 |
+
|
| 500 |
+
The minimum of the primal and maximum of the dual are the same
|
| 501 |
+
(though they occur at different points):
|
| 502 |
+
|
| 503 |
+
>>> lpmin(*p)
|
| 504 |
+
(28/3, {x1: 2/3, x2: 5/3})
|
| 505 |
+
>>> lpmax(*d)
|
| 506 |
+
(28/3, {y1: 1/3, y2: 2/3})
|
| 507 |
+
|
| 508 |
+
If the equivalent (but canonical) inequalities are
|
| 509 |
+
desired, leave `factor=True`, otherwise the unmodified
|
| 510 |
+
inequalities for M will be returned.
|
| 511 |
+
|
| 512 |
+
>>> m = Matrix([
|
| 513 |
+
... [-3, -2, 4, -2],
|
| 514 |
+
... [ 2, 0, 0, -2],
|
| 515 |
+
... [ 0, 1, -3, 0]])
|
| 516 |
+
|
| 517 |
+
>>> _primal_dual(m, False) # last condition is 2*x1 >= -2
|
| 518 |
+
((x2 - 3*x3,
|
| 519 |
+
[-3*x1 - 2*x2 + 4*x3 >= -2, 2*x1 >= -2]),
|
| 520 |
+
(-2*y1 - 2*y2,
|
| 521 |
+
[-3*y1 + 2*y2 <= 0, -2*y1 <= 1, 4*y1 <= -3]))
|
| 522 |
+
|
| 523 |
+
>>> _primal_dual(m) # condition now x1 >= -1
|
| 524 |
+
((x2 - 3*x3,
|
| 525 |
+
[-3*x1 - 2*x2 + 4*x3 >= -2, x1 >= -1]),
|
| 526 |
+
(-2*y1 - 2*y2,
|
| 527 |
+
[-3*y1 + 2*y2 <= 0, -2*y1 <= 1, 4*y1 <= -3]))
|
| 528 |
+
|
| 529 |
+
If you pass the transpose of the matrix, the primal will be
|
| 530 |
+
identified as the standard minimization problem and the
|
| 531 |
+
dual as the standard maximization:
|
| 532 |
+
|
| 533 |
+
>>> _primal_dual(m.T)
|
| 534 |
+
((-2*x1 - 2*x2,
|
| 535 |
+
[-3*x1 + 2*x2 >= 0, -2*x1 >= 1, 4*x1 >= -3]),
|
| 536 |
+
(y2 - 3*y3,
|
| 537 |
+
[-3*y1 - 2*y2 + 4*y3 <= -2, y1 <= -1]))
|
| 538 |
+
|
| 539 |
+
A matrix must have some size or else None will be returned for
|
| 540 |
+
the functions:
|
| 541 |
+
|
| 542 |
+
>>> _primal_dual(Matrix([[1, 2]]))
|
| 543 |
+
((x1 - 2, []), (-2, []))
|
| 544 |
+
|
| 545 |
+
>>> _primal_dual(Matrix([]))
|
| 546 |
+
((None, []), (None, []))
|
| 547 |
+
|
| 548 |
+
References
|
| 549 |
+
==========
|
| 550 |
+
|
| 551 |
+
.. [1] David Galvin, Relations between Primal and Dual
|
| 552 |
+
www3.nd.edu/~dgalvin1/30210/30210_F07/presentations/dual_opt.pdf
|
| 553 |
+
"""
|
| 554 |
+
if not M:
|
| 555 |
+
return (None, []), (None, [])
|
| 556 |
+
if not hasattr(M, "shape"):
|
| 557 |
+
if len(M) not in (3, 4):
|
| 558 |
+
raise ValueError("expecting Matrix or 3 or 4 lists")
|
| 559 |
+
M = _m(*M)
|
| 560 |
+
m, n = [i - 1 for i in M.shape]
|
| 561 |
+
A, b, c, d = _abcd(M)
|
| 562 |
+
d = d[0]
|
| 563 |
+
_ = lambda x: numbered_symbols(x, start=1)
|
| 564 |
+
x = Matrix([i for i, j in zip(_("x"), range(n))])
|
| 565 |
+
yT = Matrix([i for i, j in zip(_("y"), range(m))]).T
|
| 566 |
+
|
| 567 |
+
def ineq(L, r, op):
|
| 568 |
+
rv = []
|
| 569 |
+
for r in (op(i, j) for i, j in zip(L, r)):
|
| 570 |
+
if r == True:
|
| 571 |
+
continue
|
| 572 |
+
elif r == False:
|
| 573 |
+
return [False]
|
| 574 |
+
if factor:
|
| 575 |
+
f = factor_terms(r)
|
| 576 |
+
if f.lhs.is_Mul and f.rhs % f.lhs.args[0] == 0:
|
| 577 |
+
assert len(f.lhs.args) == 2, f.lhs
|
| 578 |
+
k = f.lhs.args[0]
|
| 579 |
+
r = r.func(sign(k) * f.lhs.args[1], f.rhs // abs(k))
|
| 580 |
+
rv.append(r)
|
| 581 |
+
return rv
|
| 582 |
+
|
| 583 |
+
eq = lambda x, d: x[0] - d if x else -d
|
| 584 |
+
F = eq(c * x, d)
|
| 585 |
+
f = eq(yT * b, d)
|
| 586 |
+
return (F, ineq(A * x, b, Ge)), (f, ineq(yT * A, c, Le))
|
| 587 |
+
|
| 588 |
+
|
| 589 |
+
def _rel_as_nonpos(constr, syms):
|
| 590 |
+
"""return `(np, d, aux)` where `np` is a list of nonpositive
|
| 591 |
+
expressions that represent the given constraints (possibly
|
| 592 |
+
rewritten in terms of auxilliary variables) expressible with
|
| 593 |
+
nonnegative symbols, and `d` is a dictionary mapping a given
|
| 594 |
+
symbols to an expression with an auxilliary variable. In some
|
| 595 |
+
cases a symbol will be used as part of the change of variables,
|
| 596 |
+
e.g. x: x - z1 instead of x: z1 - z2.
|
| 597 |
+
|
| 598 |
+
If any constraint is False/empty, return None. All variables in
|
| 599 |
+
``constr`` are assumed to be unbounded unless explicitly indicated
|
| 600 |
+
otherwise with a univariate constraint, e.g. ``x >= 0`` will
|
| 601 |
+
restrict ``x`` to nonnegative values.
|
| 602 |
+
|
| 603 |
+
The ``syms`` must be included so all symbols can be given an
|
| 604 |
+
unbounded assumption if they are not otherwise bound with
|
| 605 |
+
univariate conditions like ``x <= 3``.
|
| 606 |
+
|
| 607 |
+
Examples
|
| 608 |
+
========
|
| 609 |
+
|
| 610 |
+
>>> from sympy.solvers.simplex import _rel_as_nonpos
|
| 611 |
+
>>> from sympy.abc import x, y
|
| 612 |
+
>>> _rel_as_nonpos([x >= y, x >= 0, y >= 0], (x, y))
|
| 613 |
+
([-x + y], {}, [])
|
| 614 |
+
>>> _rel_as_nonpos([x >= 3, x <= 5], [x])
|
| 615 |
+
([_z1 - 2], {x: _z1 + 3}, [_z1])
|
| 616 |
+
>>> _rel_as_nonpos([x <= 5], [x])
|
| 617 |
+
([], {x: 5 - _z1}, [_z1])
|
| 618 |
+
>>> _rel_as_nonpos([x >= 1], [x])
|
| 619 |
+
([], {x: _z1 + 1}, [_z1])
|
| 620 |
+
"""
|
| 621 |
+
r = {} # replacements to handle change of variables
|
| 622 |
+
np = [] # nonpositive expressions
|
| 623 |
+
aux = [] # auxilliary symbols added
|
| 624 |
+
ui = numbered_symbols("z", start=1, cls=Dummy) # auxilliary symbols
|
| 625 |
+
univariate = {} # {x: interval} for univariate constraints
|
| 626 |
+
unbound = [] # symbols designated as unbound
|
| 627 |
+
syms = set(syms) # the expected syms of the system
|
| 628 |
+
|
| 629 |
+
# separate out univariates
|
| 630 |
+
for i in constr:
|
| 631 |
+
if i == True:
|
| 632 |
+
continue # ignore
|
| 633 |
+
if i == False:
|
| 634 |
+
return # no solution
|
| 635 |
+
if i.has(S.Infinity, S.NegativeInfinity):
|
| 636 |
+
raise ValueError("only finite bounds are permitted")
|
| 637 |
+
if isinstance(i, (Le, Ge)):
|
| 638 |
+
i = i.lts - i.gts
|
| 639 |
+
freei = i.free_symbols
|
| 640 |
+
if freei - syms:
|
| 641 |
+
raise ValueError(
|
| 642 |
+
"unexpected symbol(s) in constraint: %s" % (freei - syms)
|
| 643 |
+
)
|
| 644 |
+
if len(freei) > 1:
|
| 645 |
+
np.append(i)
|
| 646 |
+
elif freei:
|
| 647 |
+
x = freei.pop()
|
| 648 |
+
if x in unbound:
|
| 649 |
+
continue # will handle later
|
| 650 |
+
ivl = Le(i, 0, evaluate=False).as_set()
|
| 651 |
+
if x not in univariate:
|
| 652 |
+
univariate[x] = ivl
|
| 653 |
+
else:
|
| 654 |
+
univariate[x] &= ivl
|
| 655 |
+
elif i:
|
| 656 |
+
return False
|
| 657 |
+
else:
|
| 658 |
+
raise TypeError(filldedent("""
|
| 659 |
+
only equalities like Eq(x, y) or non-strict
|
| 660 |
+
inequalities like x >= y are allowed in lp, not %s""" % i))
|
| 661 |
+
|
| 662 |
+
# introduce auxilliary variables as needed for univariate
|
| 663 |
+
# inequalities
|
| 664 |
+
for x in syms:
|
| 665 |
+
i = univariate.get(x, True)
|
| 666 |
+
if not i:
|
| 667 |
+
return None # no solution possible
|
| 668 |
+
if i == True:
|
| 669 |
+
unbound.append(x)
|
| 670 |
+
continue
|
| 671 |
+
a, b = i.inf, i.sup
|
| 672 |
+
if a.is_infinite:
|
| 673 |
+
u = next(ui)
|
| 674 |
+
r[x] = b - u
|
| 675 |
+
aux.append(u)
|
| 676 |
+
elif b.is_infinite:
|
| 677 |
+
if a:
|
| 678 |
+
u = next(ui)
|
| 679 |
+
r[x] = a + u
|
| 680 |
+
aux.append(u)
|
| 681 |
+
else:
|
| 682 |
+
# standard nonnegative relationship
|
| 683 |
+
pass
|
| 684 |
+
else:
|
| 685 |
+
u = next(ui)
|
| 686 |
+
aux.append(u)
|
| 687 |
+
# shift so u = x - a => x = u + a
|
| 688 |
+
r[x] = u + a
|
| 689 |
+
# add constraint for u <= b - a
|
| 690 |
+
# since when u = b-a then x = u + a = b - a + a = b:
|
| 691 |
+
# the upper limit for x
|
| 692 |
+
np.append(u - (b - a))
|
| 693 |
+
|
| 694 |
+
# make change of variables for unbound variables
|
| 695 |
+
for x in unbound:
|
| 696 |
+
u = next(ui)
|
| 697 |
+
r[x] = u - x # reusing x
|
| 698 |
+
aux.append(u)
|
| 699 |
+
|
| 700 |
+
return np, r, aux
|
| 701 |
+
|
| 702 |
+
|
| 703 |
+
def _lp_matrices(objective, constraints):
|
| 704 |
+
"""return A, B, C, D, r, x+X, X for maximizing
|
| 705 |
+
objective = Cx - D with constraints Ax <= B, introducing
|
| 706 |
+
introducing auxilliary variables, X, as necessary to make
|
| 707 |
+
replacements of symbols as given in r, {xi: expression with Xj},
|
| 708 |
+
so all variables in x+X will take on nonnegative values.
|
| 709 |
+
|
| 710 |
+
Every univariate condition creates a semi-infinite
|
| 711 |
+
condition, e.g. a single ``x <= 3`` creates the
|
| 712 |
+
interval ``[-oo, 3]`` while ``x <= 3`` and ``x >= 2``
|
| 713 |
+
create an interval ``[2, 3]``. Variables not in a univariate
|
| 714 |
+
expression will take on nonnegative values.
|
| 715 |
+
"""
|
| 716 |
+
|
| 717 |
+
# sympify input and collect free symbols
|
| 718 |
+
F = sympify(objective)
|
| 719 |
+
np = [sympify(i) for i in constraints]
|
| 720 |
+
syms = set.union(*[i.free_symbols for i in [F] + np], set())
|
| 721 |
+
|
| 722 |
+
# change Eq(x, y) to x - y <= 0 and y - x <= 0
|
| 723 |
+
for i in range(len(np)):
|
| 724 |
+
if isinstance(np[i], Eq):
|
| 725 |
+
np[i] = np[i].lhs - np[i].rhs <= 0
|
| 726 |
+
np.append(-np[i].lhs <= 0)
|
| 727 |
+
|
| 728 |
+
# convert constraints to nonpositive expressions
|
| 729 |
+
_ = _rel_as_nonpos(np, syms)
|
| 730 |
+
if _ is None:
|
| 731 |
+
raise InfeasibleLPError(filldedent("""
|
| 732 |
+
Inconsistent/False constraint"""))
|
| 733 |
+
np, r, aux = _
|
| 734 |
+
|
| 735 |
+
# do change of variables
|
| 736 |
+
F = F.xreplace(r)
|
| 737 |
+
np = [i.xreplace(r) for i in np]
|
| 738 |
+
|
| 739 |
+
# convert to matrices
|
| 740 |
+
xx = list(ordered(syms)) + aux
|
| 741 |
+
A, B = linear_eq_to_matrix(np, xx)
|
| 742 |
+
C, D = linear_eq_to_matrix([F], xx)
|
| 743 |
+
return A, B, C, D, r, xx, aux
|
| 744 |
+
|
| 745 |
+
|
| 746 |
+
def _lp(min_max, f, constr):
|
| 747 |
+
"""Return the optimization (min or max) of ``f`` with the given
|
| 748 |
+
constraints. All variables are unbounded unless constrained.
|
| 749 |
+
|
| 750 |
+
If `min_max` is 'max' then the results corresponding to the
|
| 751 |
+
maximization of ``f`` will be returned, else the minimization.
|
| 752 |
+
The constraints can be given as Le, Ge or Eq expressions.
|
| 753 |
+
|
| 754 |
+
Examples
|
| 755 |
+
========
|
| 756 |
+
|
| 757 |
+
>>> from sympy.solvers.simplex import _lp as lp
|
| 758 |
+
>>> from sympy import Eq
|
| 759 |
+
>>> from sympy.abc import x, y, z
|
| 760 |
+
>>> f = x + y - 2*z
|
| 761 |
+
>>> c = [7*x + 4*y - 7*z <= 3, 3*x - y + 10*z <= 6]
|
| 762 |
+
>>> c += [i >= 0 for i in (x, y, z)]
|
| 763 |
+
>>> lp(min, f, c)
|
| 764 |
+
(-6/5, {x: 0, y: 0, z: 3/5})
|
| 765 |
+
|
| 766 |
+
By passing max, the maximum value for f under the constraints
|
| 767 |
+
is returned (if possible):
|
| 768 |
+
|
| 769 |
+
>>> lp(max, f, c)
|
| 770 |
+
(3/4, {x: 0, y: 3/4, z: 0})
|
| 771 |
+
|
| 772 |
+
Constraints that are equalities will require that the solution
|
| 773 |
+
also satisfy them:
|
| 774 |
+
|
| 775 |
+
>>> lp(max, f, c + [Eq(y - 9*x, 1)])
|
| 776 |
+
(5/7, {x: 0, y: 1, z: 1/7})
|
| 777 |
+
|
| 778 |
+
All symbols are reported, even if they are not in the objective
|
| 779 |
+
function:
|
| 780 |
+
|
| 781 |
+
>>> lp(min, x, [y + x >= 3, x >= 0])
|
| 782 |
+
(0, {x: 0, y: 3})
|
| 783 |
+
"""
|
| 784 |
+
# get the matrix components for the system expressed
|
| 785 |
+
# in terms of only nonnegative variables
|
| 786 |
+
A, B, C, D, r, xx, aux = _lp_matrices(f, constr)
|
| 787 |
+
|
| 788 |
+
how = str(min_max).lower()
|
| 789 |
+
if "max" in how:
|
| 790 |
+
# _simplex minimizes for Ax <= B so we
|
| 791 |
+
# have to change the sign of the function
|
| 792 |
+
# and negate the optimal value returned
|
| 793 |
+
_o, p, d = _simplex(A, B, -C, -D)
|
| 794 |
+
o = -_o
|
| 795 |
+
elif "min" in how:
|
| 796 |
+
o, p, d = _simplex(A, B, C, D)
|
| 797 |
+
else:
|
| 798 |
+
raise ValueError("expecting min or max")
|
| 799 |
+
|
| 800 |
+
# restore original variables and remove aux from p
|
| 801 |
+
p = dict(zip(xx, p))
|
| 802 |
+
if r: # p has original symbols and auxilliary symbols
|
| 803 |
+
# if r has x: x - z1 use values from p to update
|
| 804 |
+
r = {k: v.xreplace(p) for k, v in r.items()}
|
| 805 |
+
# then use the actual value of x (= x - z1) in p
|
| 806 |
+
p.update(r)
|
| 807 |
+
# don't show aux
|
| 808 |
+
p = {k: p[k] for k in ordered(p) if k not in aux}
|
| 809 |
+
|
| 810 |
+
# not returning dual since there may be extra constraints
|
| 811 |
+
# when a variable has finite bounds
|
| 812 |
+
return o, p
|
| 813 |
+
|
| 814 |
+
|
| 815 |
+
def lpmin(f, constr):
|
| 816 |
+
"""return minimum of linear equation ``f`` under
|
| 817 |
+
linear constraints expressed using Ge, Le or Eq.
|
| 818 |
+
|
| 819 |
+
All variables are unbounded unless constrained.
|
| 820 |
+
|
| 821 |
+
Examples
|
| 822 |
+
========
|
| 823 |
+
|
| 824 |
+
>>> from sympy.solvers.simplex import lpmin
|
| 825 |
+
>>> from sympy import Eq
|
| 826 |
+
>>> from sympy.abc import x, y
|
| 827 |
+
>>> lpmin(x, [2*x - 3*y >= -1, Eq(x + 3*y, 2), x <= 2*y])
|
| 828 |
+
(1/3, {x: 1/3, y: 5/9})
|
| 829 |
+
|
| 830 |
+
Negative values for variables are permitted unless explicitly
|
| 831 |
+
exluding, so minimizing ``x`` for ``x <= 3`` is an
|
| 832 |
+
unbounded problem while the following has a bounded solution:
|
| 833 |
+
|
| 834 |
+
>>> lpmin(x, [x >= 0, x <= 3])
|
| 835 |
+
(0, {x: 0})
|
| 836 |
+
|
| 837 |
+
Without indicating that ``x`` is nonnegative, there
|
| 838 |
+
is no minimum for this objective:
|
| 839 |
+
|
| 840 |
+
>>> lpmin(x, [x <= 3])
|
| 841 |
+
Traceback (most recent call last):
|
| 842 |
+
...
|
| 843 |
+
sympy.solvers.simplex.UnboundedLPError:
|
| 844 |
+
Objective function can assume arbitrarily large values!
|
| 845 |
+
|
| 846 |
+
See Also
|
| 847 |
+
========
|
| 848 |
+
linprog, lpmax
|
| 849 |
+
"""
|
| 850 |
+
return _lp(min, f, constr)
|
| 851 |
+
|
| 852 |
+
|
| 853 |
+
def lpmax(f, constr):
|
| 854 |
+
"""return maximum of linear equation ``f`` under
|
| 855 |
+
linear constraints expressed using Ge, Le or Eq.
|
| 856 |
+
|
| 857 |
+
All variables are unbounded unless constrained.
|
| 858 |
+
|
| 859 |
+
Examples
|
| 860 |
+
========
|
| 861 |
+
|
| 862 |
+
>>> from sympy.solvers.simplex import lpmax
|
| 863 |
+
>>> from sympy import Eq
|
| 864 |
+
>>> from sympy.abc import x, y
|
| 865 |
+
>>> lpmax(x, [2*x - 3*y >= -1, Eq(x+ 3*y,2), x <= 2*y])
|
| 866 |
+
(4/5, {x: 4/5, y: 2/5})
|
| 867 |
+
|
| 868 |
+
Negative values for variables are permitted unless explicitly
|
| 869 |
+
exluding:
|
| 870 |
+
|
| 871 |
+
>>> lpmax(x, [x <= -1])
|
| 872 |
+
(-1, {x: -1})
|
| 873 |
+
|
| 874 |
+
If a non-negative constraint is added for x, there is no
|
| 875 |
+
possible solution:
|
| 876 |
+
|
| 877 |
+
>>> lpmax(x, [x <= -1, x >= 0])
|
| 878 |
+
Traceback (most recent call last):
|
| 879 |
+
...
|
| 880 |
+
sympy.solvers.simplex.InfeasibleLPError: inconsistent/False constraint
|
| 881 |
+
|
| 882 |
+
See Also
|
| 883 |
+
========
|
| 884 |
+
linprog, lpmin
|
| 885 |
+
"""
|
| 886 |
+
return _lp(max, f, constr)
|
| 887 |
+
|
| 888 |
+
|
| 889 |
+
def _handle_bounds(bounds):
|
| 890 |
+
# introduce auxilliary variables as needed for univariate
|
| 891 |
+
# inequalities
|
| 892 |
+
|
| 893 |
+
unbound = []
|
| 894 |
+
R = [0] * len(bounds) # a (growing) row of zeros
|
| 895 |
+
|
| 896 |
+
def n():
|
| 897 |
+
return len(R) - 1
|
| 898 |
+
|
| 899 |
+
def Arow(inc=1):
|
| 900 |
+
R.extend([0] * inc)
|
| 901 |
+
return R[:]
|
| 902 |
+
|
| 903 |
+
row = []
|
| 904 |
+
for x, (a, b) in enumerate(bounds):
|
| 905 |
+
if a is None and b is None:
|
| 906 |
+
unbound.append(x)
|
| 907 |
+
elif a is None:
|
| 908 |
+
# r[x] = b - u
|
| 909 |
+
A = Arow()
|
| 910 |
+
A[x] = 1
|
| 911 |
+
A[n()] = 1
|
| 912 |
+
B = [b]
|
| 913 |
+
row.append((A, B))
|
| 914 |
+
A = [0] * len(A)
|
| 915 |
+
A[x] = -1
|
| 916 |
+
A[n()] = -1
|
| 917 |
+
B = [-b]
|
| 918 |
+
row.append((A, B))
|
| 919 |
+
elif b is None:
|
| 920 |
+
if a:
|
| 921 |
+
# r[x] = a + u
|
| 922 |
+
A = Arow()
|
| 923 |
+
A[x] = 1
|
| 924 |
+
A[n()] = -1
|
| 925 |
+
B = [a]
|
| 926 |
+
row.append((A, B))
|
| 927 |
+
A = [0] * len(A)
|
| 928 |
+
A[x] = -1
|
| 929 |
+
A[n()] = 1
|
| 930 |
+
B = [-a]
|
| 931 |
+
row.append((A, B))
|
| 932 |
+
else:
|
| 933 |
+
# standard nonnegative relationship
|
| 934 |
+
pass
|
| 935 |
+
else:
|
| 936 |
+
# r[x] = u + a
|
| 937 |
+
A = Arow()
|
| 938 |
+
A[x] = 1
|
| 939 |
+
A[n()] = -1
|
| 940 |
+
B = [a]
|
| 941 |
+
row.append((A, B))
|
| 942 |
+
A = [0] * len(A)
|
| 943 |
+
A[x] = -1
|
| 944 |
+
A[n()] = 1
|
| 945 |
+
B = [-a]
|
| 946 |
+
row.append((A, B))
|
| 947 |
+
# u <= b - a
|
| 948 |
+
A = [0] * len(A)
|
| 949 |
+
A[x] = 0
|
| 950 |
+
A[n()] = 1
|
| 951 |
+
B = [b - a]
|
| 952 |
+
row.append((A, B))
|
| 953 |
+
|
| 954 |
+
# make change of variables for unbound variables
|
| 955 |
+
for x in unbound:
|
| 956 |
+
# r[x] = u - v
|
| 957 |
+
A = Arow(2)
|
| 958 |
+
B = [0]
|
| 959 |
+
A[x] = 1
|
| 960 |
+
A[n()] = 1
|
| 961 |
+
A[n() - 1] = -1
|
| 962 |
+
row.append((A, B))
|
| 963 |
+
A = [0] * len(A)
|
| 964 |
+
A[x] = -1
|
| 965 |
+
A[n()] = -1
|
| 966 |
+
A[n() - 1] = 1
|
| 967 |
+
row.append((A, B))
|
| 968 |
+
|
| 969 |
+
return Matrix([r+[0]*(len(R) - len(r)) for r,_ in row]
|
| 970 |
+
), Matrix([i[1] for i in row])
|
| 971 |
+
|
| 972 |
+
|
| 973 |
+
def linprog(c, A=None, b=None, A_eq=None, b_eq=None, bounds=None):
|
| 974 |
+
"""Return the minimization of ``c*x`` with the given
|
| 975 |
+
constraints ``A*x <= b`` and ``A_eq*x = b_eq``. Unless bounds
|
| 976 |
+
are given, variables will have nonnegative values in the solution.
|
| 977 |
+
|
| 978 |
+
If ``A`` is not given, then the dimension of the system will
|
| 979 |
+
be determined by the length of ``C``.
|
| 980 |
+
|
| 981 |
+
By default, all variables will be nonnegative. If ``bounds``
|
| 982 |
+
is given as a single tuple, ``(lo, hi)``, then all variables
|
| 983 |
+
will be constrained to be between ``lo`` and ``hi``. Use
|
| 984 |
+
None for a ``lo`` or ``hi`` if it is unconstrained in the
|
| 985 |
+
negative or positive direction, respectively, e.g.
|
| 986 |
+
``(None, 0)`` indicates nonpositive values. To set
|
| 987 |
+
individual ranges, pass a list with length equal to the
|
| 988 |
+
number of columns in ``A``, each element being a tuple; if
|
| 989 |
+
only a few variables take on non-default values they can be
|
| 990 |
+
passed as a dictionary with keys giving the corresponding
|
| 991 |
+
column to which the variable is assigned, e.g. ``bounds={2:
|
| 992 |
+
(1, 4)}`` would limit the 3rd variable to have a value in
|
| 993 |
+
range ``[1, 4]``.
|
| 994 |
+
|
| 995 |
+
Examples
|
| 996 |
+
========
|
| 997 |
+
|
| 998 |
+
>>> from sympy.solvers.simplex import linprog
|
| 999 |
+
>>> from sympy import symbols, Eq, linear_eq_to_matrix as M, Matrix
|
| 1000 |
+
>>> x = x1, x2, x3, x4 = symbols('x1:5')
|
| 1001 |
+
>>> X = Matrix(x)
|
| 1002 |
+
>>> c, d = M(5*x2 + x3 + 4*x4 - x1, x)
|
| 1003 |
+
>>> a, b = M([5*x2 + 2*x3 + 5*x4 - (x1 + 5)], x)
|
| 1004 |
+
>>> aeq, beq = M([Eq(3*x2 + x4, 2), Eq(-x1 + x3 + 2*x4, 1)], x)
|
| 1005 |
+
>>> constr = [i <= j for i,j in zip(a*X, b)]
|
| 1006 |
+
>>> constr += [Eq(i, j) for i,j in zip(aeq*X, beq)]
|
| 1007 |
+
>>> linprog(c, a, b, aeq, beq)
|
| 1008 |
+
(9/2, [0, 1/2, 0, 1/2])
|
| 1009 |
+
>>> assert all(i.subs(dict(zip(x, _[1]))) for i in constr)
|
| 1010 |
+
|
| 1011 |
+
See Also
|
| 1012 |
+
========
|
| 1013 |
+
lpmin, lpmax
|
| 1014 |
+
"""
|
| 1015 |
+
|
| 1016 |
+
## the objective
|
| 1017 |
+
C = Matrix(c)
|
| 1018 |
+
if C.rows != 1 and C.cols == 1:
|
| 1019 |
+
C = C.T
|
| 1020 |
+
if C.rows != 1:
|
| 1021 |
+
raise ValueError("C must be a single row.")
|
| 1022 |
+
|
| 1023 |
+
## the inequalities
|
| 1024 |
+
if not A:
|
| 1025 |
+
if b:
|
| 1026 |
+
raise ValueError("A and b must both be given")
|
| 1027 |
+
# the governing equations will be simple constraints
|
| 1028 |
+
# on variables
|
| 1029 |
+
A, b = zeros(0, C.cols), zeros(C.cols, 1)
|
| 1030 |
+
else:
|
| 1031 |
+
A, b = [Matrix(i) for i in (A, b)]
|
| 1032 |
+
|
| 1033 |
+
if A.cols != C.cols:
|
| 1034 |
+
raise ValueError("number of columns in A and C must match")
|
| 1035 |
+
|
| 1036 |
+
## the equalities
|
| 1037 |
+
if A_eq is None:
|
| 1038 |
+
if not b_eq is None:
|
| 1039 |
+
raise ValueError("A_eq and b_eq must both be given")
|
| 1040 |
+
else:
|
| 1041 |
+
A_eq, b_eq = [Matrix(i) for i in (A_eq, b_eq)]
|
| 1042 |
+
# if x == y then x <= y and x >= y (-x <= -y)
|
| 1043 |
+
A = A.col_join(A_eq)
|
| 1044 |
+
A = A.col_join(-A_eq)
|
| 1045 |
+
b = b.col_join(b_eq)
|
| 1046 |
+
b = b.col_join(-b_eq)
|
| 1047 |
+
|
| 1048 |
+
if not (bounds is None or bounds == {} or bounds == (0, None)):
|
| 1049 |
+
## the bounds are interpreted
|
| 1050 |
+
if type(bounds) is tuple and len(bounds) == 2:
|
| 1051 |
+
bounds = [bounds] * A.cols
|
| 1052 |
+
elif len(bounds) == A.cols and all(
|
| 1053 |
+
type(i) is tuple and len(i) == 2 for i in bounds):
|
| 1054 |
+
pass # individual bounds
|
| 1055 |
+
elif type(bounds) is dict and all(
|
| 1056 |
+
type(i) is tuple and len(i) == 2
|
| 1057 |
+
for i in bounds.values()):
|
| 1058 |
+
# sparse bounds
|
| 1059 |
+
db = bounds
|
| 1060 |
+
bounds = [(0, None)] * A.cols
|
| 1061 |
+
while db:
|
| 1062 |
+
i, j = db.popitem()
|
| 1063 |
+
bounds[i] = j # IndexError if out-of-bounds indices
|
| 1064 |
+
else:
|
| 1065 |
+
raise ValueError("unexpected bounds %s" % bounds)
|
| 1066 |
+
A_, b_ = _handle_bounds(bounds)
|
| 1067 |
+
aux = A_.cols - A.cols
|
| 1068 |
+
if A:
|
| 1069 |
+
A = Matrix([[A, zeros(A.rows, aux)], [A_]])
|
| 1070 |
+
b = b.col_join(b_)
|
| 1071 |
+
else:
|
| 1072 |
+
A = A_
|
| 1073 |
+
b = b_
|
| 1074 |
+
C = C.row_join(zeros(1, aux))
|
| 1075 |
+
else:
|
| 1076 |
+
aux = -A.cols # set so -aux will give all cols below
|
| 1077 |
+
|
| 1078 |
+
o, p, d = _simplex(A, b, C)
|
| 1079 |
+
return o, p[:-aux] # don't include aux values
|
| 1080 |
+
|
| 1081 |
+
def show_linprog(c, A=None, b=None, A_eq=None, b_eq=None, bounds=None):
|
| 1082 |
+
from sympy import symbols
|
| 1083 |
+
## the objective
|
| 1084 |
+
C = Matrix(c)
|
| 1085 |
+
if C.rows != 1 and C.cols == 1:
|
| 1086 |
+
C = C.T
|
| 1087 |
+
if C.rows != 1:
|
| 1088 |
+
raise ValueError("C must be a single row.")
|
| 1089 |
+
|
| 1090 |
+
## the inequalities
|
| 1091 |
+
if not A:
|
| 1092 |
+
if b:
|
| 1093 |
+
raise ValueError("A and b must both be given")
|
| 1094 |
+
# the governing equations will be simple constraints
|
| 1095 |
+
# on variables
|
| 1096 |
+
A, b = zeros(0, C.cols), zeros(C.cols, 1)
|
| 1097 |
+
else:
|
| 1098 |
+
A, b = [Matrix(i) for i in (A, b)]
|
| 1099 |
+
|
| 1100 |
+
if A.cols != C.cols:
|
| 1101 |
+
raise ValueError("number of columns in A and C must match")
|
| 1102 |
+
|
| 1103 |
+
## the equalities
|
| 1104 |
+
if A_eq is None:
|
| 1105 |
+
if not b_eq is None:
|
| 1106 |
+
raise ValueError("A_eq and b_eq must both be given")
|
| 1107 |
+
else:
|
| 1108 |
+
A_eq, b_eq = [Matrix(i) for i in (A_eq, b_eq)]
|
| 1109 |
+
|
| 1110 |
+
if not (bounds is None or bounds == {} or bounds == (0, None)):
|
| 1111 |
+
## the bounds are interpreted
|
| 1112 |
+
if type(bounds) is tuple and len(bounds) == 2:
|
| 1113 |
+
bounds = [bounds] * A.cols
|
| 1114 |
+
elif len(bounds) == A.cols and all(
|
| 1115 |
+
type(i) is tuple and len(i) == 2 for i in bounds):
|
| 1116 |
+
pass # individual bounds
|
| 1117 |
+
elif type(bounds) is dict and all(
|
| 1118 |
+
type(i) is tuple and len(i) == 2
|
| 1119 |
+
for i in bounds.values()):
|
| 1120 |
+
# sparse bounds
|
| 1121 |
+
db = bounds
|
| 1122 |
+
bounds = [(0, None)] * A.cols
|
| 1123 |
+
while db:
|
| 1124 |
+
i, j = db.popitem()
|
| 1125 |
+
bounds[i] = j # IndexError if out-of-bounds indices
|
| 1126 |
+
else:
|
| 1127 |
+
raise ValueError("unexpected bounds %s" % bounds)
|
| 1128 |
+
|
| 1129 |
+
x = Matrix(symbols('x1:%s' % (A.cols+1)))
|
| 1130 |
+
f,c = (C*x)[0], [i<=j for i,j in zip(A*x, b)] + [Eq(i,j) for i,j in zip(A_eq*x,b_eq)]
|
| 1131 |
+
for i, (lo, hi) in enumerate(bounds):
|
| 1132 |
+
if lo is None and hi is None:
|
| 1133 |
+
continue
|
| 1134 |
+
if lo is None:
|
| 1135 |
+
c.append(x[i]<=hi)
|
| 1136 |
+
elif hi is None:
|
| 1137 |
+
c.append(x[i]>=lo)
|
| 1138 |
+
else:
|
| 1139 |
+
c.append(x[i]>=lo)
|
| 1140 |
+
c.append(x[i]<=hi)
|
| 1141 |
+
return f,c
|
evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/solvers.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/solveset.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/tests/__init__.py
ADDED
|
File without changes
|
evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/test_constantsimp.cpython-310.pyc
ADDED
|
Binary file (7.44 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/test_inequalities.cpython-310.pyc
ADDED
|
Binary file (19.6 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/test_numeric.cpython-310.pyc
ADDED
|
Binary file (5.73 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/test_pde.cpython-310.pyc
ADDED
|
Binary file (9.71 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/test_simplex.cpython-310.pyc
ADDED
|
Binary file (10.1 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/tests/test_constantsimp.py
ADDED
|
@@ -0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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
If the arbitrary constant class from issue 4435 is ever implemented, this
|
| 3 |
+
should serve as a set of test cases.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from sympy.core.function import Function
|
| 7 |
+
from sympy.core.numbers import I
|
| 8 |
+
from sympy.core.power import Pow
|
| 9 |
+
from sympy.core.relational import Eq
|
| 10 |
+
from sympy.core.singleton import S
|
| 11 |
+
from sympy.core.symbol import Symbol
|
| 12 |
+
from sympy.functions.elementary.exponential import (exp, log)
|
| 13 |
+
from sympy.functions.elementary.hyperbolic import (cosh, sinh)
|
| 14 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 15 |
+
from sympy.functions.elementary.trigonometric import (acos, cos, sin)
|
| 16 |
+
from sympy.integrals.integrals import Integral
|
| 17 |
+
from sympy.solvers.ode.ode import constantsimp, constant_renumber
|
| 18 |
+
from sympy.testing.pytest import XFAIL
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
x = Symbol('x')
|
| 22 |
+
y = Symbol('y')
|
| 23 |
+
z = Symbol('z')
|
| 24 |
+
u2 = Symbol('u2')
|
| 25 |
+
_a = Symbol('_a')
|
| 26 |
+
C1 = Symbol('C1')
|
| 27 |
+
C2 = Symbol('C2')
|
| 28 |
+
C3 = Symbol('C3')
|
| 29 |
+
f = Function('f')
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def test_constant_mul():
|
| 33 |
+
# We want C1 (Constant) below to absorb the y's, but not the x's
|
| 34 |
+
assert constant_renumber(constantsimp(y*C1, [C1])) == C1*y
|
| 35 |
+
assert constant_renumber(constantsimp(C1*y, [C1])) == C1*y
|
| 36 |
+
assert constant_renumber(constantsimp(x*C1, [C1])) == x*C1
|
| 37 |
+
assert constant_renumber(constantsimp(C1*x, [C1])) == x*C1
|
| 38 |
+
assert constant_renumber(constantsimp(2*C1, [C1])) == C1
|
| 39 |
+
assert constant_renumber(constantsimp(C1*2, [C1])) == C1
|
| 40 |
+
assert constant_renumber(constantsimp(y*C1*x, [C1, y])) == C1*x
|
| 41 |
+
assert constant_renumber(constantsimp(x*y*C1, [C1, y])) == x*C1
|
| 42 |
+
assert constant_renumber(constantsimp(y*x*C1, [C1, y])) == x*C1
|
| 43 |
+
assert constant_renumber(constantsimp(C1*x*y, [C1, y])) == C1*x
|
| 44 |
+
assert constant_renumber(constantsimp(x*C1*y, [C1, y])) == x*C1
|
| 45 |
+
assert constant_renumber(constantsimp(C1*y*(y + 1), [C1])) == C1*y*(y+1)
|
| 46 |
+
assert constant_renumber(constantsimp(y*C1*(y + 1), [C1])) == C1*y*(y+1)
|
| 47 |
+
assert constant_renumber(constantsimp(x*(y*C1), [C1])) == x*y*C1
|
| 48 |
+
assert constant_renumber(constantsimp(x*(C1*y), [C1])) == x*y*C1
|
| 49 |
+
assert constant_renumber(constantsimp(C1*(x*y), [C1, y])) == C1*x
|
| 50 |
+
assert constant_renumber(constantsimp((x*y)*C1, [C1, y])) == x*C1
|
| 51 |
+
assert constant_renumber(constantsimp((y*x)*C1, [C1, y])) == x*C1
|
| 52 |
+
assert constant_renumber(constantsimp(y*(y + 1)*C1, [C1, y])) == C1
|
| 53 |
+
assert constant_renumber(constantsimp((C1*x)*y, [C1, y])) == C1*x
|
| 54 |
+
assert constant_renumber(constantsimp(y*(x*C1), [C1, y])) == x*C1
|
| 55 |
+
assert constant_renumber(constantsimp((x*C1)*y, [C1, y])) == x*C1
|
| 56 |
+
assert constant_renumber(constantsimp(C1*x*y*x*y*2, [C1, y])) == C1*x**2
|
| 57 |
+
assert constant_renumber(constantsimp(C1*x*y*z, [C1, y, z])) == C1*x
|
| 58 |
+
assert constant_renumber(constantsimp(C1*x*y**2*sin(z), [C1, y, z])) == C1*x
|
| 59 |
+
assert constant_renumber(constantsimp(C1*C1, [C1])) == C1
|
| 60 |
+
assert constant_renumber(constantsimp(C1*C2, [C1, C2])) == C1
|
| 61 |
+
assert constant_renumber(constantsimp(C2*C2, [C1, C2])) == C1
|
| 62 |
+
assert constant_renumber(constantsimp(C1*C1*C2, [C1, C2])) == C1
|
| 63 |
+
assert constant_renumber(constantsimp(C1*x*2**x, [C1])) == C1*x*2**x
|
| 64 |
+
|
| 65 |
+
def test_constant_add():
|
| 66 |
+
assert constant_renumber(constantsimp(C1 + C1, [C1])) == C1
|
| 67 |
+
assert constant_renumber(constantsimp(C1 + 2, [C1])) == C1
|
| 68 |
+
assert constant_renumber(constantsimp(2 + C1, [C1])) == C1
|
| 69 |
+
assert constant_renumber(constantsimp(C1 + y, [C1, y])) == C1
|
| 70 |
+
assert constant_renumber(constantsimp(C1 + x, [C1])) == C1 + x
|
| 71 |
+
assert constant_renumber(constantsimp(C1 + C1, [C1])) == C1
|
| 72 |
+
assert constant_renumber(constantsimp(C1 + C2, [C1, C2])) == C1
|
| 73 |
+
assert constant_renumber(constantsimp(C2 + C1, [C1, C2])) == C1
|
| 74 |
+
assert constant_renumber(constantsimp(C1 + C2 + C1, [C1, C2])) == C1
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def test_constant_power_as_base():
|
| 78 |
+
assert constant_renumber(constantsimp(C1**C1, [C1])) == C1
|
| 79 |
+
assert constant_renumber(constantsimp(Pow(C1, C1), [C1])) == C1
|
| 80 |
+
assert constant_renumber(constantsimp(C1**C1, [C1])) == C1
|
| 81 |
+
assert constant_renumber(constantsimp(C1**C2, [C1, C2])) == C1
|
| 82 |
+
assert constant_renumber(constantsimp(C2**C1, [C1, C2])) == C1
|
| 83 |
+
assert constant_renumber(constantsimp(C2**C2, [C1, C2])) == C1
|
| 84 |
+
assert constant_renumber(constantsimp(C1**y, [C1, y])) == C1
|
| 85 |
+
assert constant_renumber(constantsimp(C1**x, [C1])) == C1**x
|
| 86 |
+
assert constant_renumber(constantsimp(C1**2, [C1])) == C1
|
| 87 |
+
assert constant_renumber(
|
| 88 |
+
constantsimp(C1**(x*y), [C1])) == C1**(x*y)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def test_constant_power_as_exp():
|
| 92 |
+
assert constant_renumber(constantsimp(x**C1, [C1])) == x**C1
|
| 93 |
+
assert constant_renumber(constantsimp(y**C1, [C1, y])) == C1
|
| 94 |
+
assert constant_renumber(constantsimp(x**y**C1, [C1, y])) == x**C1
|
| 95 |
+
assert constant_renumber(
|
| 96 |
+
constantsimp((x**y)**C1, [C1])) == (x**y)**C1
|
| 97 |
+
assert constant_renumber(
|
| 98 |
+
constantsimp(x**(y**C1), [C1, y])) == x**C1
|
| 99 |
+
assert constant_renumber(constantsimp(x**C1**y, [C1, y])) == x**C1
|
| 100 |
+
assert constant_renumber(
|
| 101 |
+
constantsimp(x**(C1**y), [C1, y])) == x**C1
|
| 102 |
+
assert constant_renumber(
|
| 103 |
+
constantsimp((x**C1)**y, [C1])) == (x**C1)**y
|
| 104 |
+
assert constant_renumber(constantsimp(2**C1, [C1])) == C1
|
| 105 |
+
assert constant_renumber(constantsimp(S(2)**C1, [C1])) == C1
|
| 106 |
+
assert constant_renumber(constantsimp(exp(C1), [C1])) == C1
|
| 107 |
+
assert constant_renumber(
|
| 108 |
+
constantsimp(exp(C1 + x), [C1])) == C1*exp(x)
|
| 109 |
+
assert constant_renumber(constantsimp(Pow(2, C1), [C1])) == C1
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def test_constant_function():
|
| 113 |
+
assert constant_renumber(constantsimp(sin(C1), [C1])) == C1
|
| 114 |
+
assert constant_renumber(constantsimp(f(C1), [C1])) == C1
|
| 115 |
+
assert constant_renumber(constantsimp(f(C1, C1), [C1])) == C1
|
| 116 |
+
assert constant_renumber(constantsimp(f(C1, C2), [C1, C2])) == C1
|
| 117 |
+
assert constant_renumber(constantsimp(f(C2, C1), [C1, C2])) == C1
|
| 118 |
+
assert constant_renumber(constantsimp(f(C2, C2), [C1, C2])) == C1
|
| 119 |
+
assert constant_renumber(
|
| 120 |
+
constantsimp(f(C1, x), [C1])) == f(C1, x)
|
| 121 |
+
assert constant_renumber(constantsimp(f(C1, y), [C1, y])) == C1
|
| 122 |
+
assert constant_renumber(constantsimp(f(y, C1), [C1, y])) == C1
|
| 123 |
+
assert constant_renumber(constantsimp(f(C1, y, C2), [C1, C2, y])) == C1
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def test_constant_function_multiple():
|
| 127 |
+
# The rules to not renumber in this case would be too complicated, and
|
| 128 |
+
# dsolve is not likely to ever encounter anything remotely like this.
|
| 129 |
+
assert constant_renumber(
|
| 130 |
+
constantsimp(f(C1, C1, x), [C1])) == f(C1, C1, x)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def test_constant_multiple():
|
| 134 |
+
assert constant_renumber(constantsimp(C1*2 + 2, [C1])) == C1
|
| 135 |
+
assert constant_renumber(constantsimp(x*2/C1, [C1])) == C1*x
|
| 136 |
+
assert constant_renumber(constantsimp(C1**2*2 + 2, [C1])) == C1
|
| 137 |
+
assert constant_renumber(
|
| 138 |
+
constantsimp(sin(2*C1) + x + sqrt(2), [C1])) == C1 + x
|
| 139 |
+
assert constant_renumber(constantsimp(2*C1 + C2, [C1, C2])) == C1
|
| 140 |
+
|
| 141 |
+
def test_constant_repeated():
|
| 142 |
+
assert C1 + C1*x == constant_renumber( C1 + C1*x)
|
| 143 |
+
|
| 144 |
+
def test_ode_solutions():
|
| 145 |
+
# only a few examples here, the rest will be tested in the actual dsolve tests
|
| 146 |
+
assert constant_renumber(constantsimp(C1*exp(2*x) + exp(x)*(C2 + C3), [C1, C2, C3])) == \
|
| 147 |
+
constant_renumber(C1*exp(x) + C2*exp(2*x))
|
| 148 |
+
assert constant_renumber(
|
| 149 |
+
constantsimp(Eq(f(x), I*C1*sinh(x/3) + C2*cosh(x/3)), [C1, C2])
|
| 150 |
+
) == constant_renumber(Eq(f(x), C1*sinh(x/3) + C2*cosh(x/3)))
|
| 151 |
+
assert constant_renumber(constantsimp(Eq(f(x), acos((-C1)/cos(x))), [C1])) == \
|
| 152 |
+
Eq(f(x), acos(C1/cos(x)))
|
| 153 |
+
assert constant_renumber(
|
| 154 |
+
constantsimp(Eq(log(f(x)/C1) + 2*exp(x/f(x)), 0), [C1])
|
| 155 |
+
) == Eq(log(C1*f(x)) + 2*exp(x/f(x)), 0)
|
| 156 |
+
assert constant_renumber(constantsimp(Eq(log(x*sqrt(2)*sqrt(1/x)*sqrt(f(x))
|
| 157 |
+
/C1) + x**2/(2*f(x)**2), 0), [C1])) == \
|
| 158 |
+
Eq(log(C1*sqrt(x)*sqrt(f(x))) + x**2/(2*f(x)**2), 0)
|
| 159 |
+
assert constant_renumber(constantsimp(Eq(-exp(-f(x)/x)*sin(f(x)/x)/2 + log(x/C1) -
|
| 160 |
+
cos(f(x)/x)*exp(-f(x)/x)/2, 0), [C1])) == \
|
| 161 |
+
Eq(-exp(-f(x)/x)*sin(f(x)/x)/2 + log(C1*x) - cos(f(x)/x)*
|
| 162 |
+
exp(-f(x)/x)/2, 0)
|
| 163 |
+
assert constant_renumber(constantsimp(Eq(-Integral(-1/(sqrt(1 - u2**2)*u2),
|
| 164 |
+
(u2, _a, x/f(x))) + log(f(x)/C1), 0), [C1])) == \
|
| 165 |
+
Eq(-Integral(-1/(u2*sqrt(1 - u2**2)), (u2, _a, x/f(x))) +
|
| 166 |
+
log(C1*f(x)), 0)
|
| 167 |
+
assert [constantsimp(i, [C1]) for i in [Eq(f(x), sqrt(-C1*x + x**2)), Eq(f(x), -sqrt(-C1*x + x**2))]] == \
|
| 168 |
+
[Eq(f(x), sqrt(x*(C1 + x))), Eq(f(x), -sqrt(x*(C1 + x)))]
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
@XFAIL
|
| 172 |
+
def test_nonlocal_simplification():
|
| 173 |
+
assert constantsimp(C1 + C2+x*C2, [C1, C2]) == C1 + C2*x
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def test_constant_Eq():
|
| 177 |
+
# C1 on the rhs is well-tested, but the lhs is only tested here
|
| 178 |
+
assert constantsimp(Eq(C1, 3 + f(x)*x), [C1]) == Eq(x*f(x), C1)
|
| 179 |
+
assert constantsimp(Eq(C1, 3 * f(x)*x), [C1]) == Eq(f(x)*x, C1)
|
evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/tests/test_decompogen.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.solvers.decompogen import decompogen, compogen
|
| 2 |
+
from sympy.core.symbol import symbols
|
| 3 |
+
from sympy.functions.elementary.complexes import Abs
|
| 4 |
+
from sympy.functions.elementary.exponential import exp
|
| 5 |
+
from sympy.functions.elementary.miscellaneous import sqrt, Max
|
| 6 |
+
from sympy.functions.elementary.trigonometric import (cos, sin)
|
| 7 |
+
from sympy.testing.pytest import XFAIL, raises
|
| 8 |
+
|
| 9 |
+
x, y = symbols('x y')
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def test_decompogen():
|
| 13 |
+
assert decompogen(sin(cos(x)), x) == [sin(x), cos(x)]
|
| 14 |
+
assert decompogen(sin(x)**2 + sin(x) + 1, x) == [x**2 + x + 1, sin(x)]
|
| 15 |
+
assert decompogen(sqrt(6*x**2 - 5), x) == [sqrt(x), 6*x**2 - 5]
|
| 16 |
+
assert decompogen(sin(sqrt(cos(x**2 + 1))), x) == [sin(x), sqrt(x), cos(x), x**2 + 1]
|
| 17 |
+
assert decompogen(Abs(cos(x)**2 + 3*cos(x) - 4), x) == [Abs(x), x**2 + 3*x - 4, cos(x)]
|
| 18 |
+
assert decompogen(sin(x)**2 + sin(x) - sqrt(3)/2, x) == [x**2 + x - sqrt(3)/2, sin(x)]
|
| 19 |
+
assert decompogen(Abs(cos(y)**2 + 3*cos(x) - 4), x) == [Abs(x), 3*x + cos(y)**2 - 4, cos(x)]
|
| 20 |
+
assert decompogen(x, y) == [x]
|
| 21 |
+
assert decompogen(1, x) == [1]
|
| 22 |
+
assert decompogen(Max(3, x), x) == [Max(3, x)]
|
| 23 |
+
raises(TypeError, lambda: decompogen(x < 5, x))
|
| 24 |
+
u = 2*x + 3
|
| 25 |
+
assert decompogen(Max(sqrt(u),(u)**2), x) == [Max(sqrt(x), x**2), u]
|
| 26 |
+
assert decompogen(Max(u, u**2, y), x) == [Max(x, x**2, y), u]
|
| 27 |
+
assert decompogen(Max(sin(x), u), x) == [Max(2*x + 3, sin(x))]
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def test_decompogen_poly():
|
| 31 |
+
assert decompogen(x**4 + 2*x**2 + 1, x) == [x**2 + 2*x + 1, x**2]
|
| 32 |
+
assert decompogen(x**4 + 2*x**3 - x - 1, x) == [x**2 - x - 1, x**2 + x]
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@XFAIL
|
| 36 |
+
def test_decompogen_fails():
|
| 37 |
+
A = lambda x: x**2 + 2*x + 3
|
| 38 |
+
B = lambda x: 4*x**2 + 5*x + 6
|
| 39 |
+
assert decompogen(A(x*exp(x)), x) == [x**2 + 2*x + 3, x*exp(x)]
|
| 40 |
+
assert decompogen(A(B(x)), x) == [x**2 + 2*x + 3, 4*x**2 + 5*x + 6]
|
| 41 |
+
assert decompogen(A(1/x + 1/x**2), x) == [x**2 + 2*x + 3, 1/x + 1/x**2]
|
| 42 |
+
assert decompogen(A(1/x + 2/(x + 1)), x) == [x**2 + 2*x + 3, 1/x + 2/(x + 1)]
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def test_compogen():
|
| 46 |
+
assert compogen([sin(x), cos(x)], x) == sin(cos(x))
|
| 47 |
+
assert compogen([x**2 + x + 1, sin(x)], x) == sin(x)**2 + sin(x) + 1
|
| 48 |
+
assert compogen([sqrt(x), 6*x**2 - 5], x) == sqrt(6*x**2 - 5)
|
| 49 |
+
assert compogen([sin(x), sqrt(x), cos(x), x**2 + 1], x) == sin(sqrt(
|
| 50 |
+
cos(x**2 + 1)))
|
| 51 |
+
assert compogen([Abs(x), x**2 + 3*x - 4, cos(x)], x) == Abs(cos(x)**2 +
|
| 52 |
+
3*cos(x) - 4)
|
| 53 |
+
assert compogen([x**2 + x - sqrt(3)/2, sin(x)], x) == (sin(x)**2 + sin(x) -
|
| 54 |
+
sqrt(3)/2)
|
| 55 |
+
assert compogen([Abs(x), 3*x + cos(y)**2 - 4, cos(x)], x) == \
|
| 56 |
+
Abs(3*cos(x) + cos(y)**2 - 4)
|
| 57 |
+
assert compogen([x**2 + 2*x + 1, x**2], x) == x**4 + 2*x**2 + 1
|
| 58 |
+
# the result is in unsimplified form
|
| 59 |
+
assert compogen([x**2 - x - 1, x**2 + x], x) == -x**2 - x + (x**2 + x)**2 - 1
|
evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/tests/test_inequalities.py
ADDED
|
@@ -0,0 +1,500 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for tools for solving inequalities and systems of inequalities. """
|
| 2 |
+
|
| 3 |
+
from sympy.concrete.summations import Sum
|
| 4 |
+
from sympy.core.function import Function
|
| 5 |
+
from sympy.core.numbers import I, Rational, oo, pi
|
| 6 |
+
from sympy.core.relational import Eq, Ge, Gt, Le, Lt, Ne
|
| 7 |
+
from sympy.core.singleton import S
|
| 8 |
+
from sympy.core.symbol import (Dummy, Symbol)
|
| 9 |
+
from sympy.functions.elementary.complexes import Abs
|
| 10 |
+
from sympy.functions.elementary.exponential import exp, log
|
| 11 |
+
from sympy.functions.elementary.miscellaneous import root, sqrt
|
| 12 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
| 13 |
+
from sympy.functions.elementary.trigonometric import cos, sin, tan
|
| 14 |
+
from sympy.integrals.integrals import Integral
|
| 15 |
+
from sympy.logic.boolalg import And, Or
|
| 16 |
+
from sympy.polys.polytools import Poly, PurePoly
|
| 17 |
+
from sympy.sets.sets import FiniteSet, Interval, Union
|
| 18 |
+
from sympy.solvers.inequalities import (reduce_inequalities,
|
| 19 |
+
solve_poly_inequality as psolve,
|
| 20 |
+
reduce_rational_inequalities,
|
| 21 |
+
solve_univariate_inequality as isolve,
|
| 22 |
+
reduce_abs_inequality,
|
| 23 |
+
_solve_inequality)
|
| 24 |
+
from sympy.polys.rootoftools import rootof
|
| 25 |
+
from sympy.solvers.solvers import solve
|
| 26 |
+
from sympy.solvers.solveset import solveset
|
| 27 |
+
from sympy.core.mod import Mod
|
| 28 |
+
from sympy.abc import x, y
|
| 29 |
+
|
| 30 |
+
from sympy.testing.pytest import raises, XFAIL
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
inf = oo.evalf()
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def test_solve_poly_inequality():
|
| 37 |
+
assert psolve(Poly(0, x), '==') == [S.Reals]
|
| 38 |
+
assert psolve(Poly(1, x), '==') == [S.EmptySet]
|
| 39 |
+
assert psolve(PurePoly(x + 1, x), ">") == [Interval(-1, oo, True, False)]
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def test_reduce_poly_inequalities_real_interval():
|
| 43 |
+
assert reduce_rational_inequalities(
|
| 44 |
+
[[Eq(x**2, 0)]], x, relational=False) == FiniteSet(0)
|
| 45 |
+
assert reduce_rational_inequalities(
|
| 46 |
+
[[Le(x**2, 0)]], x, relational=False) == FiniteSet(0)
|
| 47 |
+
assert reduce_rational_inequalities(
|
| 48 |
+
[[Lt(x**2, 0)]], x, relational=False) == S.EmptySet
|
| 49 |
+
assert reduce_rational_inequalities(
|
| 50 |
+
[[Ge(x**2, 0)]], x, relational=False) == \
|
| 51 |
+
S.Reals if x.is_real else Interval(-oo, oo)
|
| 52 |
+
assert reduce_rational_inequalities(
|
| 53 |
+
[[Gt(x**2, 0)]], x, relational=False) == \
|
| 54 |
+
FiniteSet(0).complement(S.Reals)
|
| 55 |
+
assert reduce_rational_inequalities(
|
| 56 |
+
[[Ne(x**2, 0)]], x, relational=False) == \
|
| 57 |
+
FiniteSet(0).complement(S.Reals)
|
| 58 |
+
|
| 59 |
+
assert reduce_rational_inequalities(
|
| 60 |
+
[[Eq(x**2, 1)]], x, relational=False) == FiniteSet(-1, 1)
|
| 61 |
+
assert reduce_rational_inequalities(
|
| 62 |
+
[[Le(x**2, 1)]], x, relational=False) == Interval(-1, 1)
|
| 63 |
+
assert reduce_rational_inequalities(
|
| 64 |
+
[[Lt(x**2, 1)]], x, relational=False) == Interval(-1, 1, True, True)
|
| 65 |
+
assert reduce_rational_inequalities(
|
| 66 |
+
[[Ge(x**2, 1)]], x, relational=False) == \
|
| 67 |
+
Union(Interval(-oo, -1), Interval(1, oo))
|
| 68 |
+
assert reduce_rational_inequalities(
|
| 69 |
+
[[Gt(x**2, 1)]], x, relational=False) == \
|
| 70 |
+
Interval(-1, 1).complement(S.Reals)
|
| 71 |
+
assert reduce_rational_inequalities(
|
| 72 |
+
[[Ne(x**2, 1)]], x, relational=False) == \
|
| 73 |
+
FiniteSet(-1, 1).complement(S.Reals)
|
| 74 |
+
assert reduce_rational_inequalities([[Eq(
|
| 75 |
+
x**2, 1.0)]], x, relational=False) == FiniteSet(-1.0, 1.0).evalf()
|
| 76 |
+
assert reduce_rational_inequalities(
|
| 77 |
+
[[Le(x**2, 1.0)]], x, relational=False) == Interval(-1.0, 1.0)
|
| 78 |
+
assert reduce_rational_inequalities([[Lt(
|
| 79 |
+
x**2, 1.0)]], x, relational=False) == Interval(-1.0, 1.0, True, True)
|
| 80 |
+
assert reduce_rational_inequalities(
|
| 81 |
+
[[Ge(x**2, 1.0)]], x, relational=False) == \
|
| 82 |
+
Union(Interval(-inf, -1.0), Interval(1.0, inf))
|
| 83 |
+
assert reduce_rational_inequalities(
|
| 84 |
+
[[Gt(x**2, 1.0)]], x, relational=False) == \
|
| 85 |
+
Union(Interval(-inf, -1.0, right_open=True),
|
| 86 |
+
Interval(1.0, inf, left_open=True))
|
| 87 |
+
assert reduce_rational_inequalities([[Ne(
|
| 88 |
+
x**2, 1.0)]], x, relational=False) == \
|
| 89 |
+
FiniteSet(-1.0, 1.0).complement(S.Reals)
|
| 90 |
+
|
| 91 |
+
s = sqrt(2)
|
| 92 |
+
|
| 93 |
+
assert reduce_rational_inequalities([[Lt(
|
| 94 |
+
x**2 - 1, 0), Gt(x**2 - 1, 0)]], x, relational=False) == S.EmptySet
|
| 95 |
+
assert reduce_rational_inequalities([[Le(x**2 - 1, 0), Ge(
|
| 96 |
+
x**2 - 1, 0)]], x, relational=False) == FiniteSet(-1, 1)
|
| 97 |
+
assert reduce_rational_inequalities(
|
| 98 |
+
[[Le(x**2 - 2, 0), Ge(x**2 - 1, 0)]], x, relational=False
|
| 99 |
+
) == Union(Interval(-s, -1, False, False), Interval(1, s, False, False))
|
| 100 |
+
assert reduce_rational_inequalities(
|
| 101 |
+
[[Le(x**2 - 2, 0), Gt(x**2 - 1, 0)]], x, relational=False
|
| 102 |
+
) == Union(Interval(-s, -1, False, True), Interval(1, s, True, False))
|
| 103 |
+
assert reduce_rational_inequalities(
|
| 104 |
+
[[Lt(x**2 - 2, 0), Ge(x**2 - 1, 0)]], x, relational=False
|
| 105 |
+
) == Union(Interval(-s, -1, True, False), Interval(1, s, False, True))
|
| 106 |
+
assert reduce_rational_inequalities(
|
| 107 |
+
[[Lt(x**2 - 2, 0), Gt(x**2 - 1, 0)]], x, relational=False
|
| 108 |
+
) == Union(Interval(-s, -1, True, True), Interval(1, s, True, True))
|
| 109 |
+
assert reduce_rational_inequalities(
|
| 110 |
+
[[Lt(x**2 - 2, 0), Ne(x**2 - 1, 0)]], x, relational=False
|
| 111 |
+
) == Union(Interval(-s, -1, True, True), Interval(-1, 1, True, True),
|
| 112 |
+
Interval(1, s, True, True))
|
| 113 |
+
|
| 114 |
+
assert reduce_rational_inequalities([[Lt(x**2, -1.)]], x) is S.false
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def test_reduce_poly_inequalities_complex_relational():
|
| 118 |
+
assert reduce_rational_inequalities(
|
| 119 |
+
[[Eq(x**2, 0)]], x, relational=True) == Eq(x, 0)
|
| 120 |
+
assert reduce_rational_inequalities(
|
| 121 |
+
[[Le(x**2, 0)]], x, relational=True) == Eq(x, 0)
|
| 122 |
+
assert reduce_rational_inequalities(
|
| 123 |
+
[[Lt(x**2, 0)]], x, relational=True) == False
|
| 124 |
+
assert reduce_rational_inequalities(
|
| 125 |
+
[[Ge(x**2, 0)]], x, relational=True) == And(Lt(-oo, x), Lt(x, oo))
|
| 126 |
+
assert reduce_rational_inequalities(
|
| 127 |
+
[[Gt(x**2, 0)]], x, relational=True) == \
|
| 128 |
+
And(Gt(x, -oo), Lt(x, oo), Ne(x, 0))
|
| 129 |
+
assert reduce_rational_inequalities(
|
| 130 |
+
[[Ne(x**2, 0)]], x, relational=True) == \
|
| 131 |
+
And(Gt(x, -oo), Lt(x, oo), Ne(x, 0))
|
| 132 |
+
|
| 133 |
+
for one in (S.One, S(1.0)):
|
| 134 |
+
inf = one*oo
|
| 135 |
+
assert reduce_rational_inequalities(
|
| 136 |
+
[[Eq(x**2, one)]], x, relational=True) == \
|
| 137 |
+
Or(Eq(x, -one), Eq(x, one))
|
| 138 |
+
assert reduce_rational_inequalities(
|
| 139 |
+
[[Le(x**2, one)]], x, relational=True) == \
|
| 140 |
+
And(And(Le(-one, x), Le(x, one)))
|
| 141 |
+
assert reduce_rational_inequalities(
|
| 142 |
+
[[Lt(x**2, one)]], x, relational=True) == \
|
| 143 |
+
And(And(Lt(-one, x), Lt(x, one)))
|
| 144 |
+
assert reduce_rational_inequalities(
|
| 145 |
+
[[Ge(x**2, one)]], x, relational=True) == \
|
| 146 |
+
And(Or(And(Le(one, x), Lt(x, inf)), And(Le(x, -one), Lt(-inf, x))))
|
| 147 |
+
assert reduce_rational_inequalities(
|
| 148 |
+
[[Gt(x**2, one)]], x, relational=True) == \
|
| 149 |
+
And(Or(And(Lt(-inf, x), Lt(x, -one)), And(Lt(one, x), Lt(x, inf))))
|
| 150 |
+
assert reduce_rational_inequalities(
|
| 151 |
+
[[Ne(x**2, one)]], x, relational=True) == \
|
| 152 |
+
Or(And(Lt(-inf, x), Lt(x, -one)),
|
| 153 |
+
And(Lt(-one, x), Lt(x, one)),
|
| 154 |
+
And(Lt(one, x), Lt(x, inf)))
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def test_reduce_rational_inequalities_real_relational():
|
| 158 |
+
assert reduce_rational_inequalities([], x) == False
|
| 159 |
+
assert reduce_rational_inequalities(
|
| 160 |
+
[[(x**2 + 3*x + 2)/(x**2 - 16) >= 0]], x, relational=False) == \
|
| 161 |
+
Union(Interval.open(-oo, -4), Interval(-2, -1), Interval.open(4, oo))
|
| 162 |
+
|
| 163 |
+
assert reduce_rational_inequalities(
|
| 164 |
+
[[((-2*x - 10)*(3 - x))/((x**2 + 5)*(x - 2)**2) < 0]], x,
|
| 165 |
+
relational=False) == \
|
| 166 |
+
Union(Interval.open(-5, 2), Interval.open(2, 3))
|
| 167 |
+
|
| 168 |
+
assert reduce_rational_inequalities([[(x + 1)/(x - 5) <= 0]], x,
|
| 169 |
+
relational=False) == \
|
| 170 |
+
Interval.Ropen(-1, 5)
|
| 171 |
+
|
| 172 |
+
assert reduce_rational_inequalities([[(x**2 + 4*x + 3)/(x - 1) > 0]], x,
|
| 173 |
+
relational=False) == \
|
| 174 |
+
Union(Interval.open(-3, -1), Interval.open(1, oo))
|
| 175 |
+
|
| 176 |
+
assert reduce_rational_inequalities([[(x**2 - 16)/(x - 1)**2 < 0]], x,
|
| 177 |
+
relational=False) == \
|
| 178 |
+
Union(Interval.open(-4, 1), Interval.open(1, 4))
|
| 179 |
+
|
| 180 |
+
assert reduce_rational_inequalities([[(3*x + 1)/(x + 4) >= 1]], x,
|
| 181 |
+
relational=False) == \
|
| 182 |
+
Union(Interval.open(-oo, -4), Interval.Ropen(Rational(3, 2), oo))
|
| 183 |
+
|
| 184 |
+
assert reduce_rational_inequalities([[(x - 8)/x <= 3 - x]], x,
|
| 185 |
+
relational=False) == \
|
| 186 |
+
Union(Interval.Lopen(-oo, -2), Interval.Lopen(0, 4))
|
| 187 |
+
|
| 188 |
+
# issue sympy/sympy#10237
|
| 189 |
+
assert reduce_rational_inequalities(
|
| 190 |
+
[[x < oo, x >= 0, -oo < x]], x, relational=False) == Interval(0, oo)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def test_reduce_abs_inequalities():
|
| 194 |
+
e = abs(x - 5) < 3
|
| 195 |
+
ans = And(Lt(2, x), Lt(x, 8))
|
| 196 |
+
assert reduce_inequalities(e) == ans
|
| 197 |
+
assert reduce_inequalities(e, x) == ans
|
| 198 |
+
assert reduce_inequalities(abs(x - 5)) == Eq(x, 5)
|
| 199 |
+
assert reduce_inequalities(
|
| 200 |
+
abs(2*x + 3) >= 8) == Or(And(Le(Rational(5, 2), x), Lt(x, oo)),
|
| 201 |
+
And(Le(x, Rational(-11, 2)), Lt(-oo, x)))
|
| 202 |
+
assert reduce_inequalities(abs(x - 4) + abs(
|
| 203 |
+
3*x - 5) < 7) == And(Lt(S.Half, x), Lt(x, 4))
|
| 204 |
+
assert reduce_inequalities(abs(x - 4) + abs(3*abs(x) - 5) < 7) == \
|
| 205 |
+
Or(And(S(-2) < x, x < -1), And(S.Half < x, x < 4))
|
| 206 |
+
|
| 207 |
+
nr = Symbol('nr', extended_real=False)
|
| 208 |
+
raises(TypeError, lambda: reduce_inequalities(abs(nr - 5) < 3))
|
| 209 |
+
assert reduce_inequalities(x < 3, symbols=[x, nr]) == And(-oo < x, x < 3)
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def test_reduce_inequalities_general():
|
| 213 |
+
assert reduce_inequalities(Ge(sqrt(2)*x, 1)) == And(sqrt(2)/2 <= x, x < oo)
|
| 214 |
+
assert reduce_inequalities(x + 1 > 0) == And(S.NegativeOne < x, x < oo)
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def test_reduce_inequalities_boolean():
|
| 218 |
+
assert reduce_inequalities(
|
| 219 |
+
[Eq(x**2, 0), True]) == Eq(x, 0)
|
| 220 |
+
assert reduce_inequalities([Eq(x**2, 0), False]) == False
|
| 221 |
+
assert reduce_inequalities(x**2 >= 0) is S.true # issue 10196
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def test_reduce_inequalities_multivariate():
|
| 225 |
+
assert reduce_inequalities([Ge(x**2, 1), Ge(y**2, 1)]) == And(
|
| 226 |
+
Or(And(Le(S.One, x), Lt(x, oo)), And(Le(x, -1), Lt(-oo, x))),
|
| 227 |
+
Or(And(Le(S.One, y), Lt(y, oo)), And(Le(y, -1), Lt(-oo, y))))
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
def test_reduce_inequalities_errors():
|
| 231 |
+
raises(NotImplementedError, lambda: reduce_inequalities(Ge(sin(x) + x, 1)))
|
| 232 |
+
raises(NotImplementedError, lambda: reduce_inequalities(Ge(x**2*y + y, 1)))
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def test__solve_inequalities():
|
| 236 |
+
assert reduce_inequalities(x + y < 1, symbols=[x]) == (x < 1 - y)
|
| 237 |
+
assert reduce_inequalities(x + y >= 1, symbols=[x]) == (x < oo) & (x >= -y + 1)
|
| 238 |
+
assert reduce_inequalities(Eq(0, x - y), symbols=[x]) == Eq(x, y)
|
| 239 |
+
assert reduce_inequalities(Ne(0, x - y), symbols=[x]) == Ne(x, y)
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def test_issue_6343():
|
| 243 |
+
eq = -3*x**2/2 - x*Rational(45, 4) + Rational(33, 2) > 0
|
| 244 |
+
assert reduce_inequalities(eq) == \
|
| 245 |
+
And(x < Rational(-15, 4) + sqrt(401)/4, -sqrt(401)/4 - Rational(15, 4) < x)
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def test_issue_8235():
|
| 249 |
+
assert reduce_inequalities(x**2 - 1 < 0) == \
|
| 250 |
+
And(S.NegativeOne < x, x < 1)
|
| 251 |
+
assert reduce_inequalities(x**2 - 1 <= 0) == \
|
| 252 |
+
And(S.NegativeOne <= x, x <= 1)
|
| 253 |
+
assert reduce_inequalities(x**2 - 1 > 0) == \
|
| 254 |
+
Or(And(-oo < x, x < -1), And(x < oo, S.One < x))
|
| 255 |
+
assert reduce_inequalities(x**2 - 1 >= 0) == \
|
| 256 |
+
Or(And(-oo < x, x <= -1), And(S.One <= x, x < oo))
|
| 257 |
+
|
| 258 |
+
eq = x**8 + x - 9 # we want CRootOf solns here
|
| 259 |
+
sol = solve(eq >= 0)
|
| 260 |
+
tru = Or(And(rootof(eq, 1) <= x, x < oo), And(-oo < x, x <= rootof(eq, 0)))
|
| 261 |
+
assert sol == tru
|
| 262 |
+
|
| 263 |
+
# recast vanilla as real
|
| 264 |
+
assert solve(sqrt((-x + 1)**2) < 1) == And(S.Zero < x, x < 2)
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def test_issue_5526():
|
| 268 |
+
assert reduce_inequalities(0 <=
|
| 269 |
+
x + Integral(y**2, (y, 1, 3)) - 1, [x]) == \
|
| 270 |
+
(x >= -Integral(y**2, (y, 1, 3)) + 1)
|
| 271 |
+
f = Function('f')
|
| 272 |
+
e = Sum(f(x), (x, 1, 3))
|
| 273 |
+
assert reduce_inequalities(0 <= x + e + y**2, [x]) == \
|
| 274 |
+
(x >= -y**2 - Sum(f(x), (x, 1, 3)))
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
def test_solve_univariate_inequality():
|
| 278 |
+
assert isolve(x**2 >= 4, x, relational=False) == Union(Interval(-oo, -2),
|
| 279 |
+
Interval(2, oo))
|
| 280 |
+
assert isolve(x**2 >= 4, x) == Or(And(Le(2, x), Lt(x, oo)), And(Le(x, -2),
|
| 281 |
+
Lt(-oo, x)))
|
| 282 |
+
assert isolve((x - 1)*(x - 2)*(x - 3) >= 0, x, relational=False) == \
|
| 283 |
+
Union(Interval(1, 2), Interval(3, oo))
|
| 284 |
+
assert isolve((x - 1)*(x - 2)*(x - 3) >= 0, x) == \
|
| 285 |
+
Or(And(Le(1, x), Le(x, 2)), And(Le(3, x), Lt(x, oo)))
|
| 286 |
+
assert isolve((x - 1)*(x - 2)*(x - 4) < 0, x, domain = FiniteSet(0, 3)) == \
|
| 287 |
+
Or(Eq(x, 0), Eq(x, 3))
|
| 288 |
+
# issue 2785:
|
| 289 |
+
assert isolve(x**3 - 2*x - 1 > 0, x, relational=False) == \
|
| 290 |
+
Union(Interval(-1, -sqrt(5)/2 + S.Half, True, True),
|
| 291 |
+
Interval(S.Half + sqrt(5)/2, oo, True, True))
|
| 292 |
+
# issue 2794:
|
| 293 |
+
assert isolve(x**3 - x**2 + x - 1 > 0, x, relational=False) == \
|
| 294 |
+
Interval(1, oo, True)
|
| 295 |
+
#issue 13105
|
| 296 |
+
assert isolve((x + I)*(x + 2*I) < 0, x) == Eq(x, 0)
|
| 297 |
+
assert isolve(((x - 1)*(x - 2) + I)*((x - 1)*(x - 2) + 2*I) < 0, x) == Or(Eq(x, 1), Eq(x, 2))
|
| 298 |
+
assert isolve((((x - 1)*(x - 2) + I)*((x - 1)*(x - 2) + 2*I))/(x - 2) > 0, x) == Eq(x, 1)
|
| 299 |
+
raises (ValueError, lambda: isolve((x**2 - 3*x*I + 2)/x < 0, x))
|
| 300 |
+
|
| 301 |
+
# numerical testing in valid() is needed
|
| 302 |
+
assert isolve(x**7 - x - 2 > 0, x) == \
|
| 303 |
+
And(rootof(x**7 - x - 2, 0) < x, x < oo)
|
| 304 |
+
|
| 305 |
+
# handle numerator and denominator; although these would be handled as
|
| 306 |
+
# rational inequalities, these test confirm that the right thing is done
|
| 307 |
+
# when the domain is EX (e.g. when 2 is replaced with sqrt(2))
|
| 308 |
+
assert isolve(1/(x - 2) > 0, x) == And(S(2) < x, x < oo)
|
| 309 |
+
den = ((x - 1)*(x - 2)).expand()
|
| 310 |
+
assert isolve((x - 1)/den <= 0, x) == \
|
| 311 |
+
(x > -oo) & (x < 2) & Ne(x, 1)
|
| 312 |
+
|
| 313 |
+
n = Dummy('n')
|
| 314 |
+
raises(NotImplementedError, lambda: isolve(Abs(x) <= n, x, relational=False))
|
| 315 |
+
c1 = Dummy("c1", positive=True)
|
| 316 |
+
raises(NotImplementedError, lambda: isolve(n/c1 < 0, c1))
|
| 317 |
+
n = Dummy('n', negative=True)
|
| 318 |
+
assert isolve(n/c1 > -2, c1) == (-n/2 < c1)
|
| 319 |
+
assert isolve(n/c1 < 0, c1) == True
|
| 320 |
+
assert isolve(n/c1 > 0, c1) == False
|
| 321 |
+
|
| 322 |
+
zero = cos(1)**2 + sin(1)**2 - 1
|
| 323 |
+
raises(NotImplementedError, lambda: isolve(x**2 < zero, x))
|
| 324 |
+
raises(NotImplementedError, lambda: isolve(
|
| 325 |
+
x**2 < zero*I, x))
|
| 326 |
+
raises(NotImplementedError, lambda: isolve(1/(x - y) < 2, x))
|
| 327 |
+
raises(NotImplementedError, lambda: isolve(1/(x - y) < 0, x))
|
| 328 |
+
raises(TypeError, lambda: isolve(x - I < 0, x))
|
| 329 |
+
|
| 330 |
+
zero = x**2 + x - x*(x + 1)
|
| 331 |
+
assert isolve(zero < 0, x, relational=False) is S.EmptySet
|
| 332 |
+
assert isolve(zero <= 0, x, relational=False) is S.Reals
|
| 333 |
+
|
| 334 |
+
# make sure iter_solutions gets a default value
|
| 335 |
+
raises(NotImplementedError, lambda: isolve(
|
| 336 |
+
Eq(cos(x)**2 + sin(x)**2, 1), x))
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
def test_trig_inequalities():
|
| 340 |
+
# all the inequalities are solved in a periodic interval.
|
| 341 |
+
assert isolve(sin(x) < S.Half, x, relational=False) == \
|
| 342 |
+
Union(Interval(0, pi/6, False, True), Interval.open(pi*Rational(5, 6), 2*pi))
|
| 343 |
+
assert isolve(sin(x) > S.Half, x, relational=False) == \
|
| 344 |
+
Interval(pi/6, pi*Rational(5, 6), True, True)
|
| 345 |
+
assert isolve(cos(x) < S.Zero, x, relational=False) == \
|
| 346 |
+
Interval(pi/2, pi*Rational(3, 2), True, True)
|
| 347 |
+
assert isolve(cos(x) >= S.Zero, x, relational=False) == \
|
| 348 |
+
Union(Interval(0, pi/2), Interval.Ropen(pi*Rational(3, 2), 2*pi))
|
| 349 |
+
|
| 350 |
+
assert isolve(tan(x) < S.One, x, relational=False) == \
|
| 351 |
+
Union(Interval.Ropen(0, pi/4), Interval.open(pi/2, pi))
|
| 352 |
+
|
| 353 |
+
assert isolve(sin(x) <= S.Zero, x, relational=False) == \
|
| 354 |
+
Union(FiniteSet(S.Zero), Interval.Ropen(pi, 2*pi))
|
| 355 |
+
|
| 356 |
+
assert isolve(sin(x) <= S.One, x, relational=False) == S.Reals
|
| 357 |
+
assert isolve(cos(x) < S(-2), x, relational=False) == S.EmptySet
|
| 358 |
+
assert isolve(sin(x) >= S.NegativeOne, x, relational=False) == S.Reals
|
| 359 |
+
assert isolve(cos(x) > S.One, x, relational=False) == S.EmptySet
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
def test_issue_9954():
|
| 363 |
+
assert isolve(x**2 >= 0, x, relational=False) == S.Reals
|
| 364 |
+
assert isolve(x**2 >= 0, x, relational=True) == S.Reals.as_relational(x)
|
| 365 |
+
assert isolve(x**2 < 0, x, relational=False) == S.EmptySet
|
| 366 |
+
assert isolve(x**2 < 0, x, relational=True) == S.EmptySet.as_relational(x)
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
@XFAIL
|
| 370 |
+
def test_slow_general_univariate():
|
| 371 |
+
r = rootof(x**5 - x**2 + 1, 0)
|
| 372 |
+
assert solve(sqrt(x) + 1/root(x, 3) > 1) == \
|
| 373 |
+
Or(And(0 < x, x < r**6), And(r**6 < x, x < oo))
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
def test_issue_8545():
|
| 377 |
+
eq = 1 - x - abs(1 - x)
|
| 378 |
+
ans = And(Lt(1, x), Lt(x, oo))
|
| 379 |
+
assert reduce_abs_inequality(eq, '<', x) == ans
|
| 380 |
+
eq = 1 - x - sqrt((1 - x)**2)
|
| 381 |
+
assert reduce_inequalities(eq < 0) == ans
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
def test_issue_8974():
|
| 385 |
+
assert isolve(-oo < x, x) == And(-oo < x, x < oo)
|
| 386 |
+
assert isolve(oo > x, x) == And(-oo < x, x < oo)
|
| 387 |
+
|
| 388 |
+
|
| 389 |
+
def test_issue_10198():
|
| 390 |
+
assert reduce_inequalities(
|
| 391 |
+
-1 + 1/abs(1/x - 1) < 0) == (x > -oo) & (x < S(1)/2) & Ne(x, 0)
|
| 392 |
+
|
| 393 |
+
assert reduce_inequalities(abs(1/sqrt(x)) - 1, x) == Eq(x, 1)
|
| 394 |
+
assert reduce_abs_inequality(-3 + 1/abs(1 - 1/x), '<', x) == \
|
| 395 |
+
Or(And(-oo < x, x < 0),
|
| 396 |
+
And(S.Zero < x, x < Rational(3, 4)), And(Rational(3, 2) < x, x < oo))
|
| 397 |
+
raises(ValueError,lambda: reduce_abs_inequality(-3 + 1/abs(
|
| 398 |
+
1 - 1/sqrt(x)), '<', x))
|
| 399 |
+
|
| 400 |
+
|
| 401 |
+
def test_issue_10047():
|
| 402 |
+
# issue 10047: this must remain an inequality, not True, since if x
|
| 403 |
+
# is not real the inequality is invalid
|
| 404 |
+
# assert solve(sin(x) < 2) == (x <= oo)
|
| 405 |
+
|
| 406 |
+
# with PR 16956, (x <= oo) autoevaluates when x is extended_real
|
| 407 |
+
# which is assumed in the current implementation of inequality solvers
|
| 408 |
+
assert solve(sin(x) < 2) == True
|
| 409 |
+
assert solveset(sin(x) < 2, domain=S.Reals) == S.Reals
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
def test_issue_10268():
|
| 413 |
+
assert solve(log(x) < 1000) == And(S.Zero < x, x < exp(1000))
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
@XFAIL
|
| 417 |
+
def test_isolve_Sets():
|
| 418 |
+
n = Dummy('n')
|
| 419 |
+
assert isolve(Abs(x) <= n, x, relational=False) == \
|
| 420 |
+
Piecewise((S.EmptySet, n < 0), (Interval(-n, n), True))
|
| 421 |
+
|
| 422 |
+
|
| 423 |
+
def test_integer_domain_relational_isolve():
|
| 424 |
+
|
| 425 |
+
dom = FiniteSet(0, 3)
|
| 426 |
+
x = Symbol('x',zero=False)
|
| 427 |
+
assert isolve((x - 1)*(x - 2)*(x - 4) < 0, x, domain=dom) == Eq(x, 3)
|
| 428 |
+
|
| 429 |
+
x = Symbol('x')
|
| 430 |
+
assert isolve(x + 2 < 0, x, domain=S.Integers) == \
|
| 431 |
+
(x <= -3) & (x > -oo) & Eq(Mod(x, 1), 0)
|
| 432 |
+
assert isolve(2 * x + 3 > 0, x, domain=S.Integers) == \
|
| 433 |
+
(x >= -1) & (x < oo) & Eq(Mod(x, 1), 0)
|
| 434 |
+
assert isolve((x ** 2 + 3 * x - 2) < 0, x, domain=S.Integers) == \
|
| 435 |
+
(x >= -3) & (x <= 0) & Eq(Mod(x, 1), 0)
|
| 436 |
+
assert isolve((x ** 2 + 3 * x - 2) > 0, x, domain=S.Integers) == \
|
| 437 |
+
((x >= 1) & (x < oo) & Eq(Mod(x, 1), 0)) | (
|
| 438 |
+
(x <= -4) & (x > -oo) & Eq(Mod(x, 1), 0))
|
| 439 |
+
|
| 440 |
+
|
| 441 |
+
def test_issue_10671_12466():
|
| 442 |
+
assert solveset(sin(y), y, Interval(0, pi)) == FiniteSet(0, pi)
|
| 443 |
+
i = Interval(1, 10)
|
| 444 |
+
assert solveset((1/x).diff(x) < 0, x, i) == i
|
| 445 |
+
assert solveset((log(x - 6)/x) <= 0, x, S.Reals) == \
|
| 446 |
+
Interval.Lopen(6, 7)
|
| 447 |
+
|
| 448 |
+
|
| 449 |
+
def test__solve_inequality():
|
| 450 |
+
for op in (Gt, Lt, Le, Ge, Eq, Ne):
|
| 451 |
+
assert _solve_inequality(op(x, 1), x).lhs == x
|
| 452 |
+
assert _solve_inequality(op(S.One, x), x).lhs == x
|
| 453 |
+
# don't get tricked by symbol on right: solve it
|
| 454 |
+
assert _solve_inequality(Eq(2*x - 1, x), x) == Eq(x, 1)
|
| 455 |
+
ie = Eq(S.One, y)
|
| 456 |
+
assert _solve_inequality(ie, x) == ie
|
| 457 |
+
for fx in (x**2, exp(x), sin(x) + cos(x), x*(1 + x)):
|
| 458 |
+
for c in (0, 1):
|
| 459 |
+
e = 2*fx - c > 0
|
| 460 |
+
assert _solve_inequality(e, x, linear=True) == (
|
| 461 |
+
fx > c/S(2))
|
| 462 |
+
assert _solve_inequality(2*x**2 + 2*x - 1 < 0, x, linear=True) == (
|
| 463 |
+
x*(x + 1) < S.Half)
|
| 464 |
+
assert _solve_inequality(Eq(x*y, 1), x) == Eq(x*y, 1)
|
| 465 |
+
nz = Symbol('nz', nonzero=True)
|
| 466 |
+
assert _solve_inequality(Eq(x*nz, 1), x) == Eq(x, 1/nz)
|
| 467 |
+
assert _solve_inequality(x*nz < 1, x) == (x*nz < 1)
|
| 468 |
+
a = Symbol('a', positive=True)
|
| 469 |
+
assert _solve_inequality(a/x > 1, x) == (S.Zero < x) & (x < a)
|
| 470 |
+
assert _solve_inequality(a/x > 1, x, linear=True) == (1/x > 1/a)
|
| 471 |
+
# make sure to include conditions under which solution is valid
|
| 472 |
+
e = Eq(1 - x, x*(1/x - 1))
|
| 473 |
+
assert _solve_inequality(e, x) == Ne(x, 0)
|
| 474 |
+
assert _solve_inequality(x < x*(1/x - 1), x) == (x < S.Half) & Ne(x, 0)
|
| 475 |
+
|
| 476 |
+
|
| 477 |
+
def test__pt():
|
| 478 |
+
from sympy.solvers.inequalities import _pt
|
| 479 |
+
assert _pt(-oo, oo) == 0
|
| 480 |
+
assert _pt(S.One, S(3)) == 2
|
| 481 |
+
assert _pt(S.One, oo) == _pt(oo, S.One) == 2
|
| 482 |
+
assert _pt(S.One, -oo) == _pt(-oo, S.One) == S.Half
|
| 483 |
+
assert _pt(S.NegativeOne, oo) == _pt(oo, S.NegativeOne) == Rational(-1, 2)
|
| 484 |
+
assert _pt(S.NegativeOne, -oo) == _pt(-oo, S.NegativeOne) == -2
|
| 485 |
+
assert _pt(x, oo) == _pt(oo, x) == x + 1
|
| 486 |
+
assert _pt(x, -oo) == _pt(-oo, x) == x - 1
|
| 487 |
+
raises(ValueError, lambda: _pt(Dummy('i', infinite=True), S.One))
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
def test_issue_25697():
|
| 491 |
+
assert _solve_inequality(log(x, 3) <= 2, x) == (x <= 9) & (S.Zero < x)
|
| 492 |
+
|
| 493 |
+
|
| 494 |
+
def test_issue_25738():
|
| 495 |
+
assert reduce_inequalities(3 < abs(x)
|
| 496 |
+
) == reduce_inequalities(pi < abs(x)).subs(pi, 3)
|
| 497 |
+
|
| 498 |
+
|
| 499 |
+
def test_issue_25983():
|
| 500 |
+
assert(reduce_inequalities(pi/Abs(x) <= 1) == ((pi <= x) & (x < oo)) | ((-oo < x) & (x <= -pi)))
|
evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/tests/test_numeric.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.function import nfloat
|
| 2 |
+
from sympy.core.numbers import (Float, I, Rational, pi)
|
| 3 |
+
from sympy.core.relational import Eq
|
| 4 |
+
from sympy.core.symbol import (Symbol, symbols)
|
| 5 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 6 |
+
from sympy.functions.elementary.piecewise import Piecewise
|
| 7 |
+
from sympy.functions.elementary.trigonometric import sin
|
| 8 |
+
from sympy.integrals.integrals import Integral
|
| 9 |
+
from sympy.matrices.dense import Matrix
|
| 10 |
+
from mpmath import mnorm, mpf
|
| 11 |
+
from sympy.solvers import nsolve
|
| 12 |
+
from sympy.utilities.lambdify import lambdify
|
| 13 |
+
from sympy.testing.pytest import raises, XFAIL
|
| 14 |
+
from sympy.utilities.decorator import conserve_mpmath_dps
|
| 15 |
+
|
| 16 |
+
@XFAIL
|
| 17 |
+
def test_nsolve_fail():
|
| 18 |
+
x = symbols('x')
|
| 19 |
+
# Sometimes it is better to use the numerator (issue 4829)
|
| 20 |
+
# but sometimes it is not (issue 11768) so leave this to
|
| 21 |
+
# the discretion of the user
|
| 22 |
+
ans = nsolve(x**2/(1 - x)/(1 - 2*x)**2 - 100, x, 0)
|
| 23 |
+
assert ans > 0.46 and ans < 0.47
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def test_nsolve_denominator():
|
| 27 |
+
x = symbols('x')
|
| 28 |
+
# Test that nsolve uses the full expression (numerator and denominator).
|
| 29 |
+
ans = nsolve((x**2 + 3*x + 2)/(x + 2), -2.1)
|
| 30 |
+
# The root -2 was divided out, so make sure we don't find it.
|
| 31 |
+
assert ans == -1.0
|
| 32 |
+
|
| 33 |
+
def test_nsolve():
|
| 34 |
+
# onedimensional
|
| 35 |
+
x = Symbol('x')
|
| 36 |
+
assert nsolve(sin(x), 2) - pi.evalf() < 1e-15
|
| 37 |
+
assert nsolve(Eq(2*x, 2), x, -10) == nsolve(2*x - 2, -10)
|
| 38 |
+
# Testing checks on number of inputs
|
| 39 |
+
raises(TypeError, lambda: nsolve(Eq(2*x, 2)))
|
| 40 |
+
raises(TypeError, lambda: nsolve(Eq(2*x, 2), x, 1, 2))
|
| 41 |
+
# multidimensional
|
| 42 |
+
x1 = Symbol('x1')
|
| 43 |
+
x2 = Symbol('x2')
|
| 44 |
+
f1 = 3 * x1**2 - 2 * x2**2 - 1
|
| 45 |
+
f2 = x1**2 - 2 * x1 + x2**2 + 2 * x2 - 8
|
| 46 |
+
f = Matrix((f1, f2)).T
|
| 47 |
+
F = lambdify((x1, x2), f.T, modules='mpmath')
|
| 48 |
+
for x0 in [(-1, 1), (1, -2), (4, 4), (-4, -4)]:
|
| 49 |
+
x = nsolve(f, (x1, x2), x0, tol=1.e-8)
|
| 50 |
+
assert mnorm(F(*x), 1) <= 1.e-10
|
| 51 |
+
# The Chinese mathematician Zhu Shijie was the very first to solve this
|
| 52 |
+
# nonlinear system 700 years ago (z was added to make it 3-dimensional)
|
| 53 |
+
x = Symbol('x')
|
| 54 |
+
y = Symbol('y')
|
| 55 |
+
z = Symbol('z')
|
| 56 |
+
f1 = -x + 2*y
|
| 57 |
+
f2 = (x**2 + x*(y**2 - 2) - 4*y) / (x + 4)
|
| 58 |
+
f3 = sqrt(x**2 + y**2)*z
|
| 59 |
+
f = Matrix((f1, f2, f3)).T
|
| 60 |
+
F = lambdify((x, y, z), f.T, modules='mpmath')
|
| 61 |
+
|
| 62 |
+
def getroot(x0):
|
| 63 |
+
root = nsolve(f, (x, y, z), x0)
|
| 64 |
+
assert mnorm(F(*root), 1) <= 1.e-8
|
| 65 |
+
return root
|
| 66 |
+
assert list(map(round, getroot((1, 1, 1)))) == [2, 1, 0]
|
| 67 |
+
assert nsolve([Eq(
|
| 68 |
+
f1, 0), Eq(f2, 0), Eq(f3, 0)], [x, y, z], (1, 1, 1)) # just see that it works
|
| 69 |
+
a = Symbol('a')
|
| 70 |
+
assert abs(nsolve(1/(0.001 + a)**3 - 6/(0.9 - a)**3, a, 0.3) -
|
| 71 |
+
mpf('0.31883011387318591')) < 1e-15
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def test_issue_6408():
|
| 75 |
+
x = Symbol('x')
|
| 76 |
+
assert nsolve(Piecewise((x, x < 1), (x**2, True)), x, 2) == 0
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def test_issue_6408_integral():
|
| 80 |
+
x, y = symbols('x y')
|
| 81 |
+
assert nsolve(Integral(x*y, (x, 0, 5)), y, 2) == 0
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
@conserve_mpmath_dps
|
| 85 |
+
def test_increased_dps():
|
| 86 |
+
# Issue 8564
|
| 87 |
+
import mpmath
|
| 88 |
+
mpmath.mp.dps = 128
|
| 89 |
+
x = Symbol('x')
|
| 90 |
+
e1 = x**2 - pi
|
| 91 |
+
q = nsolve(e1, x, 3.0)
|
| 92 |
+
|
| 93 |
+
assert abs(sqrt(pi).evalf(128) - q) < 1e-128
|
| 94 |
+
|
| 95 |
+
def test_nsolve_precision():
|
| 96 |
+
x, y = symbols('x y')
|
| 97 |
+
sol = nsolve(x**2 - pi, x, 3, prec=128)
|
| 98 |
+
assert abs(sqrt(pi).evalf(128) - sol) < 1e-128
|
| 99 |
+
assert isinstance(sol, Float)
|
| 100 |
+
|
| 101 |
+
sols = nsolve((y**2 - x, x**2 - pi), (x, y), (3, 3), prec=128)
|
| 102 |
+
assert isinstance(sols, Matrix)
|
| 103 |
+
assert sols.shape == (2, 1)
|
| 104 |
+
assert abs(sqrt(pi).evalf(128) - sols[0]) < 1e-128
|
| 105 |
+
assert abs(sqrt(sqrt(pi)).evalf(128) - sols[1]) < 1e-128
|
| 106 |
+
assert all(isinstance(i, Float) for i in sols)
|
| 107 |
+
|
| 108 |
+
def test_nsolve_complex():
|
| 109 |
+
x, y = symbols('x y')
|
| 110 |
+
|
| 111 |
+
assert nsolve(x**2 + 2, 1j) == sqrt(2.)*I
|
| 112 |
+
assert nsolve(x**2 + 2, I) == sqrt(2.)*I
|
| 113 |
+
|
| 114 |
+
assert nsolve([x**2 + 2, y**2 + 2], [x, y], [I, I]) == Matrix([sqrt(2.)*I, sqrt(2.)*I])
|
| 115 |
+
assert nsolve([x**2 + 2, y**2 + 2], [x, y], [I, I]) == Matrix([sqrt(2.)*I, sqrt(2.)*I])
|
| 116 |
+
|
| 117 |
+
def test_nsolve_dict_kwarg():
|
| 118 |
+
x, y = symbols('x y')
|
| 119 |
+
# one variable
|
| 120 |
+
assert nsolve(x**2 - 2, 1, dict = True) == \
|
| 121 |
+
[{x: sqrt(2.)}]
|
| 122 |
+
# one variable with complex solution
|
| 123 |
+
assert nsolve(x**2 + 2, I, dict = True) == \
|
| 124 |
+
[{x: sqrt(2.)*I}]
|
| 125 |
+
# two variables
|
| 126 |
+
assert nsolve([x**2 + y**2 - 5, x**2 - y**2 + 1], [x, y], [1, 1], dict = True) == \
|
| 127 |
+
[{x: sqrt(2.), y: sqrt(3.)}]
|
| 128 |
+
|
| 129 |
+
def test_nsolve_rational():
|
| 130 |
+
x = symbols('x')
|
| 131 |
+
assert nsolve(x - Rational(1, 3), 0, prec=100) == Rational(1, 3).evalf(100)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def test_issue_14950():
|
| 135 |
+
x = Matrix(symbols('t s'))
|
| 136 |
+
x0 = Matrix([17, 23])
|
| 137 |
+
eqn = x + x0
|
| 138 |
+
assert nsolve(eqn, x, x0) == nfloat(-x0)
|
| 139 |
+
assert nsolve(eqn.T, x.T, x0.T) == nfloat(-x0)
|
evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/tests/test_pde.py
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.function import (Derivative as D, Function)
|
| 2 |
+
from sympy.core.relational import Eq
|
| 3 |
+
from sympy.core.symbol import (Symbol, symbols)
|
| 4 |
+
from sympy.functions.elementary.exponential import (exp, log)
|
| 5 |
+
from sympy.functions.elementary.trigonometric import (cos, sin)
|
| 6 |
+
from sympy.core import S
|
| 7 |
+
from sympy.solvers.pde import (pde_separate, pde_separate_add, pde_separate_mul,
|
| 8 |
+
pdsolve, classify_pde, checkpdesol)
|
| 9 |
+
from sympy.testing.pytest import raises
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
a, b, c, x, y = symbols('a b c x y')
|
| 13 |
+
|
| 14 |
+
def test_pde_separate_add():
|
| 15 |
+
x, y, z, t = symbols("x,y,z,t")
|
| 16 |
+
F, T, X, Y, Z, u = map(Function, 'FTXYZu')
|
| 17 |
+
|
| 18 |
+
eq = Eq(D(u(x, t), x), D(u(x, t), t)*exp(u(x, t)))
|
| 19 |
+
res = pde_separate_add(eq, u(x, t), [X(x), T(t)])
|
| 20 |
+
assert res == [D(X(x), x)*exp(-X(x)), D(T(t), t)*exp(T(t))]
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def test_pde_separate():
|
| 24 |
+
x, y, z, t = symbols("x,y,z,t")
|
| 25 |
+
F, T, X, Y, Z, u = map(Function, 'FTXYZu')
|
| 26 |
+
|
| 27 |
+
eq = Eq(D(u(x, t), x), D(u(x, t), t)*exp(u(x, t)))
|
| 28 |
+
raises(ValueError, lambda: pde_separate(eq, u(x, t), [X(x), T(t)], 'div'))
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def test_pde_separate_mul():
|
| 32 |
+
x, y, z, t = symbols("x,y,z,t")
|
| 33 |
+
c = Symbol("C", real=True)
|
| 34 |
+
Phi = Function('Phi')
|
| 35 |
+
F, R, T, X, Y, Z, u = map(Function, 'FRTXYZu')
|
| 36 |
+
r, theta, z = symbols('r,theta,z')
|
| 37 |
+
|
| 38 |
+
# Something simple :)
|
| 39 |
+
eq = Eq(D(F(x, y, z), x) + D(F(x, y, z), y) + D(F(x, y, z), z), 0)
|
| 40 |
+
|
| 41 |
+
# Duplicate arguments in functions
|
| 42 |
+
raises(
|
| 43 |
+
ValueError, lambda: pde_separate_mul(eq, F(x, y, z), [X(x), u(z, z)]))
|
| 44 |
+
# Wrong number of arguments
|
| 45 |
+
raises(ValueError, lambda: pde_separate_mul(eq, F(x, y, z), [X(x), Y(y)]))
|
| 46 |
+
# Wrong variables: [x, y] -> [x, z]
|
| 47 |
+
raises(
|
| 48 |
+
ValueError, lambda: pde_separate_mul(eq, F(x, y, z), [X(t), Y(x, y)]))
|
| 49 |
+
|
| 50 |
+
assert pde_separate_mul(eq, F(x, y, z), [Y(y), u(x, z)]) == \
|
| 51 |
+
[D(Y(y), y)/Y(y), -D(u(x, z), x)/u(x, z) - D(u(x, z), z)/u(x, z)]
|
| 52 |
+
assert pde_separate_mul(eq, F(x, y, z), [X(x), Y(y), Z(z)]) == \
|
| 53 |
+
[D(X(x), x)/X(x), -D(Z(z), z)/Z(z) - D(Y(y), y)/Y(y)]
|
| 54 |
+
|
| 55 |
+
# wave equation
|
| 56 |
+
wave = Eq(D(u(x, t), t, t), c**2*D(u(x, t), x, x))
|
| 57 |
+
res = pde_separate_mul(wave, u(x, t), [X(x), T(t)])
|
| 58 |
+
assert res == [D(X(x), x, x)/X(x), D(T(t), t, t)/(c**2*T(t))]
|
| 59 |
+
|
| 60 |
+
# Laplace equation in cylindrical coords
|
| 61 |
+
eq = Eq(1/r * D(Phi(r, theta, z), r) + D(Phi(r, theta, z), r, 2) +
|
| 62 |
+
1/r**2 * D(Phi(r, theta, z), theta, 2) + D(Phi(r, theta, z), z, 2), 0)
|
| 63 |
+
# Separate z
|
| 64 |
+
res = pde_separate_mul(eq, Phi(r, theta, z), [Z(z), u(theta, r)])
|
| 65 |
+
assert res == [D(Z(z), z, z)/Z(z),
|
| 66 |
+
-D(u(theta, r), r, r)/u(theta, r) -
|
| 67 |
+
D(u(theta, r), r)/(r*u(theta, r)) -
|
| 68 |
+
D(u(theta, r), theta, theta)/(r**2*u(theta, r))]
|
| 69 |
+
# Lets use the result to create a new equation...
|
| 70 |
+
eq = Eq(res[1], c)
|
| 71 |
+
# ...and separate theta...
|
| 72 |
+
res = pde_separate_mul(eq, u(theta, r), [T(theta), R(r)])
|
| 73 |
+
assert res == [D(T(theta), theta, theta)/T(theta),
|
| 74 |
+
-r*D(R(r), r)/R(r) - r**2*D(R(r), r, r)/R(r) - c*r**2]
|
| 75 |
+
# ...or r...
|
| 76 |
+
res = pde_separate_mul(eq, u(theta, r), [R(r), T(theta)])
|
| 77 |
+
assert res == [r*D(R(r), r)/R(r) + r**2*D(R(r), r, r)/R(r) + c*r**2,
|
| 78 |
+
-D(T(theta), theta, theta)/T(theta)]
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def test_issue_11726():
|
| 82 |
+
x, t = symbols("x t")
|
| 83 |
+
f = symbols("f", cls=Function)
|
| 84 |
+
X, T = symbols("X T", cls=Function)
|
| 85 |
+
|
| 86 |
+
u = f(x, t)
|
| 87 |
+
eq = u.diff(x, 2) - u.diff(t, 2)
|
| 88 |
+
res = pde_separate(eq, u, [T(x), X(t)])
|
| 89 |
+
assert res == [D(T(x), x, x)/T(x),D(X(t), t, t)/X(t)]
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def test_pde_classify():
|
| 93 |
+
# When more number of hints are added, add tests for classifying here.
|
| 94 |
+
f = Function('f')
|
| 95 |
+
eq1 = a*f(x,y) + b*f(x,y).diff(x) + c*f(x,y).diff(y)
|
| 96 |
+
eq2 = 3*f(x,y) + 2*f(x,y).diff(x) + f(x,y).diff(y)
|
| 97 |
+
eq3 = a*f(x,y) + b*f(x,y).diff(x) + 2*f(x,y).diff(y)
|
| 98 |
+
eq4 = x*f(x,y) + f(x,y).diff(x) + 3*f(x,y).diff(y)
|
| 99 |
+
eq5 = x**2*f(x,y) + x*f(x,y).diff(x) + x*y*f(x,y).diff(y)
|
| 100 |
+
eq6 = y*x**2*f(x,y) + y*f(x,y).diff(x) + f(x,y).diff(y)
|
| 101 |
+
for eq in [eq1, eq2, eq3]:
|
| 102 |
+
assert classify_pde(eq) == ('1st_linear_constant_coeff_homogeneous',)
|
| 103 |
+
for eq in [eq4, eq5, eq6]:
|
| 104 |
+
assert classify_pde(eq) == ('1st_linear_variable_coeff',)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def test_checkpdesol():
|
| 108 |
+
f, F = map(Function, ['f', 'F'])
|
| 109 |
+
eq1 = a*f(x,y) + b*f(x,y).diff(x) + c*f(x,y).diff(y)
|
| 110 |
+
eq2 = 3*f(x,y) + 2*f(x,y).diff(x) + f(x,y).diff(y)
|
| 111 |
+
eq3 = a*f(x,y) + b*f(x,y).diff(x) + 2*f(x,y).diff(y)
|
| 112 |
+
for eq in [eq1, eq2, eq3]:
|
| 113 |
+
assert checkpdesol(eq, pdsolve(eq))[0]
|
| 114 |
+
eq4 = x*f(x,y) + f(x,y).diff(x) + 3*f(x,y).diff(y)
|
| 115 |
+
eq5 = 2*f(x,y) + 1*f(x,y).diff(x) + 3*f(x,y).diff(y)
|
| 116 |
+
eq6 = f(x,y) + 1*f(x,y).diff(x) + 3*f(x,y).diff(y)
|
| 117 |
+
assert checkpdesol(eq4, [pdsolve(eq5), pdsolve(eq6)]) == [
|
| 118 |
+
(False, (x - 2)*F(3*x - y)*exp(-x/S(5) - 3*y/S(5))),
|
| 119 |
+
(False, (x - 1)*F(3*x - y)*exp(-x/S(10) - 3*y/S(10)))]
|
| 120 |
+
for eq in [eq4, eq5, eq6]:
|
| 121 |
+
assert checkpdesol(eq, pdsolve(eq))[0]
|
| 122 |
+
sol = pdsolve(eq4)
|
| 123 |
+
sol4 = Eq(sol.lhs - sol.rhs, 0)
|
| 124 |
+
raises(NotImplementedError, lambda:
|
| 125 |
+
checkpdesol(eq4, sol4, solve_for_func=False))
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def test_solvefun():
|
| 129 |
+
f, F, G, H = map(Function, ['f', 'F', 'G', 'H'])
|
| 130 |
+
eq1 = f(x,y) + f(x,y).diff(x) + f(x,y).diff(y)
|
| 131 |
+
assert pdsolve(eq1) == Eq(f(x, y), F(x - y)*exp(-x/2 - y/2))
|
| 132 |
+
assert pdsolve(eq1, solvefun=G) == Eq(f(x, y), G(x - y)*exp(-x/2 - y/2))
|
| 133 |
+
assert pdsolve(eq1, solvefun=H) == Eq(f(x, y), H(x - y)*exp(-x/2 - y/2))
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def test_pde_1st_linear_constant_coeff_homogeneous():
|
| 137 |
+
f, F = map(Function, ['f', 'F'])
|
| 138 |
+
u = f(x, y)
|
| 139 |
+
eq = 2*u + u.diff(x) + u.diff(y)
|
| 140 |
+
assert classify_pde(eq) == ('1st_linear_constant_coeff_homogeneous',)
|
| 141 |
+
sol = pdsolve(eq)
|
| 142 |
+
assert sol == Eq(u, F(x - y)*exp(-x - y))
|
| 143 |
+
assert checkpdesol(eq, sol)[0]
|
| 144 |
+
|
| 145 |
+
eq = 4 + (3*u.diff(x)/u) + (2*u.diff(y)/u)
|
| 146 |
+
assert classify_pde(eq) == ('1st_linear_constant_coeff_homogeneous',)
|
| 147 |
+
sol = pdsolve(eq)
|
| 148 |
+
assert sol == Eq(u, F(2*x - 3*y)*exp(-S(12)*x/13 - S(8)*y/13))
|
| 149 |
+
assert checkpdesol(eq, sol)[0]
|
| 150 |
+
|
| 151 |
+
eq = u + (6*u.diff(x)) + (7*u.diff(y))
|
| 152 |
+
assert classify_pde(eq) == ('1st_linear_constant_coeff_homogeneous',)
|
| 153 |
+
sol = pdsolve(eq)
|
| 154 |
+
assert sol == Eq(u, F(7*x - 6*y)*exp(-6*x/S(85) - 7*y/S(85)))
|
| 155 |
+
assert checkpdesol(eq, sol)[0]
|
| 156 |
+
|
| 157 |
+
eq = a*u + b*u.diff(x) + c*u.diff(y)
|
| 158 |
+
sol = pdsolve(eq)
|
| 159 |
+
assert checkpdesol(eq, sol)[0]
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def test_pde_1st_linear_constant_coeff():
|
| 163 |
+
f, F = map(Function, ['f', 'F'])
|
| 164 |
+
u = f(x,y)
|
| 165 |
+
eq = -2*u.diff(x) + 4*u.diff(y) + 5*u - exp(x + 3*y)
|
| 166 |
+
sol = pdsolve(eq)
|
| 167 |
+
assert sol == Eq(f(x,y),
|
| 168 |
+
(F(4*x + 2*y)*exp(x/2) + exp(x + 4*y)/15)*exp(-y))
|
| 169 |
+
assert classify_pde(eq) == ('1st_linear_constant_coeff',
|
| 170 |
+
'1st_linear_constant_coeff_Integral')
|
| 171 |
+
assert checkpdesol(eq, sol)[0]
|
| 172 |
+
|
| 173 |
+
eq = (u.diff(x)/u) + (u.diff(y)/u) + 1 - (exp(x + y)/u)
|
| 174 |
+
sol = pdsolve(eq)
|
| 175 |
+
assert sol == Eq(f(x, y), F(x - y)*exp(-x/2 - y/2) + exp(x + y)/3)
|
| 176 |
+
assert classify_pde(eq) == ('1st_linear_constant_coeff',
|
| 177 |
+
'1st_linear_constant_coeff_Integral')
|
| 178 |
+
assert checkpdesol(eq, sol)[0]
|
| 179 |
+
|
| 180 |
+
eq = 2*u + -u.diff(x) + 3*u.diff(y) + sin(x)
|
| 181 |
+
sol = pdsolve(eq)
|
| 182 |
+
assert sol == Eq(f(x, y),
|
| 183 |
+
F(3*x + y)*exp(x/5 - 3*y/5) - 2*sin(x)/5 - cos(x)/5)
|
| 184 |
+
assert classify_pde(eq) == ('1st_linear_constant_coeff',
|
| 185 |
+
'1st_linear_constant_coeff_Integral')
|
| 186 |
+
assert checkpdesol(eq, sol)[0]
|
| 187 |
+
|
| 188 |
+
eq = u + u.diff(x) + u.diff(y) + x*y
|
| 189 |
+
sol = pdsolve(eq)
|
| 190 |
+
assert sol.expand() == Eq(f(x, y),
|
| 191 |
+
x + y + (x - y)**2/4 - (x + y)**2/4 + F(x - y)*exp(-x/2 - y/2) - 2).expand()
|
| 192 |
+
assert classify_pde(eq) == ('1st_linear_constant_coeff',
|
| 193 |
+
'1st_linear_constant_coeff_Integral')
|
| 194 |
+
assert checkpdesol(eq, sol)[0]
|
| 195 |
+
eq = u + u.diff(x) + u.diff(y) + log(x)
|
| 196 |
+
assert classify_pde(eq) == ('1st_linear_constant_coeff',
|
| 197 |
+
'1st_linear_constant_coeff_Integral')
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def test_pdsolve_all():
|
| 201 |
+
f, F = map(Function, ['f', 'F'])
|
| 202 |
+
u = f(x,y)
|
| 203 |
+
eq = u + u.diff(x) + u.diff(y) + x**2*y
|
| 204 |
+
sol = pdsolve(eq, hint = 'all')
|
| 205 |
+
keys = ['1st_linear_constant_coeff',
|
| 206 |
+
'1st_linear_constant_coeff_Integral', 'default', 'order']
|
| 207 |
+
assert sorted(sol.keys()) == keys
|
| 208 |
+
assert sol['order'] == 1
|
| 209 |
+
assert sol['default'] == '1st_linear_constant_coeff'
|
| 210 |
+
assert sol['1st_linear_constant_coeff'].expand() == Eq(f(x, y),
|
| 211 |
+
-x**2*y + x**2 + 2*x*y - 4*x - 2*y + F(x - y)*exp(-x/2 - y/2) + 6).expand()
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def test_pdsolve_variable_coeff():
|
| 215 |
+
f, F = map(Function, ['f', 'F'])
|
| 216 |
+
u = f(x, y)
|
| 217 |
+
eq = x*(u.diff(x)) - y*(u.diff(y)) + y**2*u - y**2
|
| 218 |
+
sol = pdsolve(eq, hint="1st_linear_variable_coeff")
|
| 219 |
+
assert sol == Eq(u, F(x*y)*exp(y**2/2) + 1)
|
| 220 |
+
assert checkpdesol(eq, sol)[0]
|
| 221 |
+
|
| 222 |
+
eq = x**2*u + x*u.diff(x) + x*y*u.diff(y)
|
| 223 |
+
sol = pdsolve(eq, hint='1st_linear_variable_coeff')
|
| 224 |
+
assert sol == Eq(u, F(y*exp(-x))*exp(-x**2/2))
|
| 225 |
+
assert checkpdesol(eq, sol)[0]
|
| 226 |
+
|
| 227 |
+
eq = y*x**2*u + y*u.diff(x) + u.diff(y)
|
| 228 |
+
sol = pdsolve(eq, hint='1st_linear_variable_coeff')
|
| 229 |
+
assert sol == Eq(u, F(-2*x + y**2)*exp(-x**3/3))
|
| 230 |
+
assert checkpdesol(eq, sol)[0]
|
| 231 |
+
|
| 232 |
+
eq = exp(x)**2*(u.diff(x)) + y
|
| 233 |
+
sol = pdsolve(eq, hint='1st_linear_variable_coeff')
|
| 234 |
+
assert sol == Eq(u, y*exp(-2*x)/2 + F(y))
|
| 235 |
+
assert checkpdesol(eq, sol)[0]
|
| 236 |
+
|
| 237 |
+
eq = exp(2*x)*(u.di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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Tests for solvers of systems of polynomial equations. """
|
| 2 |
+
from sympy.core.numbers import (I, Integer, Rational)
|
| 3 |
+
from sympy.core.singleton import S
|
| 4 |
+
from sympy.core.symbol import symbols
|
| 5 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 6 |
+
from sympy.polys.domains.rationalfield import QQ
|
| 7 |
+
from sympy.polys.polyerrors import UnsolvableFactorError
|
| 8 |
+
from sympy.polys.polyoptions import Options
|
| 9 |
+
from sympy.polys.polytools import Poly
|
| 10 |
+
from sympy.solvers.solvers import solve
|
| 11 |
+
from sympy.utilities.iterables import flatten
|
| 12 |
+
from sympy.abc import x, y, z
|
| 13 |
+
from sympy.polys import PolynomialError
|
| 14 |
+
from sympy.solvers.polysys import (solve_poly_system,
|
| 15 |
+
solve_triangulated,
|
| 16 |
+
solve_biquadratic, SolveFailed,
|
| 17 |
+
solve_generic)
|
| 18 |
+
from sympy.polys.polytools import parallel_poly_from_expr
|
| 19 |
+
from sympy.testing.pytest import raises
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def test_solve_poly_system():
|
| 23 |
+
assert solve_poly_system([x - 1], x) == [(S.One,)]
|
| 24 |
+
|
| 25 |
+
assert solve_poly_system([y - x, y - x - 1], x, y) is None
|
| 26 |
+
|
| 27 |
+
assert solve_poly_system([y - x**2, y + x**2], x, y) == [(S.Zero, S.Zero)]
|
| 28 |
+
|
| 29 |
+
assert solve_poly_system([2*x - 3, y*Rational(3, 2) - 2*x, z - 5*y], x, y, z) == \
|
| 30 |
+
[(Rational(3, 2), Integer(2), Integer(10))]
|
| 31 |
+
|
| 32 |
+
assert solve_poly_system([x*y - 2*y, 2*y**2 - x**2], x, y) == \
|
| 33 |
+
[(0, 0), (2, -sqrt(2)), (2, sqrt(2))]
|
| 34 |
+
|
| 35 |
+
assert solve_poly_system([y - x**2, y + x**2 + 1], x, y) == \
|
| 36 |
+
[(-I*sqrt(S.Half), Rational(-1, 2)), (I*sqrt(S.Half), Rational(-1, 2))]
|
| 37 |
+
|
| 38 |
+
f_1 = x**2 + y + z - 1
|
| 39 |
+
f_2 = x + y**2 + z - 1
|
| 40 |
+
f_3 = x + y + z**2 - 1
|
| 41 |
+
|
| 42 |
+
a, b = sqrt(2) - 1, -sqrt(2) - 1
|
| 43 |
+
|
| 44 |
+
assert solve_poly_system([f_1, f_2, f_3], x, y, z) == \
|
| 45 |
+
[(0, 0, 1), (0, 1, 0), (1, 0, 0), (a, a, a), (b, b, b)]
|
| 46 |
+
|
| 47 |
+
solution = [(1, -1), (1, 1)]
|
| 48 |
+
|
| 49 |
+
assert solve_poly_system([Poly(x**2 - y**2), Poly(x - 1)]) == solution
|
| 50 |
+
assert solve_poly_system([x**2 - y**2, x - 1], x, y) == solution
|
| 51 |
+
assert solve_poly_system([x**2 - y**2, x - 1]) == solution
|
| 52 |
+
|
| 53 |
+
assert solve_poly_system(
|
| 54 |
+
[x + x*y - 3, y + x*y - 4], x, y) == [(-3, -2), (1, 2)]
|
| 55 |
+
|
| 56 |
+
raises(NotImplementedError, lambda: solve_poly_system([x**3 - y**3], x, y))
|
| 57 |
+
raises(NotImplementedError, lambda: solve_poly_system(
|
| 58 |
+
[z, -2*x*y**2 + x + y**2*z, y**2*(-z - 4) + 2]))
|
| 59 |
+
raises(PolynomialError, lambda: solve_poly_system([1/x], x))
|
| 60 |
+
|
| 61 |
+
raises(NotImplementedError, lambda: solve_poly_system(
|
| 62 |
+
[x-1,], (x, y)))
|
| 63 |
+
raises(NotImplementedError, lambda: solve_poly_system(
|
| 64 |
+
[y-1,], (x, y)))
|
| 65 |
+
|
| 66 |
+
# solve_poly_system should ideally construct solutions using
|
| 67 |
+
# CRootOf for the following four tests
|
| 68 |
+
assert solve_poly_system([x**5 - x + 1], [x], strict=False) == []
|
| 69 |
+
raises(UnsolvableFactorError, lambda: solve_poly_system(
|
| 70 |
+
[x**5 - x + 1], [x], strict=True))
|
| 71 |
+
|
| 72 |
+
assert solve_poly_system([(x - 1)*(x**5 - x + 1), y**2 - 1], [x, y],
|
| 73 |
+
strict=False) == [(1, -1), (1, 1)]
|
| 74 |
+
raises(UnsolvableFactorError,
|
| 75 |
+
lambda: solve_poly_system([(x - 1)*(x**5 - x + 1), y**2-1],
|
| 76 |
+
[x, y], strict=True))
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def test_solve_generic():
|
| 80 |
+
NewOption = Options((x, y), {'domain': 'ZZ'})
|
| 81 |
+
assert solve_generic([x**2 - 2*y**2, y**2 - y + 1], NewOption) == \
|
| 82 |
+
[(-sqrt(-1 - sqrt(3)*I), Rational(1, 2) - sqrt(3)*I/2),
|
| 83 |
+
(sqrt(-1 - sqrt(3)*I), Rational(1, 2) - sqrt(3)*I/2),
|
| 84 |
+
(-sqrt(-1 + sqrt(3)*I), Rational(1, 2) + sqrt(3)*I/2),
|
| 85 |
+
(sqrt(-1 + sqrt(3)*I), Rational(1, 2) + sqrt(3)*I/2)]
|
| 86 |
+
|
| 87 |
+
# solve_generic should ideally construct solutions using
|
| 88 |
+
# CRootOf for the following two tests
|
| 89 |
+
assert solve_generic(
|
| 90 |
+
[2*x - y, (y - 1)*(y**5 - y + 1)], NewOption, strict=False) == \
|
| 91 |
+
[(Rational(1, 2), 1)]
|
| 92 |
+
raises(UnsolvableFactorError, lambda: solve_generic(
|
| 93 |
+
[2*x - y, (y - 1)*(y**5 - y + 1)], NewOption, strict=True))
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def test_solve_biquadratic():
|
| 97 |
+
x0, y0, x1, y1, r = symbols('x0 y0 x1 y1 r')
|
| 98 |
+
|
| 99 |
+
f_1 = (x - 1)**2 + (y - 1)**2 - r**2
|
| 100 |
+
f_2 = (x - 2)**2 + (y - 2)**2 - r**2
|
| 101 |
+
s = sqrt(2*r**2 - 1)
|
| 102 |
+
a = (3 - s)/2
|
| 103 |
+
b = (3 + s)/2
|
| 104 |
+
assert solve_poly_system([f_1, f_2], x, y) == [(a, b), (b, a)]
|
| 105 |
+
|
| 106 |
+
f_1 = (x - 1)**2 + (y - 2)**2 - r**2
|
| 107 |
+
f_2 = (x - 1)**2 + (y - 1)**2 - r**2
|
| 108 |
+
|
| 109 |
+
assert solve_poly_system([f_1, f_2], x, y) == \
|
| 110 |
+
[(1 - sqrt((2*r - 1)*(2*r + 1))/2, Rational(3, 2)),
|
| 111 |
+
(1 + sqrt((2*r - 1)*(2*r + 1))/2, Rational(3, 2))]
|
| 112 |
+
|
| 113 |
+
query = lambda expr: expr.is_Pow and expr.exp is S.Half
|
| 114 |
+
|
| 115 |
+
f_1 = (x - 1 )**2 + (y - 2)**2 - r**2
|
| 116 |
+
f_2 = (x - x1)**2 + (y - 1)**2 - r**2
|
| 117 |
+
|
| 118 |
+
result = solve_poly_system([f_1, f_2], x, y)
|
| 119 |
+
|
| 120 |
+
assert len(result) == 2 and all(len(r) == 2 for r in result)
|
| 121 |
+
assert all(r.count(query) == 1 for r in flatten(result))
|
| 122 |
+
|
| 123 |
+
f_1 = (x - x0)**2 + (y - y0)**2 - r**2
|
| 124 |
+
f_2 = (x - x1)**2 + (y - y1)**2 - r**2
|
| 125 |
+
|
| 126 |
+
result = solve_poly_system([f_1, f_2], x, y)
|
| 127 |
+
|
| 128 |
+
assert len(result) == 2 and all(len(r) == 2 for r in result)
|
| 129 |
+
assert all(len(r.find(query)) == 1 for r in flatten(result))
|
| 130 |
+
|
| 131 |
+
s1 = (x*y - y, x**2 - x)
|
| 132 |
+
assert solve(s1) == [{x: 1}, {x: 0, y: 0}]
|
| 133 |
+
s2 = (x*y - x, y**2 - y)
|
| 134 |
+
assert solve(s2) == [{y: 1}, {x: 0, y: 0}]
|
| 135 |
+
gens = (x, y)
|
| 136 |
+
for seq in (s1, s2):
|
| 137 |
+
(f, g), opt = parallel_poly_from_expr(seq, *gens)
|
| 138 |
+
raises(SolveFailed, lambda: solve_biquadratic(f, g, opt))
|
| 139 |
+
seq = (x**2 + y**2 - 2, y**2 - 1)
|
| 140 |
+
(f, g), opt = parallel_poly_from_expr(seq, *gens)
|
| 141 |
+
assert solve_biquadratic(f, g, opt) == [
|
| 142 |
+
(-1, -1), (-1, 1), (1, -1), (1, 1)]
|
| 143 |
+
ans = [(0, -1), (0, 1)]
|
| 144 |
+
seq = (x**2 + y**2 - 1, y**2 - 1)
|
| 145 |
+
(f, g), opt = parallel_poly_from_expr(seq, *gens)
|
| 146 |
+
assert solve_biquadratic(f, g, opt) == ans
|
| 147 |
+
seq = (x**2 + y**2 - 1, x**2 - x + y**2 - 1)
|
| 148 |
+
(f, g), opt = parallel_poly_from_expr(seq, *gens)
|
| 149 |
+
assert solve_biquadratic(f, g, opt) == ans
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def test_solve_triangulated():
|
| 153 |
+
f_1 = x**2 + y + z - 1
|
| 154 |
+
f_2 = x + y**2 + z - 1
|
| 155 |
+
f_3 = x + y + z**2 - 1
|
| 156 |
+
|
| 157 |
+
a, b = sqrt(2) - 1, -sqrt(2) - 1
|
| 158 |
+
|
| 159 |
+
assert solve_triangulated([f_1, f_2, f_3], x, y, z) == \
|
| 160 |
+
[(0, 0, 1), (0, 1, 0), (1, 0, 0)]
|
| 161 |
+
|
| 162 |
+
dom = QQ.algebraic_field(sqrt(2))
|
| 163 |
+
|
| 164 |
+
assert solve_triangulated([f_1, f_2, f_3], x, y, z, domain=dom) == \
|
| 165 |
+
[(0, 0, 1), (0, 1, 0), (1, 0, 0), (a, a, a), (b, b, b)]
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def test_solve_issue_3686():
|
| 169 |
+
roots = solve_poly_system([((x - 5)**2/250000 + (y - Rational(5, 10))**2/250000) - 1, x], x, y)
|
| 170 |
+
assert roots == [(0, S.Half - 15*sqrt(1111)), (0, S.Half + 15*sqrt(1111))]
|
| 171 |
+
|
| 172 |
+
roots = solve_poly_system([((x - 5)**2/250000 + (y - 5.0/10)**2/250000) - 1, x], x, y)
|
| 173 |
+
# TODO: does this really have to be so complicated?!
|
| 174 |
+
assert len(roots) == 2
|
| 175 |
+
assert roots[0][0] == 0
|
| 176 |
+
assert roots[0][1].epsilon_eq(-499.474999374969, 1e12)
|
| 177 |
+
assert roots[1][0] == 0
|
| 178 |
+
assert roots[1][1].epsilon_eq(500.474999374969, 1e12)
|
evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/tests/test_recurr.py
ADDED
|
@@ -0,0 +1,295 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.function import (Function, Lambda, expand)
|
| 2 |
+
from sympy.core.numbers import (I, Rational)
|
| 3 |
+
from sympy.core.relational import Eq
|
| 4 |
+
from sympy.core.singleton import S
|
| 5 |
+
from sympy.core.symbol import (Symbol, symbols)
|
| 6 |
+
from sympy.functions.combinatorial.factorials import (rf, binomial, factorial)
|
| 7 |
+
from sympy.functions.elementary.complexes import Abs
|
| 8 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 9 |
+
from sympy.functions.elementary.trigonometric import (cos, sin)
|
| 10 |
+
from sympy.polys.polytools import factor
|
| 11 |
+
from sympy.solvers.recurr import rsolve, rsolve_hyper, rsolve_poly, rsolve_ratio
|
| 12 |
+
from sympy.testing.pytest import raises, slow, XFAIL
|
| 13 |
+
from sympy.abc import a, b
|
| 14 |
+
|
| 15 |
+
y = Function('y')
|
| 16 |
+
n, k = symbols('n,k', integer=True)
|
| 17 |
+
C0, C1, C2 = symbols('C0,C1,C2')
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def test_rsolve_poly():
|
| 21 |
+
assert rsolve_poly([-1, -1, 1], 0, n) == 0
|
| 22 |
+
assert rsolve_poly([-1, -1, 1], 1, n) == -1
|
| 23 |
+
|
| 24 |
+
assert rsolve_poly([-1, n + 1], n, n) == 1
|
| 25 |
+
assert rsolve_poly([-1, 1], n, n) == C0 + (n**2 - n)/2
|
| 26 |
+
assert rsolve_poly([-n - 1, n], 1, n) == C0*n - 1
|
| 27 |
+
assert rsolve_poly([-4*n - 2, 1], 4*n + 1, n) == -1
|
| 28 |
+
|
| 29 |
+
assert rsolve_poly([-1, 1], n**5 + n**3, n) == \
|
| 30 |
+
C0 - n**3 / 2 - n**5 / 2 + n**2 / 6 + n**6 / 6 + 2*n**4 / 3
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def test_rsolve_ratio():
|
| 34 |
+
solution = rsolve_ratio([-2*n**3 + n**2 + 2*n - 1, 2*n**3 + n**2 - 6*n,
|
| 35 |
+
-2*n**3 - 11*n**2 - 18*n - 9, 2*n**3 + 13*n**2 + 22*n + 8], 0, n)
|
| 36 |
+
assert solution == C0*(2*n - 3)/(n**2 - 1)/2
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def test_rsolve_hyper():
|
| 40 |
+
assert rsolve_hyper([-1, -1, 1], 0, n) in [
|
| 41 |
+
C0*(S.Half - S.Half*sqrt(5))**n + C1*(S.Half + S.Half*sqrt(5))**n,
|
| 42 |
+
C1*(S.Half - S.Half*sqrt(5))**n + C0*(S.Half + S.Half*sqrt(5))**n,
|
| 43 |
+
]
|
| 44 |
+
|
| 45 |
+
assert rsolve_hyper([n**2 - 2, -2*n - 1, 1], 0, n) in [
|
| 46 |
+
C0*rf(sqrt(2), n) + C1*rf(-sqrt(2), n),
|
| 47 |
+
C1*rf(sqrt(2), n) + C0*rf(-sqrt(2), n),
|
| 48 |
+
]
|
| 49 |
+
|
| 50 |
+
assert rsolve_hyper([n**2 - k, -2*n - 1, 1], 0, n) in [
|
| 51 |
+
C0*rf(sqrt(k), n) + C1*rf(-sqrt(k), n),
|
| 52 |
+
C1*rf(sqrt(k), n) + C0*rf(-sqrt(k), n),
|
| 53 |
+
]
|
| 54 |
+
|
| 55 |
+
assert rsolve_hyper(
|
| 56 |
+
[2*n*(n + 1), -n**2 - 3*n + 2, n - 1], 0, n) == C1*factorial(n) + C0*2**n
|
| 57 |
+
|
| 58 |
+
assert rsolve_hyper(
|
| 59 |
+
[n + 2, -(2*n + 3)*(17*n**2 + 51*n + 39), n + 1], 0, n) == 0
|
| 60 |
+
|
| 61 |
+
assert rsolve_hyper([-n - 1, -1, 1], 0, n) == 0
|
| 62 |
+
|
| 63 |
+
assert rsolve_hyper([-1, 1], n, n).expand() == C0 + n**2/2 - n/2
|
| 64 |
+
|
| 65 |
+
assert rsolve_hyper([-1, 1], 1 + n, n).expand() == C0 + n**2/2 + n/2
|
| 66 |
+
|
| 67 |
+
assert rsolve_hyper([-1, 1], 3*(n + n**2), n).expand() == C0 + n**3 - n
|
| 68 |
+
|
| 69 |
+
assert rsolve_hyper([-a, 1],0,n).expand() == C0*a**n
|
| 70 |
+
|
| 71 |
+
assert rsolve_hyper([-a, 0, 1], 0, n).expand() == (-1)**n*C1*a**(n/2) + C0*a**(n/2)
|
| 72 |
+
|
| 73 |
+
assert rsolve_hyper([1, 1, 1], 0, n).expand() == \
|
| 74 |
+
C0*(Rational(-1, 2) - sqrt(3)*I/2)**n + C1*(Rational(-1, 2) + sqrt(3)*I/2)**n
|
| 75 |
+
|
| 76 |
+
assert rsolve_hyper([1, -2*n/a - 2/a, 1], 0, n) == 0
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
@XFAIL
|
| 80 |
+
def test_rsolve_ratio_missed():
|
| 81 |
+
# this arises during computation
|
| 82 |
+
# assert rsolve_hyper([-1, 1], 3*(n + n**2), n).expand() == C0 + n**3 - n
|
| 83 |
+
assert rsolve_ratio([-n, n + 2], n, n) is not None
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def recurrence_term(c, f):
|
| 87 |
+
"""Compute RHS of recurrence in f(n) with coefficients in c."""
|
| 88 |
+
return sum(c[i]*f.subs(n, n + i) for i in range(len(c)))
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def test_rsolve_bulk():
|
| 92 |
+
"""Some bulk-generated tests."""
|
| 93 |
+
funcs = [ n, n + 1, n**2, n**3, n**4, n + n**2, 27*n + 52*n**2 - 3*
|
| 94 |
+
n**3 + 12*n**4 - 52*n**5 ]
|
| 95 |
+
coeffs = [ [-2, 1], [-2, -1, 1], [-1, 1, 1, -1, 1], [-n, 1], [n**2 -
|
| 96 |
+
n + 12, 1] ]
|
| 97 |
+
for p in funcs:
|
| 98 |
+
# compute difference
|
| 99 |
+
for c in coeffs:
|
| 100 |
+
q = recurrence_term(c, p)
|
| 101 |
+
if p.is_polynomial(n):
|
| 102 |
+
assert rsolve_poly(c, q, n) == p
|
| 103 |
+
# See issue 3956:
|
| 104 |
+
if p.is_hypergeometric(n) and len(c) <= 3:
|
| 105 |
+
assert rsolve_hyper(c, q, n).subs(zip(symbols('C:3'), [0, 0, 0])).expand() == p
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def test_rsolve_0_sol_homogeneous():
|
| 109 |
+
# fixed by cherry-pick from
|
| 110 |
+
# https://github.com/diofant/diofant/commit/e1d2e52125199eb3df59f12e8944f8a5f24b00a5
|
| 111 |
+
assert rsolve_hyper([n**2 - n + 12, 1], n*(n**2 - n + 12) + n + 1, n) == n
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def test_rsolve():
|
| 115 |
+
f = y(n + 2) - y(n + 1) - y(n)
|
| 116 |
+
h = sqrt(5)*(S.Half + S.Half*sqrt(5))**n \
|
| 117 |
+
- sqrt(5)*(S.Half - S.Half*sqrt(5))**n
|
| 118 |
+
|
| 119 |
+
assert rsolve(f, y(n)) in [
|
| 120 |
+
C0*(S.Half - S.Half*sqrt(5))**n + C1*(S.Half + S.Half*sqrt(5))**n,
|
| 121 |
+
C1*(S.Half - S.Half*sqrt(5))**n + C0*(S.Half + S.Half*sqrt(5))**n,
|
| 122 |
+
]
|
| 123 |
+
|
| 124 |
+
assert rsolve(f, y(n), [0, 5]) == h
|
| 125 |
+
assert rsolve(f, y(n), {0: 0, 1: 5}) == h
|
| 126 |
+
assert rsolve(f, y(n), {y(0): 0, y(1): 5}) == h
|
| 127 |
+
assert rsolve(y(n) - y(n - 1) - y(n - 2), y(n), [0, 5]) == h
|
| 128 |
+
assert rsolve(Eq(y(n), y(n - 1) + y(n - 2)), y(n), [0, 5]) == h
|
| 129 |
+
|
| 130 |
+
assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0
|
| 131 |
+
|
| 132 |
+
f = (n - 1)*y(n + 2) - (n**2 + 3*n - 2)*y(n + 1) + 2*n*(n + 1)*y(n)
|
| 133 |
+
g = C1*factorial(n) + C0*2**n
|
| 134 |
+
h = -3*factorial(n) + 3*2**n
|
| 135 |
+
|
| 136 |
+
assert rsolve(f, y(n)) == g
|
| 137 |
+
assert rsolve(f, y(n), []) == g
|
| 138 |
+
assert rsolve(f, y(n), {}) == g
|
| 139 |
+
|
| 140 |
+
assert rsolve(f, y(n), [0, 3]) == h
|
| 141 |
+
assert rsolve(f, y(n), {0: 0, 1: 3}) == h
|
| 142 |
+
assert rsolve(f, y(n), {y(0): 0, y(1): 3}) == h
|
| 143 |
+
|
| 144 |
+
assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0
|
| 145 |
+
|
| 146 |
+
f = y(n) - y(n - 1) - 2
|
| 147 |
+
|
| 148 |
+
assert rsolve(f, y(n), {y(0): 0}) == 2*n
|
| 149 |
+
assert rsolve(f, y(n), {y(0): 1}) == 2*n + 1
|
| 150 |
+
assert rsolve(f, y(n), {y(0): 0, y(1): 1}) is None
|
| 151 |
+
|
| 152 |
+
assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0
|
| 153 |
+
|
| 154 |
+
f = 3*y(n - 1) - y(n) - 1
|
| 155 |
+
|
| 156 |
+
assert rsolve(f, y(n), {y(0): 0}) == -3**n/2 + S.Half
|
| 157 |
+
assert rsolve(f, y(n), {y(0): 1}) == 3**n/2 + S.Half
|
| 158 |
+
assert rsolve(f, y(n), {y(0): 2}) == 3*3**n/2 + S.Half
|
| 159 |
+
|
| 160 |
+
assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0
|
| 161 |
+
|
| 162 |
+
f = y(n) - 1/n*y(n - 1)
|
| 163 |
+
assert rsolve(f, y(n)) == C0/factorial(n)
|
| 164 |
+
assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0
|
| 165 |
+
|
| 166 |
+
f = y(n) - 1/n*y(n - 1) - 1
|
| 167 |
+
assert rsolve(f, y(n)) is None
|
| 168 |
+
|
| 169 |
+
f = 2*y(n - 1) + (1 - n)*y(n)/n
|
| 170 |
+
|
| 171 |
+
assert rsolve(f, y(n), {y(1): 1}) == 2**(n - 1)*n
|
| 172 |
+
assert rsolve(f, y(n), {y(1): 2}) == 2**(n - 1)*n*2
|
| 173 |
+
assert rsolve(f, y(n), {y(1): 3}) == 2**(n - 1)*n*3
|
| 174 |
+
|
| 175 |
+
assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0
|
| 176 |
+
|
| 177 |
+
f = (n - 1)*(n - 2)*y(n + 2) - (n + 1)*(n + 2)*y(n)
|
| 178 |
+
|
| 179 |
+
assert rsolve(f, y(n), {y(3): 6, y(4): 24}) == n*(n - 1)*(n - 2)
|
| 180 |
+
assert rsolve(
|
| 181 |
+
f, y(n), {y(3): 6, y(4): -24}) == -n*(n - 1)*(n - 2)*(-1)**(n)
|
| 182 |
+
|
| 183 |
+
assert f.subs(y, Lambda(k, rsolve(f, y(n)).subs(n, k))).simplify() == 0
|
| 184 |
+
|
| 185 |
+
assert rsolve(Eq(y(n + 1), a*y(n)), y(n), {y(1): a}).simplify() == a**n
|
| 186 |
+
|
| 187 |
+
assert rsolve(y(n) - a*y(n-2),y(n), \
|
| 188 |
+
{y(1): sqrt(a)*(a + b), y(2): a*(a - b)}).simplify() == \
|
| 189 |
+
a**(n/2 + 1) - b*(-sqrt(a))**n
|
| 190 |
+
|
| 191 |
+
f = (-16*n**2 + 32*n - 12)*y(n - 1) + (4*n**2 - 12*n + 9)*y(n)
|
| 192 |
+
|
| 193 |
+
yn = rsolve(f, y(n), {y(1): binomial(2*n + 1, 3)})
|
| 194 |
+
sol = 2**(2*n)*n*(2*n - 1)**2*(2*n + 1)/12
|
| 195 |
+
assert factor(expand(yn, func=True)) == sol
|
| 196 |
+
|
| 197 |
+
sol = rsolve(y(n) + a*(y(n + 1) + y(n - 1))/2, y(n))
|
| 198 |
+
assert str(sol) == 'C0*((-sqrt(1 - a**2) - 1)/a)**n + C1*((sqrt(1 - a**2) - 1)/a)**n'
|
| 199 |
+
|
| 200 |
+
assert rsolve((k + 1)*y(k), y(k)) is None
|
| 201 |
+
assert (rsolve((k + 1)*y(k) + (k + 3)*y(k + 1) + (k + 5)*y(k + 2), y(k))
|
| 202 |
+
is None)
|
| 203 |
+
|
| 204 |
+
assert rsolve(y(n) + y(n + 1) + 2**n + 3**n, y(n)) == (-1)**n*C0 - 2**n/3 - 3**n/4
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def test_rsolve_raises():
|
| 208 |
+
x = Function('x')
|
| 209 |
+
raises(ValueError, lambda: rsolve(y(n) - y(k + 1), y(n)))
|
| 210 |
+
raises(ValueError, lambda: rsolve(y(n) - y(n + 1), x(n)))
|
| 211 |
+
raises(ValueError, lambda: rsolve(y(n) - x(n + 1), y(n)))
|
| 212 |
+
raises(ValueError, lambda: rsolve(y(n) - sqrt(n)*y(n + 1), y(n)))
|
| 213 |
+
raises(ValueError, lambda: rsolve(y(n) - y(n + 1), y(n), {x(0): 0}))
|
| 214 |
+
raises(ValueError, lambda: rsolve(y(n) + y(n + 1) + 2**n + cos(n), y(n)))
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def test_issue_6844():
|
| 218 |
+
f = y(n + 2) - y(n + 1) + y(n)/4
|
| 219 |
+
assert rsolve(f, y(n)) == 2**(-n + 1)*C1*n + 2**(-n)*C0
|
| 220 |
+
assert rsolve(f, y(n), {y(0): 0, y(1): 1}) == 2**(1 - n)*n
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def test_issue_18751():
|
| 224 |
+
r = Symbol('r', positive=True)
|
| 225 |
+
theta = Symbol('theta', real=True)
|
| 226 |
+
f = y(n) - 2 * r * cos(theta) * y(n - 1) + r**2 * y(n - 2)
|
| 227 |
+
assert rsolve(f, y(n)) == \
|
| 228 |
+
C0*(r*(cos(theta) - I*Abs(sin(theta))))**n + C1*(r*(cos(theta) + I*Abs(sin(theta))))**n
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def test_constant_naming():
|
| 232 |
+
#issue 8697
|
| 233 |
+
assert rsolve(y(n+3) - y(n+2) - y(n+1) + y(n), y(n)) == (-1)**n*C1 + C0 + C2*n
|
| 234 |
+
assert rsolve(y(n+3)+3*y(n+2)+3*y(n+1)+y(n), y(n)).expand() == (-1)**n*C0 - (-1)**n*C1*n - (-1)**n*C2*n**2
|
| 235 |
+
assert rsolve(y(n) - 2*y(n - 3) + 5*y(n - 2) - 4*y(n - 1),y(n),[1,3,8]) == 3*2**n - n - 2
|
| 236 |
+
|
| 237 |
+
#issue 19630
|
| 238 |
+
assert rsolve(y(n+3) - 3*y(n+1) + 2*y(n), y(n), {y(1):0, y(2):8, y(3):-2}) == (-2)**n + 2*n
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
@slow
|
| 242 |
+
def test_issue_15751():
|
| 243 |
+
f = y(n) + 21*y(n + 1) - 273*y(n + 2) - 1092*y(n + 3) + 1820*y(n + 4) + 1092*y(n + 5) - 273*y(n + 6) - 21*y(n + 7) + y(n + 8)
|
| 244 |
+
assert rsolve(f, y(n)) is not None
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def test_issue_17990():
|
| 248 |
+
f = -10*y(n) + 4*y(n + 1) + 6*y(n + 2) + 46*y(n + 3)
|
| 249 |
+
sol = rsolve(f, y(n))
|
| 250 |
+
expected = C0*((86*18**(S(1)/3)/69 + (-12 + (-1 + sqrt(3)*I)*(290412 +
|
| 251 |
+
3036*sqrt(9165))**(S(1)/3))*(1 - sqrt(3)*I)*(24201 + 253*sqrt(9165))**
|
| 252 |
+
(S(1)/3)/276)/((1 - sqrt(3)*I)*(24201 + 253*sqrt(9165))**(S(1)/3))
|
| 253 |
+
)**n + C1*((86*18**(S(1)/3)/69 + (-12 + (-1 - sqrt(3)*I)*(290412 + 3036
|
| 254 |
+
*sqrt(9165))**(S(1)/3))*(1 + sqrt(3)*I)*(24201 + 253*sqrt(9165))**
|
| 255 |
+
(S(1)/3)/276)/((1 + sqrt(3)*I)*(24201 + 253*sqrt(9165))**(S(1)/3))
|
| 256 |
+
)**n + C2*(-43*18**(S(1)/3)/(69*(24201 + 253*sqrt(9165))**(S(1)/3)) -
|
| 257 |
+
S(1)/23 + (290412 + 3036*sqrt(9165))**(S(1)/3)/138)**n
|
| 258 |
+
assert sol == expected
|
| 259 |
+
e = sol.subs({C0: 1, C1: 1, C2: 1, n: 1}).evalf()
|
| 260 |
+
assert abs(e + 0.130434782608696) < 1e-13
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def test_issue_8697():
|
| 264 |
+
a = Function('a')
|
| 265 |
+
eq = a(n + 3) - a(n + 2) - a(n + 1) + a(n)
|
| 266 |
+
assert rsolve(eq, a(n)) == (-1)**n*C1 + C0 + C2*n
|
| 267 |
+
eq2 = a(n + 3) + 3*a(n + 2) + 3*a(n + 1) + a(n)
|
| 268 |
+
assert (rsolve(eq2, a(n)) ==
|
| 269 |
+
(-1)**n*C0 + (-1)**(n + 1)*C1*n + (-1)**(n + 1)*C2*n**2)
|
| 270 |
+
|
| 271 |
+
assert rsolve(a(n) - 2*a(n - 3) + 5*a(n - 2) - 4*a(n - 1),
|
| 272 |
+
a(n), {a(0): 1, a(1): 3, a(2): 8}) == 3*2**n - n - 2
|
| 273 |
+
|
| 274 |
+
# From issue thread (but fixed by https://github.com/diofant/diofant/commit/da9789c6cd7d0c2ceeea19fbf59645987125b289):
|
| 275 |
+
assert rsolve(a(n) - 2*a(n - 1) - n, a(n), {a(0): 1}) == 3*2**n - n - 2
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
def test_diofantissue_294():
|
| 279 |
+
f = y(n) - y(n - 1) - 2*y(n - 2) - 2*n
|
| 280 |
+
assert rsolve(f, y(n)) == (-1)**n*C0 + 2**n*C1 - n - Rational(5, 2)
|
| 281 |
+
# issue sympy/sympy#11261
|
| 282 |
+
assert rsolve(f, y(n), {y(0): -1, y(1): 1}) == (-(-1)**n/2 + 2*2**n -
|
| 283 |
+
n - Rational(5, 2))
|
| 284 |
+
# issue sympy/sympy#7055
|
| 285 |
+
assert rsolve(-2*y(n) + y(n + 1) + n - 1, y(n)) == 2**n*C0 + n
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
def test_issue_15553():
|
| 289 |
+
f = Function("f")
|
| 290 |
+
assert rsolve(Eq(f(n), 2*f(n - 1) + n), f(n)) == 2**n*C0 - n - 2
|
| 291 |
+
assert rsolve(Eq(f(n + 1), 2*f(n) + n**2 + 1), f(n)) == 2**n*C0 - n**2 - 2*n - 4
|
| 292 |
+
assert rsolve(Eq(f(n + 1), 2*f(n) + n**2 + 1), f(n), {f(1): 0}) == 7*2**n/2 - n**2 - 2*n - 4
|
| 293 |
+
assert rsolve(Eq(f(n), 2*f(n - 1) + 3*n**2), f(n)) == 2**n*C0 - 3*n**2 - 12*n - 18
|
| 294 |
+
assert rsolve(Eq(f(n), 2*f(n - 1) + n**2), f(n)) == 2**n*C0 - n**2 - 4*n - 6
|
| 295 |
+
assert rsolve(Eq(f(n), 2*f(n - 1) + n), f(n), {f(0): 1}) == 3*2**n - n - 2
|
evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/tests/test_simplex.py
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.numbers import Rational
|
| 2 |
+
from sympy.core.relational import Eq, Ne
|
| 3 |
+
from sympy.core.symbol import symbols
|
| 4 |
+
from sympy.core.sympify import sympify
|
| 5 |
+
from sympy.core.singleton import S
|
| 6 |
+
from sympy.core.random import random, choice
|
| 7 |
+
from sympy.functions.elementary.miscellaneous import sqrt
|
| 8 |
+
from sympy.ntheory.generate import randprime
|
| 9 |
+
from sympy.matrices.dense import Matrix
|
| 10 |
+
from sympy.solvers.solveset import linear_eq_to_matrix
|
| 11 |
+
from sympy.solvers.simplex import (_lp as lp, _primal_dual,
|
| 12 |
+
UnboundedLPError, InfeasibleLPError, lpmin, lpmax,
|
| 13 |
+
_m, _abcd, _simplex, linprog)
|
| 14 |
+
|
| 15 |
+
from sympy.external.importtools import import_module
|
| 16 |
+
|
| 17 |
+
from sympy.testing.pytest import raises
|
| 18 |
+
|
| 19 |
+
from sympy.abc import x, y, z
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
np = import_module("numpy")
|
| 23 |
+
scipy = import_module("scipy")
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def test_lp():
|
| 27 |
+
r1 = y + 2*z <= 3
|
| 28 |
+
r2 = -x - 3*z <= -2
|
| 29 |
+
r3 = 2*x + y + 7*z <= 5
|
| 30 |
+
constraints = [r1, r2, r3, x >= 0, y >= 0, z >= 0]
|
| 31 |
+
objective = -x - y - 5 * z
|
| 32 |
+
ans = optimum, argmax = lp(max, objective, constraints)
|
| 33 |
+
assert ans == lpmax(objective, constraints)
|
| 34 |
+
assert objective.subs(argmax) == optimum
|
| 35 |
+
for constr in constraints:
|
| 36 |
+
assert constr.subs(argmax) == True
|
| 37 |
+
|
| 38 |
+
r1 = x - y + 2*z <= 3
|
| 39 |
+
r2 = -x + 2*y - 3*z <= -2
|
| 40 |
+
r3 = 2*x + y - 7*z <= -5
|
| 41 |
+
constraints = [r1, r2, r3, x >= 0, y >= 0, z >= 0]
|
| 42 |
+
objective = -x - y - 5*z
|
| 43 |
+
ans = optimum, argmax = lp(max, objective, constraints)
|
| 44 |
+
assert ans == lpmax(objective, constraints)
|
| 45 |
+
assert objective.subs(argmax) == optimum
|
| 46 |
+
for constr in constraints:
|
| 47 |
+
assert constr.subs(argmax) == True
|
| 48 |
+
|
| 49 |
+
r1 = x - y + 2*z <= -4
|
| 50 |
+
r2 = -x + 2*y - 3*z <= 8
|
| 51 |
+
r3 = 2*x + y - 7*z <= 10
|
| 52 |
+
constraints = [r1, r2, r3, x >= 0, y >= 0, z >= 0]
|
| 53 |
+
const = 2
|
| 54 |
+
objective = -x-y-5*z+const # has constant term
|
| 55 |
+
ans = optimum, argmax = lp(max, objective, constraints)
|
| 56 |
+
assert ans == lpmax(objective, constraints)
|
| 57 |
+
assert objective.subs(argmax) == optimum
|
| 58 |
+
for constr in constraints:
|
| 59 |
+
assert constr.subs(argmax) == True
|
| 60 |
+
|
| 61 |
+
# Section 4 Problem 1 from
|
| 62 |
+
# http://web.tecnico.ulisboa.pt/mcasquilho/acad/or/ftp/FergusonUCLA_LP.pdf
|
| 63 |
+
# answer on page 55
|
| 64 |
+
v = x1, x2, x3, x4 = symbols('x1 x2 x3 x4')
|
| 65 |
+
r1 = x1 - x2 - 2*x3 - x4 <= 4
|
| 66 |
+
r2 = 2*x1 + x3 -4*x4 <= 2
|
| 67 |
+
r3 = -2*x1 + x2 + x4 <= 1
|
| 68 |
+
objective, constraints = x1 - 2*x2 - 3*x3 - x4, [r1, r2, r3] + [
|
| 69 |
+
i >= 0 for i in v]
|
| 70 |
+
ans = optimum, argmax = lp(max, objective, constraints)
|
| 71 |
+
assert ans == lpmax(objective, constraints)
|
| 72 |
+
assert ans == (4, {x1: 7, x2: 0, x3: 0, x4: 3})
|
| 73 |
+
|
| 74 |
+
# input contains Floats
|
| 75 |
+
r1 = x - y + 2.0*z <= -4
|
| 76 |
+
r2 = -x + 2*y - 3.0*z <= 8
|
| 77 |
+
r3 = 2*x + y - 7*z <= 10
|
| 78 |
+
constraints = [r1, r2, r3] + [i >= 0 for i in (x, y, z)]
|
| 79 |
+
objective = -x-y-5*z
|
| 80 |
+
optimum, argmax = lp(max, objective, constraints)
|
| 81 |
+
assert objective.subs(argmax) == optimum
|
| 82 |
+
for constr in constraints:
|
| 83 |
+
assert constr.subs(argmax) == True
|
| 84 |
+
|
| 85 |
+
# input contains non-float or non-Rational
|
| 86 |
+
r1 = x - y + sqrt(2) * z <= -4
|
| 87 |
+
r2 = -x + 2*y - 3*z <= 8
|
| 88 |
+
r3 = 2*x + y - 7*z <= 10
|
| 89 |
+
raises(TypeError, lambda: lp(max, -x-y-5*z, [r1, r2, r3]))
|
| 90 |
+
|
| 91 |
+
r1 = x >= 0
|
| 92 |
+
raises(UnboundedLPError, lambda: lp(max, x, [r1]))
|
| 93 |
+
r2 = x <= -1
|
| 94 |
+
raises(InfeasibleLPError, lambda: lp(max, x, [r1, r2]))
|
| 95 |
+
|
| 96 |
+
# strict inequalities are not allowed
|
| 97 |
+
r1 = x > 0
|
| 98 |
+
raises(TypeError, lambda: lp(max, x, [r1]))
|
| 99 |
+
|
| 100 |
+
# not equals not allowed
|
| 101 |
+
r1 = Ne(x, 0)
|
| 102 |
+
raises(TypeError, lambda: lp(max, x, [r1]))
|
| 103 |
+
|
| 104 |
+
def make_random_problem(nvar=2, num_constraints=2, sparsity=.1):
|
| 105 |
+
def rand():
|
| 106 |
+
if random() < sparsity:
|
| 107 |
+
return sympify(0)
|
| 108 |
+
int1, int2 = [randprime(0, 200) for _ in range(2)]
|
| 109 |
+
return Rational(int1, int2)*choice([-1, 1])
|
| 110 |
+
variables = symbols('x1:%s' % (nvar + 1))
|
| 111 |
+
constraints = [(sum(rand()*x for x in variables) <= rand())
|
| 112 |
+
for _ in range(num_constraints)]
|
| 113 |
+
objective = sum(rand() * x for x in variables)
|
| 114 |
+
return objective, constraints, variables
|
| 115 |
+
|
| 116 |
+
# equality
|
| 117 |
+
r1 = Eq(x, y)
|
| 118 |
+
r2 = Eq(y, z)
|
| 119 |
+
r3 = z <= 3
|
| 120 |
+
constraints = [r1, r2, r3]
|
| 121 |
+
objective = x
|
| 122 |
+
ans = optimum, argmax = lp(max, objective, constraints)
|
| 123 |
+
assert ans == lpmax(objective, constraints)
|
| 124 |
+
assert objective.subs(argmax) == optimum
|
| 125 |
+
for constr in constraints:
|
| 126 |
+
assert constr.subs(argmax) == True
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def test_simplex():
|
| 130 |
+
L = [
|
| 131 |
+
[[1, 1], [-1, 1], [0, 1], [-1, 0]],
|
| 132 |
+
[5, 1, 2, -1],
|
| 133 |
+
[[1, 1]],
|
| 134 |
+
[-1]]
|
| 135 |
+
A, B, C, D = _abcd(_m(*L), list=False)
|
| 136 |
+
assert _simplex(A, B, -C, -D) == (-6, [3, 2], [1, 0, 0, 0])
|
| 137 |
+
assert _simplex(A, B, -C, -D, dual=True) == (-6,
|
| 138 |
+
[1, 0, 0, 0], [5, 0])
|
| 139 |
+
|
| 140 |
+
assert _simplex([[]],[],[[1]],[0]) == (0, [0], [])
|
| 141 |
+
|
| 142 |
+
# handling of Eq (or Eq-like x<=y, x>=y conditions)
|
| 143 |
+
assert lpmax(x - y, [x <= y + 2, x >= y + 2, x >= 0, y >= 0]
|
| 144 |
+
) == (2, {x: 2, y: 0})
|
| 145 |
+
assert lpmax(x - y, [x <= y + 2, Eq(x, y + 2), x >= 0, y >= 0]
|
| 146 |
+
) == (2, {x: 2, y: 0})
|
| 147 |
+
assert lpmax(x - y, [x <= y + 2, Eq(x, 2)]) == (2, {x: 2, y: 0})
|
| 148 |
+
assert lpmax(y, [Eq(y, 2)]) == (2, {y: 2})
|
| 149 |
+
|
| 150 |
+
# the conditions are equivalent to Eq(x, y + 2)
|
| 151 |
+
assert lpmin(y, [x <= y + 2, x >= y + 2, y >= 0]
|
| 152 |
+
) == (0, {x: 2, y: 0})
|
| 153 |
+
# equivalent to Eq(y, -2)
|
| 154 |
+
assert lpmax(y, [0 <= y + 2, 0 >= y + 2]) == (-2, {y: -2})
|
| 155 |
+
assert lpmax(y, [0 <= y + 2, 0 >= y + 2, y <= 0]
|
| 156 |
+
) == (-2, {y: -2})
|
| 157 |
+
|
| 158 |
+
# extra symbols symbols
|
| 159 |
+
assert lpmin(x, [y >= 1, x >= y]) == (1, {x: 1, y: 1})
|
| 160 |
+
assert lpmin(x, [y >= 1, x >= y + z, x >= 0, z >= 0]
|
| 161 |
+
) == (1, {x: 1, y: 1, z: 0})
|
| 162 |
+
|
| 163 |
+
# detect oscillation
|
| 164 |
+
# o1
|
| 165 |
+
v = x1, x2, x3, x4 = symbols('x1 x2 x3 x4')
|
| 166 |
+
raises(InfeasibleLPError, lambda: lpmin(
|
| 167 |
+
9*x2 - 8*x3 + 3*x4 + 6,
|
| 168 |
+
[5*x2 - 2*x3 <= 0,
|
| 169 |
+
-x1 - 8*x2 + 9*x3 <= -3,
|
| 170 |
+
10*x1 - x2+ 9*x4 <= -4] + [i >= 0 for i in v]))
|
| 171 |
+
# o2 - equations fed to lpmin are changed into a matrix
|
| 172 |
+
# system that doesn't oscillate and has the same solution
|
| 173 |
+
# as below
|
| 174 |
+
M = linear_eq_to_matrix
|
| 175 |
+
f = 5*x2 + x3 + 4*x4 - x1
|
| 176 |
+
L = 5*x2 + 2*x3 + 5*x4 - (x1 + 5)
|
| 177 |
+
cond = [L <= 0] + [Eq(3*x2 + x4, 2), Eq(-x1 + x3 + 2*x4, 1)]
|
| 178 |
+
c, d = M(f, v)
|
| 179 |
+
a, b = M(L, v)
|
| 180 |
+
aeq, beq = M(cond[1:], v)
|
| 181 |
+
ans = (S(9)/2, [0, S(1)/2, 0, S(1)/2])
|
| 182 |
+
assert linprog(c, a, b, aeq, beq, bounds=(0, 1)) == ans
|
| 183 |
+
lpans = lpmin(f, cond + [x1 >= 0, x1 <= 1,
|
| 184 |
+
x2 >= 0, x2 <= 1, x3 >= 0, x3 <= 1, x4 >= 0, x4 <= 1])
|
| 185 |
+
assert (lpans[0], list(lpans[1].values())) == ans
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def test_lpmin_lpmax():
|
| 189 |
+
v = x1, x2, y1, y2 = symbols('x1 x2 y1 y2')
|
| 190 |
+
L = [[1, -1]], [1], [[1, 1]], [2]
|
| 191 |
+
a, b, c, d = [Matrix(i) for i in L]
|
| 192 |
+
m = Matrix([[a, b], [c, d]])
|
| 193 |
+
f, constr = _primal_dual(m)[0]
|
| 194 |
+
ans = lpmin(f, constr + [i >= 0 for i in v[:2]])
|
| 195 |
+
assert ans == (-1, {x1: 1, x2: 0}),ans
|
| 196 |
+
|
| 197 |
+
L = [[1, -1], [1, 1]], [1, 1], [[1, 1]], [2]
|
| 198 |
+
a, b, c, d = [Matrix(i) for i in L]
|
| 199 |
+
m = Matrix([[a, b], [c, d]])
|
| 200 |
+
f, constr = _primal_dual(m)[1]
|
| 201 |
+
ans = lpmax(f, constr + [i >= 0 for i in v[-2:]])
|
| 202 |
+
assert ans == (-1, {y1: 1, y2: 0})
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def test_linprog():
|
| 206 |
+
for do in range(2):
|
| 207 |
+
if not do:
|
| 208 |
+
M = lambda a, b: linear_eq_to_matrix(a, b)
|
| 209 |
+
else:
|
| 210 |
+
# check matrices as list
|
| 211 |
+
M = lambda a, b: tuple([
|
| 212 |
+
i.tolist() for i in linear_eq_to_matrix(a, b)])
|
| 213 |
+
|
| 214 |
+
v = x, y, z = symbols('x1:4')
|
| 215 |
+
f = x + y - 2*z
|
| 216 |
+
c = M(f, v)[0]
|
| 217 |
+
ineq = [7*x + 4*y - 7*z <= 3,
|
| 218 |
+
3*x - y + 10*z <= 6,
|
| 219 |
+
x >= 0, y >= 0, z >= 0]
|
| 220 |
+
ab = M([i.lts - i.gts for i in ineq], v)
|
| 221 |
+
ans = (-S(6)/5, [0, 0, S(3)/5])
|
| 222 |
+
assert lpmin(f, ineq) == (ans[0], dict(zip(v, ans[1])))
|
| 223 |
+
assert linprog(c, *ab) == ans
|
| 224 |
+
|
| 225 |
+
f += 1
|
| 226 |
+
c = M(f, v)[0]
|
| 227 |
+
eq = [Eq(y - 9*x, 1)]
|
| 228 |
+
abeq = M([i.lhs - i.rhs for i in eq], v)
|
| 229 |
+
ans = (1 - S(2)/5, [0, 1, S(7)/10])
|
| 230 |
+
assert lpmin(f, ineq + eq) == (ans[0], dict(zip(v, ans[1])))
|
| 231 |
+
assert linprog(c, *ab, *abeq) == (ans[0] - 1, ans[1])
|
| 232 |
+
|
| 233 |
+
eq = [z - y <= S.Half]
|
| 234 |
+
abeq = M([i.lhs - i.rhs for i in eq], v)
|
| 235 |
+
ans = (1 - S(10)/9, [0, S(1)/9, S(11)/18])
|
| 236 |
+
assert lpmin(f, ineq + eq) == (ans[0], dict(zip(v, ans[1])))
|
| 237 |
+
assert linprog(c, *ab, *abeq) == (ans[0] - 1, ans[1])
|
| 238 |
+
|
| 239 |
+
bounds = [(0, None), (0, None), (None, S.Half)]
|
| 240 |
+
ans = (0, [0, 0, S.Half])
|
| 241 |
+
assert lpmin(f, ineq + [z <= S.Half]) == (
|
| 242 |
+
ans[0], dict(zip(v, ans[1])))
|
| 243 |
+
assert linprog(c, *ab, bounds=bounds) == (ans[0] - 1, ans[1])
|
| 244 |
+
assert linprog(c, *ab, bounds={v.index(z): bounds[-1]}
|
| 245 |
+
) == (ans[0] - 1, ans[1])
|
| 246 |
+
eq = [z - y <= S.Half]
|
| 247 |
+
|
| 248 |
+
assert linprog([[1]], [], [], bounds=(2, 3)) == (2, [2])
|
| 249 |
+
assert linprog([1], [], [], bounds=(2, 3)) == (2, [2])
|
| 250 |
+
assert linprog([1], bounds=(2, 3)) == (2, [2])
|
| 251 |
+
assert linprog([1, -1], [[1, 1]], [2], bounds={1:(None, None)}
|
| 252 |
+
) == (-2, [0, 2])
|
| 253 |
+
assert linprog([1, -1], [[1, 1]], [5], bounds={1:(3, None)}
|
| 254 |
+
) == (-5, [0, 5])
|
evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/tests/test_solvers.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/solvers/tests/test_solveset.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/tensor/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (943 Bytes). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/tensor/__pycache__/index_methods.cpython-310.pyc
ADDED
|
Binary file (13.6 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/tensor/__pycache__/indexed.cpython-310.pyc
ADDED
|
Binary file (23.7 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/tensor/__pycache__/toperators.cpython-310.pyc
ADDED
|
Binary file (9.19 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/tensor/array/expressions/__pycache__/from_indexed_to_array.cpython-310.pyc
ADDED
|
Binary file (9.82 kB). View file
|
|
|
evalkit_internvl/lib/python3.10/site-packages/sympy/tensor/array/mutable_ndim_array.py
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.tensor.array.ndim_array import NDimArray
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class MutableNDimArray(NDimArray):
|
| 5 |
+
|
| 6 |
+
def as_immutable(self):
|
| 7 |
+
raise NotImplementedError("abstract method")
|
| 8 |
+
|
| 9 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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.basic import Basic
|
| 2 |
+
from sympy.core.containers import (Dict, Tuple)
|
| 3 |
+
from sympy.core.expr import Expr
|
| 4 |
+
from sympy.core.kind import Kind, NumberKind, UndefinedKind
|
| 5 |
+
from sympy.core.numbers import Integer
|
| 6 |
+
from sympy.core.singleton import S
|
| 7 |
+
from sympy.core.sympify import sympify
|
| 8 |
+
from sympy.external.gmpy import SYMPY_INTS
|
| 9 |
+
from sympy.printing.defaults import Printable
|
| 10 |
+
|
| 11 |
+
import itertools
|
| 12 |
+
from collections.abc import Iterable
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class ArrayKind(Kind):
|
| 16 |
+
"""
|
| 17 |
+
Kind for N-dimensional array in SymPy.
|
| 18 |
+
|
| 19 |
+
This kind represents the multidimensional array that algebraic
|
| 20 |
+
operations are defined. Basic class for this kind is ``NDimArray``,
|
| 21 |
+
but any expression representing the array can have this.
|
| 22 |
+
|
| 23 |
+
Parameters
|
| 24 |
+
==========
|
| 25 |
+
|
| 26 |
+
element_kind : Kind
|
| 27 |
+
Kind of the element. Default is :obj:NumberKind `<sympy.core.kind.NumberKind>`,
|
| 28 |
+
which means that the array contains only numbers.
|
| 29 |
+
|
| 30 |
+
Examples
|
| 31 |
+
========
|
| 32 |
+
|
| 33 |
+
Any instance of array class has ``ArrayKind``.
|
| 34 |
+
|
| 35 |
+
>>> from sympy import NDimArray
|
| 36 |
+
>>> NDimArray([1,2,3]).kind
|
| 37 |
+
ArrayKind(NumberKind)
|
| 38 |
+
|
| 39 |
+
Although expressions representing an array may be not instance of
|
| 40 |
+
array class, it will have ``ArrayKind`` as well.
|
| 41 |
+
|
| 42 |
+
>>> from sympy import Integral
|
| 43 |
+
>>> from sympy.tensor.array import NDimArray
|
| 44 |
+
>>> from sympy.abc import x
|
| 45 |
+
>>> intA = Integral(NDimArray([1,2,3]), x)
|
| 46 |
+
>>> isinstance(intA, NDimArray)
|
| 47 |
+
False
|
| 48 |
+
>>> intA.kind
|
| 49 |
+
ArrayKind(NumberKind)
|
| 50 |
+
|
| 51 |
+
Use ``isinstance()`` to check for ``ArrayKind` without specifying
|
| 52 |
+
the element kind. Use ``is`` with specifying the element kind.
|
| 53 |
+
|
| 54 |
+
>>> from sympy.tensor.array import ArrayKind
|
| 55 |
+
>>> from sympy.core import NumberKind
|
| 56 |
+
>>> boolA = NDimArray([True, False])
|
| 57 |
+
>>> isinstance(boolA.kind, ArrayKind)
|
| 58 |
+
True
|
| 59 |
+
>>> boolA.kind is ArrayKind(NumberKind)
|
| 60 |
+
False
|
| 61 |
+
|
| 62 |
+
See Also
|
| 63 |
+
========
|
| 64 |
+
|
| 65 |
+
shape : Function to return the shape of objects with ``MatrixKind``.
|
| 66 |
+
|
| 67 |
+
"""
|
| 68 |
+
def __new__(cls, element_kind=NumberKind):
|
| 69 |
+
obj = super().__new__(cls, element_kind)
|
| 70 |
+
obj.element_kind = element_kind
|
| 71 |
+
return obj
|
| 72 |
+
|
| 73 |
+
def __repr__(self):
|
| 74 |
+
return "ArrayKind(%s)" % self.element_kind
|
| 75 |
+
|
| 76 |
+
@classmethod
|
| 77 |
+
def _union(cls, kinds) -> 'ArrayKind':
|
| 78 |
+
elem_kinds = {e.kind for e in kinds}
|
| 79 |
+
if len(elem_kinds) == 1:
|
| 80 |
+
elemkind, = elem_kinds
|
| 81 |
+
else:
|
| 82 |
+
elemkind = UndefinedKind
|
| 83 |
+
return ArrayKind(elemkind)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class NDimArray(Printable):
|
| 87 |
+
"""N-dimensional array.
|
| 88 |
+
|
| 89 |
+
Examples
|
| 90 |
+
========
|
| 91 |
+
|
| 92 |
+
Create an N-dim array of zeros:
|
| 93 |
+
|
| 94 |
+
>>> from sympy import MutableDenseNDimArray
|
| 95 |
+
>>> a = MutableDenseNDimArray.zeros(2, 3, 4)
|
| 96 |
+
>>> a
|
| 97 |
+
[[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]]
|
| 98 |
+
|
| 99 |
+
Create an N-dim array from a list;
|
| 100 |
+
|
| 101 |
+
>>> a = MutableDenseNDimArray([[2, 3], [4, 5]])
|
| 102 |
+
>>> a
|
| 103 |
+
[[2, 3], [4, 5]]
|
| 104 |
+
|
| 105 |
+
>>> b = MutableDenseNDimArray([[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11, 12]]])
|
| 106 |
+
>>> b
|
| 107 |
+
[[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11, 12]]]
|
| 108 |
+
|
| 109 |
+
Create an N-dim array from a flat list with dimension shape:
|
| 110 |
+
|
| 111 |
+
>>> a = MutableDenseNDimArray([1, 2, 3, 4, 5, 6], (2, 3))
|
| 112 |
+
>>> a
|
| 113 |
+
[[1, 2, 3], [4, 5, 6]]
|
| 114 |
+
|
| 115 |
+
Create an N-dim array from a matrix:
|
| 116 |
+
|
| 117 |
+
>>> from sympy import Matrix
|
| 118 |
+
>>> a = Matrix([[1,2],[3,4]])
|
| 119 |
+
>>> a
|
| 120 |
+
Matrix([
|
| 121 |
+
[1, 2],
|
| 122 |
+
[3, 4]])
|
| 123 |
+
>>> b = MutableDenseNDimArray(a)
|
| 124 |
+
>>> b
|
| 125 |
+
[[1, 2], [3, 4]]
|
| 126 |
+
|
| 127 |
+
Arithmetic operations on N-dim arrays
|
| 128 |
+
|
| 129 |
+
>>> a = MutableDenseNDimArray([1, 1, 1, 1], (2, 2))
|
| 130 |
+
>>> b = MutableDenseNDimArray([4, 4, 4, 4], (2, 2))
|
| 131 |
+
>>> c = a + b
|
| 132 |
+
>>> c
|
| 133 |
+
[[5, 5], [5, 5]]
|
| 134 |
+
>>> a - b
|
| 135 |
+
[[-3, -3], [-3, -3]]
|
| 136 |
+
|
| 137 |
+
"""
|
| 138 |
+
|
| 139 |
+
_diff_wrt = True
|
| 140 |
+
is_scalar = False
|
| 141 |
+
|
| 142 |
+
def __new__(cls, iterable, shape=None, **kwargs):
|
| 143 |
+
from sympy.tensor.array import ImmutableDenseNDimArray
|
| 144 |
+
return ImmutableDenseNDimArray(iterable, shape, **kwargs)
|
| 145 |
+
|
| 146 |
+
def __getitem__(self, index):
|
| 147 |
+
raise NotImplementedError("A subclass of NDimArray should implement __getitem__")
|
| 148 |
+
|
| 149 |
+
def _parse_index(self, index):
|
| 150 |
+
if isinstance(index, (SYMPY_INTS, Integer)):
|
| 151 |
+
if index >= self._loop_size:
|
| 152 |
+
raise ValueError("Only a tuple index is accepted")
|
| 153 |
+
return index
|
| 154 |
+
|
| 155 |
+
if self._loop_size == 0:
|
| 156 |
+
raise ValueError("Index not valid with an empty array")
|
| 157 |
+
|
| 158 |
+
if len(index) != self._rank:
|
| 159 |
+
raise ValueError('Wrong number of array axes')
|
| 160 |
+
|
| 161 |
+
real_index = 0
|
| 162 |
+
# check if input index can exist in current indexing
|
| 163 |
+
for i in range(self._rank):
|
| 164 |
+
if (index[i] >= self.shape[i]) or (index[i] < -self.shape[i]):
|
| 165 |
+
raise ValueError('Index ' + str(index) + ' out of border')
|
| 166 |
+
if index[i] < 0:
|
| 167 |
+
real_index += 1
|
| 168 |
+
real_index = real_index*self.shape[i] + index[i]
|
| 169 |
+
|
| 170 |
+
return real_index
|
| 171 |
+
|
| 172 |
+
def _get_tuple_index(self, integer_index):
|
| 173 |
+
index = []
|
| 174 |
+
for sh in reversed(self.shape):
|
| 175 |
+
index.append(integer_index % sh)
|
| 176 |
+
integer_index //= sh
|
| 177 |
+
index.reverse()
|
| 178 |
+
return tuple(index)
|
| 179 |
+
|
| 180 |
+
def _check_symbolic_index(self, index):
|
| 181 |
+
# Check if any index is symbolic:
|
| 182 |
+
tuple_index = (index if isinstance(index, tuple) else (index,))
|
| 183 |
+
if any((isinstance(i, Expr) and (not i.is_number)) for i in tuple_index):
|
| 184 |
+
for i, nth_dim in zip(tuple_index, self.shape):
|
| 185 |
+
if ((i < 0) == True) or ((i >= nth_dim) == True):
|
| 186 |
+
raise ValueError("index out of range")
|
| 187 |
+
from sympy.tensor import Indexed
|
| 188 |
+
return Indexed(self, *tuple_index)
|
| 189 |
+
return None
|
| 190 |
+
|
| 191 |
+
def _setter_iterable_check(self, value):
|
| 192 |
+
from sympy.matrices.matrixbase import MatrixBase
|
| 193 |
+
if isinstance(value, (Iterable, MatrixBase, NDimArray)):
|
| 194 |
+
raise NotImplementedError
|
| 195 |
+
|
| 196 |
+
@classmethod
|
| 197 |
+
def _scan_iterable_shape(cls, iterable):
|
| 198 |
+
def f(pointer):
|
| 199 |
+
if not isinstance(pointer, Iterable):
|
| 200 |
+
return [pointer], ()
|
| 201 |
+
|
| 202 |
+
if len(pointer) == 0:
|
| 203 |
+
return [], (0,)
|
| 204 |
+
|
| 205 |
+
result = []
|
| 206 |
+
elems, shapes = zip(*[f(i) for i in pointer])
|
| 207 |
+
if len(set(shapes)) != 1:
|
| 208 |
+
raise ValueError("could not determine shape unambiguously")
|
| 209 |
+
for i in elems:
|
| 210 |
+
result.extend(i)
|
| 211 |
+
return result, (len(shapes),)+shapes[0]
|
| 212 |
+
|
| 213 |
+
return f(iterable)
|
| 214 |
+
|
| 215 |
+
@classmethod
|
| 216 |
+
def _handle_ndarray_creation_inputs(cls, iterable=None, shape=None, **kwargs):
|
| 217 |
+
from sympy.matrices.matrixbase import MatrixBase
|
| 218 |
+
from sympy.tensor.array import SparseNDimArray
|
| 219 |
+
|
| 220 |
+
if shape is None:
|
| 221 |
+
if iterable is None:
|
| 222 |
+
shape = ()
|
| 223 |
+
iterable = ()
|
| 224 |
+
# Construction of a sparse array from a sparse array
|
| 225 |
+
elif isinstance(iterable, SparseNDimArray):
|
| 226 |
+
return iterable._shape, iterable._sparse_array
|
| 227 |
+
|
| 228 |
+
# Construct N-dim array from another N-dim array:
|
| 229 |
+
elif isinstance(iterable, NDimArray):
|
| 230 |
+
shape = iterable.shape
|
| 231 |
+
|
| 232 |
+
# Construct N-dim array from an iterable (numpy arrays included):
|
| 233 |
+
elif isinstance(iterable, Iterable):
|
| 234 |
+
iterable, shape = cls._scan_iterable_shape(iterable)
|
| 235 |
+
|
| 236 |
+
# Construct N-dim array from a Matrix:
|
| 237 |
+
elif isinstance(iterable, MatrixBase):
|
| 238 |
+
shape = iterable.shape
|
| 239 |
+
|
| 240 |
+
else:
|
| 241 |
+
shape = ()
|
| 242 |
+
iterable = (iterable,)
|
| 243 |
+
|
| 244 |
+
if isinstance(iterable, (Dict, dict)) and shape is not None:
|
| 245 |
+
new_dict = iterable.copy()
|
| 246 |
+
for k in new_dict:
|
| 247 |
+
if isinstance(k, (tuple, Tuple)):
|
| 248 |
+
new_key = 0
|
| 249 |
+
for i, idx in enumerate(k):
|
| 250 |
+
new_key = new_key * shape[i] + idx
|
| 251 |
+
iterable[new_key] = iterable[k]
|
| 252 |
+
del iterable[k]
|
| 253 |
+
|
| 254 |
+
if isinstance(shape, (SYMPY_INTS, Integer)):
|
| 255 |
+
shape = (shape,)
|
| 256 |
+
|
| 257 |
+
if not all(isinstance(dim, (SYMPY_INTS, Integer)) for dim in shape):
|
| 258 |
+
raise TypeError("Shape should contain integers only.")
|
| 259 |
+
|
| 260 |
+
return tuple(shape), iterable
|
| 261 |
+
|
| 262 |
+
def __len__(self):
|
| 263 |
+
"""Overload common function len(). Returns number of elements in array.
|
| 264 |
+
|
| 265 |
+
Examples
|
| 266 |
+
========
|
| 267 |
+
|
| 268 |
+
>>> from sympy import MutableDenseNDimArray
|
| 269 |
+
>>> a = MutableDenseNDimArray.zeros(3, 3)
|
| 270 |
+
>>> a
|
| 271 |
+
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
|
| 272 |
+
>>> len(a)
|
| 273 |
+
9
|
| 274 |
+
|
| 275 |
+
"""
|
| 276 |
+
return self._loop_size
|
| 277 |
+
|
| 278 |
+
@property
|
| 279 |
+
def shape(self):
|
| 280 |
+
"""
|
| 281 |
+
Returns array shape (dimension).
|
| 282 |
+
|
| 283 |
+
Examples
|
| 284 |
+
========
|
| 285 |
+
|
| 286 |
+
>>> from sympy import MutableDenseNDimArray
|
| 287 |
+
>>> a = MutableDenseNDimArray.zeros(3, 3)
|
| 288 |
+
>>> a.shape
|
| 289 |
+
(3, 3)
|
| 290 |
+
|
| 291 |
+
"""
|
| 292 |
+
return self._shape
|
| 293 |
+
|
| 294 |
+
def rank(self):
|
| 295 |
+
"""
|
| 296 |
+
Returns rank of array.
|
| 297 |
+
|
| 298 |
+
Examples
|
| 299 |
+
========
|
| 300 |
+
|
| 301 |
+
>>> from sympy import MutableDenseNDimArray
|
| 302 |
+
>>> a = MutableDenseNDimArray.zeros(3,4,5,6,3)
|
| 303 |
+
>>> a.rank()
|
| 304 |
+
5
|
| 305 |
+
|
| 306 |
+
"""
|
| 307 |
+
return self._rank
|
| 308 |
+
|
| 309 |
+
def diff(self, *args, **kwargs):
|
| 310 |
+
"""
|
| 311 |
+
Calculate the derivative of each element in the array.
|
| 312 |
+
|
| 313 |
+
Examples
|
| 314 |
+
========
|
| 315 |
+
|
| 316 |
+
>>> from sympy import ImmutableDenseNDimArray
|
| 317 |
+
>>> from sympy.abc import x, y
|
| 318 |
+
>>> M = ImmutableDenseNDimArray([[x, y], [1, x*y]])
|
| 319 |
+
>>> M.diff(x)
|
| 320 |
+
[[1, 0], [0, y]]
|
| 321 |
+
|
| 322 |
+
"""
|
| 323 |
+
from sympy.tensor.array.array_derivatives import ArrayDerivative
|
| 324 |
+
kwargs.setdefault('evaluate', True)
|
| 325 |
+
return ArrayDerivative(self.as_immutable(), *args, **kwargs)
|
| 326 |
+
|
| 327 |
+
def _eval_derivative(self, base):
|
| 328 |
+
# Types are (base: scalar, self: array)
|
| 329 |
+
return self.applyfunc(lambda x: base.diff(x))
|
| 330 |
+
|
| 331 |
+
def _eval_derivative_n_times(self, s, n):
|
| 332 |
+
return Basic._eval_derivative_n_times(self, s, n)
|
| 333 |
+
|
| 334 |
+
def applyfunc(self, f):
|
| 335 |
+
"""Apply a function to each element of the N-dim array.
|
| 336 |
+
|
| 337 |
+
Examples
|
| 338 |
+
========
|
| 339 |
+
|
| 340 |
+
>>> from sympy import ImmutableDenseNDimArray
|
| 341 |
+
>>> m = ImmutableDenseNDimArray([i*2+j for i in range(2) for j in range(2)], (2, 2))
|
| 342 |
+
>>> m
|
| 343 |
+
[[0, 1], [2, 3]]
|
| 344 |
+
>>> m.applyfunc(lambda i: 2*i)
|
| 345 |
+
[[0, 2], [4, 6]]
|
| 346 |
+
"""
|
| 347 |
+
from sympy.tensor.array import SparseNDimArray
|
| 348 |
+
from sympy.tensor.array.arrayop import Flatten
|
| 349 |
+
|
| 350 |
+
if isinstance(self, SparseNDimArray) and f(S.Zero) == 0:
|
| 351 |
+
return type(self)({k: f(v) for k, v in self._sparse_array.items() if f(v) != 0}, self.shape)
|
| 352 |
+
|
| 353 |
+
return type(self)(map(f, Flatten(self)), self.shape)
|
| 354 |
+
|
| 355 |
+
def _sympystr(self, printer):
|
| 356 |
+
def f(sh, shape_left, i, j):
|
| 357 |
+
if len(shape_left) == 1:
|
| 358 |
+
return "["+", ".join([printer._print(self[self._get_tuple_index(e)]) for e in range(i, j)])+"]"
|
| 359 |
+
|
| 360 |
+
sh //= shape_left[0]
|
| 361 |
+
return "[" + ", ".join([f(sh, shape_left[1:], i+e*sh, i+(e+1)*sh) for e in range(shape_left[0])]) + "]" # + "\n"*len(shape_left)
|
| 362 |
+
|
| 363 |
+
if self.rank() == 0:
|
| 364 |
+
return printer._print(self[()])
|
| 365 |
+
|
| 366 |
+
return f(self._loop_size, self.shape, 0, self._loop_size)
|
| 367 |
+
|
| 368 |
+
def tolist(self):
|
| 369 |
+
"""
|
| 370 |
+
Converting MutableDenseNDimArray to one-dim list
|
| 371 |
+
|
| 372 |
+
Examples
|
| 373 |
+
========
|
| 374 |
+
|
| 375 |
+
>>> from sympy import MutableDenseNDimArray
|
| 376 |
+
>>> a = MutableDenseNDimArray([1, 2, 3, 4], (2, 2))
|
| 377 |
+
>>> a
|
| 378 |
+
[[1, 2], [3, 4]]
|
| 379 |
+
>>> b = a.tolist()
|
| 380 |
+
>>> b
|
| 381 |
+
[[1, 2], [3, 4]]
|
| 382 |
+
"""
|
| 383 |
+
|
| 384 |
+
def f(sh, shape_left, i, j):
|
| 385 |
+
if len(shape_left) == 1:
|
| 386 |
+
return [self[self._get_tuple_index(e)] for e in range(i, j)]
|
| 387 |
+
result = []
|
| 388 |
+
sh //= shape_left[0]
|
| 389 |
+
for e in range(shape_left[0]):
|
| 390 |
+
result.append(f(sh, shape_left[1:], i+e*sh, i+(e+1)*sh))
|
| 391 |
+
return result
|
| 392 |
+
|
| 393 |
+
return f(self._loop_size, self.shape, 0, self._loop_size)
|
| 394 |
+
|
| 395 |
+
def __add__(self, other):
|
| 396 |
+
from sympy.tensor.array.arrayop import Flatten
|
| 397 |
+
|
| 398 |
+
if not isinstance(other, NDimArray):
|
| 399 |
+
return NotImplemented
|
| 400 |
+
|
| 401 |
+
if self.shape != other.shape:
|
| 402 |
+
raise ValueError("array shape mismatch")
|
| 403 |
+
result_list = [i+j for i,j in zip(Flatten(self), Flatten(other))]
|
| 404 |
+
|
| 405 |
+
return type(self)(result_list, self.shape)
|
| 406 |
+
|
| 407 |
+
def __sub__(self, other):
|
| 408 |
+
from sympy.tensor.array.arrayop import Flatten
|
| 409 |
+
|
| 410 |
+
if not isinstance(other, NDimArray):
|
| 411 |
+
return NotImplemented
|
| 412 |
+
|
| 413 |
+
if self.shape != other.shape:
|
| 414 |
+
raise ValueError("array shape mismatch")
|
| 415 |
+
result_list = [i-j for i,j in zip(Flatten(self), Flatten(other))]
|
| 416 |
+
|
| 417 |
+
return type(self)(result_list, self.shape)
|
| 418 |
+
|
| 419 |
+
def __mul__(self, other):
|
| 420 |
+
from sympy.matrices.matrixbase import MatrixBase
|
| 421 |
+
from sympy.tensor.array import SparseNDimArray
|
| 422 |
+
from sympy.tensor.array.arrayop import Flatten
|
| 423 |
+
|
| 424 |
+
if isinstance(other, (Iterable, NDimArray, MatrixBase)):
|
| 425 |
+
raise ValueError("scalar expected, use tensorproduct(...) for tensorial product")
|
| 426 |
+
|
| 427 |
+
other = sympify(other)
|
| 428 |
+
if isinstance(self, SparseNDimArray):
|
| 429 |
+
if other.is_zero:
|
| 430 |
+
return type(self)({}, self.shape)
|
| 431 |
+
return type(self)({k: other*v for (k, v) in self._sparse_array.items()}, self.shape)
|
| 432 |
+
|
| 433 |
+
result_list = [i*other for i in Flatten(self)]
|
| 434 |
+
return type(self)(result_list, self.shape)
|
| 435 |
+
|
| 436 |
+
def __rmul__(self, other):
|
| 437 |
+
from sympy.matrices.matrixbase import MatrixBase
|
| 438 |
+
from sympy.tensor.array import SparseNDimArray
|
| 439 |
+
from sympy.tensor.array.arrayop import Flatten
|
| 440 |
+
|
| 441 |
+
if isinstance(other, (Iterable, NDimArray, MatrixBase)):
|
| 442 |
+
raise ValueError("scalar expected, use tensorproduct(...) for tensorial product")
|
| 443 |
+
|
| 444 |
+
other = sympify(other)
|
| 445 |
+
if isinstance(self, SparseNDimArray):
|
| 446 |
+
if other.is_zero:
|
| 447 |
+
return type(self)({}, self.shape)
|
| 448 |
+
return type(self)({k: other*v for (k, v) in self._sparse_array.items()}, self.shape)
|
| 449 |
+
|
| 450 |
+
result_list = [other*i for i in Flatten(self)]
|
| 451 |
+
return type(self)(result_list, self.shape)
|
| 452 |
+
|
| 453 |
+
def __truediv__(self, other):
|
| 454 |
+
from sympy.matrices.matrixbase import MatrixBase
|
| 455 |
+
from sympy.tensor.array import SparseNDimArray
|
| 456 |
+
from sympy.tensor.array.arrayop import Flatten
|
| 457 |
+
|
| 458 |
+
if isinstance(other, (Iterable, NDimArray, MatrixBase)):
|
| 459 |
+
raise ValueError("scalar expected")
|
| 460 |
+
|
| 461 |
+
other = sympify(other)
|
| 462 |
+
if isinstance(self, SparseNDimArray) and other != S.Zero:
|
| 463 |
+
return type(self)({k: v/other for (k, v) in self._sparse_array.items()}, self.shape)
|
| 464 |
+
|
| 465 |
+
result_list = [i/other for i in Flatten(self)]
|
| 466 |
+
return type(self)(result_list, self.shape)
|
| 467 |
+
|
| 468 |
+
def __rtruediv__(self, other):
|
| 469 |
+
raise NotImplementedError('unsupported operation on NDimArray')
|
| 470 |
+
|
| 471 |
+
def __neg__(self):
|
| 472 |
+
from sympy.tensor.array import SparseNDimArray
|
| 473 |
+
from sympy.tensor.array.arrayop import Flatten
|
| 474 |
+
|
| 475 |
+
if isinstance(self, SparseNDimArray):
|
| 476 |
+
return type(self)({k: -v for (k, v) in self._sparse_array.items()}, self.shape)
|
| 477 |
+
|
| 478 |
+
result_list = [-i for i in Flatten(self)]
|
| 479 |
+
return type(self)(result_list, self.shape)
|
| 480 |
+
|
| 481 |
+
def __iter__(self):
|
| 482 |
+
def iterator():
|
| 483 |
+
if self._shape:
|
| 484 |
+
for i in range(self._shape[0]):
|
| 485 |
+
yield self[i]
|
| 486 |
+
else:
|
| 487 |
+
yield self[()]
|
| 488 |
+
|
| 489 |
+
return iterator()
|
| 490 |
+
|
| 491 |
+
def __eq__(self, other):
|
| 492 |
+
"""
|
| 493 |
+
NDimArray instances can be compared to each other.
|
| 494 |
+
Instances equal if they have same shape and data.
|
| 495 |
+
|
| 496 |
+
Examples
|
| 497 |
+
========
|
| 498 |
+
|
| 499 |
+
>>> from sympy import MutableDenseNDimArray
|
| 500 |
+
>>> a = MutableDenseNDimArray.zeros(2, 3)
|
| 501 |
+
>>> b = MutableDenseNDimArray.zeros(2, 3)
|
| 502 |
+
>>> a == b
|
| 503 |
+
True
|
| 504 |
+
>>> c = a.reshape(3, 2)
|
| 505 |
+
>>> c == b
|
| 506 |
+
False
|
| 507 |
+
>>> a[0,0] = 1
|
| 508 |
+
>>> b[0,0] = 2
|
| 509 |
+
>>> a == b
|
| 510 |
+
False
|
| 511 |
+
"""
|
| 512 |
+
from sympy.tensor.array import SparseNDimArray
|
| 513 |
+
if not isinstance(other, NDimArray):
|
| 514 |
+
return False
|
| 515 |
+
|
| 516 |
+
if not self.shape == other.shape:
|
| 517 |
+
return False
|
| 518 |
+
|
| 519 |
+
if isinstance(self, SparseNDimArray) and isinstance(other, SparseNDimArray):
|
| 520 |
+
return dict(self._sparse_array) == dict(other._sparse_array)
|
| 521 |
+
|
| 522 |
+
return list(self) == list(other)
|
| 523 |
+
|
| 524 |
+
def __ne__(self, other):
|
| 525 |
+
return not self == other
|
| 526 |
+
|
| 527 |
+
def _eval_transpose(self):
|
| 528 |
+
if self.rank() != 2:
|
| 529 |
+
raise ValueError("array rank not 2")
|
| 530 |
+
from .arrayop import permutedims
|
| 531 |
+
return permutedims(self, (1, 0))
|
| 532 |
+
|
| 533 |
+
def transpose(self):
|
| 534 |
+
return self._eval_transpose()
|
| 535 |
+
|
| 536 |
+
def _eval_conjugate(self):
|
| 537 |
+
from sympy.tensor.array.arrayop import Flatten
|
| 538 |
+
|
| 539 |
+
return self.func([i.conjugate() for i in Flatten(self)], self.shape)
|
| 540 |
+
|
| 541 |
+
def conjugate(self):
|
| 542 |
+
return self._eval_conjugate()
|
| 543 |
+
|
| 544 |
+
def _eval_adjoint(self):
|
| 545 |
+
return self.transpose().conjugate()
|
| 546 |
+
|
| 547 |
+
def adjoint(self):
|
| 548 |
+
return self._eval_adjoint()
|
| 549 |
+
|
| 550 |
+
def _slice_expand(self, s, dim):
|
| 551 |
+
if not isinstance(s, slice):
|
| 552 |
+
return (s,)
|
| 553 |
+
start, stop, step = s.indices(dim)
|
| 554 |
+
return [start + i*step for i in range((stop-start)//step)]
|
| 555 |
+
|
| 556 |
+
def _get_slice_data_for_array_access(self, index):
|
| 557 |
+
sl_factors = [self._slice_expand(i, dim) for (i, dim) in zip(index, self.shape)]
|
| 558 |
+
eindices = itertools.product(*sl_factors)
|
| 559 |
+
return sl_factors, eindices
|
| 560 |
+
|
| 561 |
+
def _get_slice_data_for_array_assignment(self, index, value):
|
| 562 |
+
if not isinstance(value, NDimArray):
|
| 563 |
+
value = type(self)(value)
|
| 564 |
+
sl_factors, eindices = self._get_slice_data_for_array_access(index)
|
| 565 |
+
slice_offsets = [min(i) if isinstance(i, list) else None for i in sl_factors]
|
| 566 |
+
# TODO: add checks for dimensions for `value`?
|
| 567 |
+
return value, eindices, slice_offsets
|
| 568 |
+
|
| 569 |
+
@classmethod
|
| 570 |
+
def _check_special_bounds(cls, flat_list, shape):
|
| 571 |
+
if shape == () and len(flat_list) != 1:
|
| 572 |
+
raise ValueError("arrays without shape need one scalar value")
|
| 573 |
+
if shape == (0,) and len(flat_list) > 0:
|
| 574 |
+
raise ValueError("if array shape is (0,) there cannot be elements")
|
| 575 |
+
|
| 576 |
+
def _check_index_for_getitem(self, index):
|
| 577 |
+
if isinstance(index, (SYMPY_INTS, Integer, slice)):
|
| 578 |
+
index = (index,)
|
| 579 |
+
|
| 580 |
+
if len(index) < self.rank():
|
| 581 |
+
index = tuple(index) + \
|
| 582 |
+
tuple(slice(None) for i in range(len(index), self.rank()))
|
| 583 |
+
|
| 584 |
+
if len(index) > self.rank():
|
| 585 |
+
raise ValueError('Dimension of index greater than rank of array')
|
| 586 |
+
|
| 587 |
+
return index
|
| 588 |
+
|
| 589 |
+
|
| 590 |
+
class ImmutableNDimArray(NDimArray, Basic):
|
| 591 |
+
_op_priority = 11.0
|
| 592 |
+
|
| 593 |
+
def __hash__(self):
|
| 594 |
+
return Basic.__hash__(self)
|
| 595 |
+
|
| 596 |
+
def as_immutable(self):
|
| 597 |
+
return self
|
| 598 |
+
|
| 599 |
+
def as_mutable(self):
|
| 600 |
+
raise NotImplementedError("abstract method")
|
evalkit_internvl/lib/python3.10/site-packages/sympy/tensor/array/sparse_ndim_array.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.basic import Basic
|
| 2 |
+
from sympy.core.containers import (Dict, Tuple)
|
| 3 |
+
from sympy.core.singleton import S
|
| 4 |
+
from sympy.core.sympify import _sympify
|
| 5 |
+
from sympy.tensor.array.mutable_ndim_array import MutableNDimArray
|
| 6 |
+
from sympy.tensor.array.ndim_array import NDimArray, ImmutableNDimArray
|
| 7 |
+
from sympy.utilities.iterables import flatten
|
| 8 |
+
|
| 9 |
+
import functools
|
| 10 |
+
|
| 11 |
+
class SparseNDimArray(NDimArray):
|
| 12 |
+
|
| 13 |
+
def __new__(self, *args, **kwargs):
|
| 14 |
+
return ImmutableSparseNDimArray(*args, **kwargs)
|
| 15 |
+
|
| 16 |
+
def __getitem__(self, index):
|
| 17 |
+
"""
|
| 18 |
+
Get an element from a sparse N-dim array.
|
| 19 |
+
|
| 20 |
+
Examples
|
| 21 |
+
========
|
| 22 |
+
|
| 23 |
+
>>> from sympy import MutableSparseNDimArray
|
| 24 |
+
>>> a = MutableSparseNDimArray(range(4), (2, 2))
|
| 25 |
+
>>> a
|
| 26 |
+
[[0, 1], [2, 3]]
|
| 27 |
+
>>> a[0, 0]
|
| 28 |
+
0
|
| 29 |
+
>>> a[1, 1]
|
| 30 |
+
3
|
| 31 |
+
>>> a[0]
|
| 32 |
+
[0, 1]
|
| 33 |
+
>>> a[1]
|
| 34 |
+
[2, 3]
|
| 35 |
+
|
| 36 |
+
Symbolic indexing:
|
| 37 |
+
|
| 38 |
+
>>> from sympy.abc import i, j
|
| 39 |
+
>>> a[i, j]
|
| 40 |
+
[[0, 1], [2, 3]][i, j]
|
| 41 |
+
|
| 42 |
+
Replace `i` and `j` to get element `(0, 0)`:
|
| 43 |
+
|
| 44 |
+
>>> a[i, j].subs({i: 0, j: 0})
|
| 45 |
+
0
|
| 46 |
+
|
| 47 |
+
"""
|
| 48 |
+
syindex = self._check_symbolic_index(index)
|
| 49 |
+
if syindex is not None:
|
| 50 |
+
return syindex
|
| 51 |
+
|
| 52 |
+
index = self._check_index_for_getitem(index)
|
| 53 |
+
|
| 54 |
+
# `index` is a tuple with one or more slices:
|
| 55 |
+
if isinstance(index, tuple) and any(isinstance(i, slice) for i in index):
|
| 56 |
+
sl_factors, eindices = self._get_slice_data_for_array_access(index)
|
| 57 |
+
array = [self._sparse_array.get(self._parse_index(i), S.Zero) for i in eindices]
|
| 58 |
+
nshape = [len(el) for i, el in enumerate(sl_factors) if isinstance(index[i], slice)]
|
| 59 |
+
return type(self)(array, nshape)
|
| 60 |
+
else:
|
| 61 |
+
index = self._parse_index(index)
|
| 62 |
+
return self._sparse_array.get(index, S.Zero)
|
| 63 |
+
|
| 64 |
+
@classmethod
|
| 65 |
+
def zeros(cls, *shape):
|
| 66 |
+
"""
|
| 67 |
+
Return a sparse N-dim array of zeros.
|
| 68 |
+
"""
|
| 69 |
+
return cls({}, shape)
|
| 70 |
+
|
| 71 |
+
def tomatrix(self):
|
| 72 |
+
"""
|
| 73 |
+
Converts MutableDenseNDimArray to Matrix. Can convert only 2-dim array, else will raise error.
|
| 74 |
+
|
| 75 |
+
Examples
|
| 76 |
+
========
|
| 77 |
+
|
| 78 |
+
>>> from sympy import MutableSparseNDimArray
|
| 79 |
+
>>> a = MutableSparseNDimArray([1 for i in range(9)], (3, 3))
|
| 80 |
+
>>> b = a.tomatrix()
|
| 81 |
+
>>> b
|
| 82 |
+
Matrix([
|
| 83 |
+
[1, 1, 1],
|
| 84 |
+
[1, 1, 1],
|
| 85 |
+
[1, 1, 1]])
|
| 86 |
+
"""
|
| 87 |
+
from sympy.matrices import SparseMatrix
|
| 88 |
+
if self.rank() != 2:
|
| 89 |
+
raise ValueError('Dimensions must be of size of 2')
|
| 90 |
+
|
| 91 |
+
mat_sparse = {}
|
| 92 |
+
for key, value in self._sparse_array.items():
|
| 93 |
+
mat_sparse[self._get_tuple_index(key)] = value
|
| 94 |
+
|
| 95 |
+
return SparseMatrix(self.shape[0], self.shape[1], mat_sparse)
|
| 96 |
+
|
| 97 |
+
def reshape(self, *newshape):
|
| 98 |
+
new_total_size = functools.reduce(lambda x,y: x*y, newshape)
|
| 99 |
+
if new_total_size != self._loop_size:
|
| 100 |
+
raise ValueError("Invalid reshape parameters " + newshape)
|
| 101 |
+
|
| 102 |
+
return type(self)(self._sparse_array, newshape)
|
| 103 |
+
|
| 104 |
+
class ImmutableSparseNDimArray(SparseNDimArray, ImmutableNDimArray): # type: ignore
|
| 105 |
+
|
| 106 |
+
def __new__(cls, iterable=None, shape=None, **kwargs):
|
| 107 |
+
shape, flat_list = cls._handle_ndarray_creation_inputs(iterable, shape, **kwargs)
|
| 108 |
+
shape = Tuple(*map(_sympify, shape))
|
| 109 |
+
cls._check_special_bounds(flat_list, shape)
|
| 110 |
+
loop_size = functools.reduce(lambda x,y: x*y, shape) if shape else len(flat_list)
|
| 111 |
+
|
| 112 |
+
# Sparse array:
|
| 113 |
+
if isinstance(flat_list, (dict, Dict)):
|
| 114 |
+
sparse_array = Dict(flat_list)
|
| 115 |
+
else:
|
| 116 |
+
sparse_array = {}
|
| 117 |
+
for i, el in enumerate(flatten(flat_list)):
|
| 118 |
+
if el != 0:
|
| 119 |
+
sparse_array[i] = _sympify(el)
|
| 120 |
+
|
| 121 |
+
sparse_array = Dict(sparse_array)
|
| 122 |
+
|
| 123 |
+
self = Basic.__new__(cls, sparse_array, shape, **kwargs)
|
| 124 |
+
self._shape = shape
|
| 125 |
+
self._rank = len(shape)
|
| 126 |
+
self._loop_size = loop_size
|
| 127 |
+
self._sparse_array = sparse_array
|
| 128 |
+
|
| 129 |
+
return self
|
| 130 |
+
|
| 131 |
+
def __setitem__(self, index, value):
|
| 132 |
+
raise TypeError("immutable N-dim array")
|
| 133 |
+
|
| 134 |
+
def as_mutable(self):
|
| 135 |
+
return MutableSparseNDimArray(self)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
class MutableSparseNDimArray(MutableNDimArray, SparseNDimArray):
|
| 139 |
+
|
| 140 |
+
def __new__(cls, iterable=None, shape=None, **kwargs):
|
| 141 |
+
shape, flat_list = cls._handle_ndarray_creation_inputs(iterable, shape, **kwargs)
|
| 142 |
+
self = object.__new__(cls)
|
| 143 |
+
self._shape = shape
|
| 144 |
+
self._rank = len(shape)
|
| 145 |
+
self._loop_size = functools.reduce(lambda x,y: x*y, shape) if shape else len(flat_list)
|
| 146 |
+
|
| 147 |
+
# Sparse array:
|
| 148 |
+
if isinstance(flat_list, (dict, Dict)):
|
| 149 |
+
self._sparse_array = dict(flat_list)
|
| 150 |
+
return self
|
| 151 |
+
|
| 152 |
+
self._sparse_array = {}
|
| 153 |
+
|
| 154 |
+
for i, el in enumerate(flatten(flat_list)):
|
| 155 |
+
if el != 0:
|
| 156 |
+
self._sparse_array[i] = _sympify(el)
|
| 157 |
+
|
| 158 |
+
return self
|
| 159 |
+
|
| 160 |
+
def __setitem__(self, index, value):
|
| 161 |
+
"""Allows to set items to MutableDenseNDimArray.
|
| 162 |
+
|
| 163 |
+
Examples
|
| 164 |
+
========
|
| 165 |
+
|
| 166 |
+
>>> from sympy import MutableSparseNDimArray
|
| 167 |
+
>>> a = MutableSparseNDimArray.zeros(2, 2)
|
| 168 |
+
>>> a[0, 0] = 1
|
| 169 |
+
>>> a[1, 1] = 1
|
| 170 |
+
>>> a
|
| 171 |
+
[[1, 0], [0, 1]]
|
| 172 |
+
"""
|
| 173 |
+
if isinstance(index, tuple) and any(isinstance(i, slice) for i in index):
|
| 174 |
+
value, eindices, slice_offsets = self._get_slice_data_for_array_assignment(index, value)
|
| 175 |
+
for i in eindices:
|
| 176 |
+
other_i = [ind - j for ind, j in zip(i, slice_offsets) if j is not None]
|
| 177 |
+
other_value = value[other_i]
|
| 178 |
+
complete_index = self._parse_index(i)
|
| 179 |
+
if other_value != 0:
|
| 180 |
+
self._sparse_array[complete_index] = other_value
|
| 181 |
+
elif complete_index in self._sparse_array:
|
| 182 |
+
self._sparse_array.pop(complete_index)
|
| 183 |
+
else:
|
| 184 |
+
index = self._parse_index(index)
|
| 185 |
+
value = _sympify(value)
|
| 186 |
+
if value == 0 and index in self._sparse_array:
|
| 187 |
+
self._sparse_array.pop(index)
|
| 188 |
+
else:
|
| 189 |
+
self._sparse_array[index] = value
|
| 190 |
+
|
| 191 |
+
def as_immutable(self):
|
| 192 |
+
return ImmutableSparseNDimArray(self)
|
| 193 |
+
|
| 194 |
+
@property
|
| 195 |
+
def free_symbols(self):
|
| 196 |
+
return {i for j in self._sparse_array.values() for i in j.free_symbols}
|
evalkit_internvl/lib/python3.10/site-packages/sympy/tensor/array/tests/__init__.py
ADDED
|
File without changes
|
evalkit_internvl/lib/python3.10/site-packages/sympy/tensor/array/tests/test_array_comprehension.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.tensor.array.array_comprehension import ArrayComprehension, ArrayComprehensionMap
|
| 2 |
+
from sympy.tensor.array import ImmutableDenseNDimArray
|
| 3 |
+
from sympy.abc import i, j, k, l
|
| 4 |
+
from sympy.testing.pytest import raises
|
| 5 |
+
from sympy.matrices import Matrix
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def test_array_comprehension():
|
| 9 |
+
a = ArrayComprehension(i*j, (i, 1, 3), (j, 2, 4))
|
| 10 |
+
b = ArrayComprehension(i, (i, 1, j+1))
|
| 11 |
+
c = ArrayComprehension(i+j+k+l, (i, 1, 2), (j, 1, 3), (k, 1, 4), (l, 1, 5))
|
| 12 |
+
d = ArrayComprehension(k, (i, 1, 5))
|
| 13 |
+
e = ArrayComprehension(i, (j, k+1, k+5))
|
| 14 |
+
assert a.doit().tolist() == [[2, 3, 4], [4, 6, 8], [6, 9, 12]]
|
| 15 |
+
assert a.shape == (3, 3)
|
| 16 |
+
assert a.is_shape_numeric == True
|
| 17 |
+
assert a.tolist() == [[2, 3, 4], [4, 6, 8], [6, 9, 12]]
|
| 18 |
+
assert a.tomatrix() == Matrix([
|
| 19 |
+
[2, 3, 4],
|
| 20 |
+
[4, 6, 8],
|
| 21 |
+
[6, 9, 12]])
|
| 22 |
+
assert len(a) == 9
|
| 23 |
+
assert isinstance(b.doit(), ArrayComprehension)
|
| 24 |
+
assert isinstance(a.doit(), ImmutableDenseNDimArray)
|
| 25 |
+
assert b.subs(j, 3) == ArrayComprehension(i, (i, 1, 4))
|
| 26 |
+
assert b.free_symbols == {j}
|
| 27 |
+
assert b.shape == (j + 1,)
|
| 28 |
+
assert b.rank() == 1
|
| 29 |
+
assert b.is_shape_numeric == False
|
| 30 |
+
assert c.free_symbols == set()
|
| 31 |
+
assert c.function == i + j + k + l
|
| 32 |
+
assert c.limits == ((i, 1, 2), (j, 1, 3), (k, 1, 4), (l, 1, 5))
|
| 33 |
+
assert c.doit().tolist() == [[[[4, 5, 6, 7, 8], [5, 6, 7, 8, 9], [6, 7, 8, 9, 10], [7, 8, 9, 10, 11]],
|
| 34 |
+
[[5, 6, 7, 8, 9], [6, 7, 8, 9, 10], [7, 8, 9, 10, 11], [8, 9, 10, 11, 12]],
|
| 35 |
+
[[6, 7, 8, 9, 10], [7, 8, 9, 10, 11], [8, 9, 10, 11, 12], [9, 10, 11, 12, 13]]],
|
| 36 |
+
[[[5, 6, 7, 8, 9], [6, 7, 8, 9, 10], [7, 8, 9, 10, 11], [8, 9, 10, 11, 12]],
|
| 37 |
+
[[6, 7, 8, 9, 10], [7, 8, 9, 10, 11], [8, 9, 10, 11, 12], [9, 10, 11, 12, 13]],
|
| 38 |
+
[[7, 8, 9, 10, 11], [8, 9, 10, 11, 12], [9, 10, 11, 12, 13], [10, 11, 12, 13, 14]]]]
|
| 39 |
+
assert c.free_symbols == set()
|
| 40 |
+
assert c.variables == [i, j, k, l]
|
| 41 |
+
assert c.bound_symbols == [i, j, k, l]
|
| 42 |
+
assert d.doit().tolist() == [k, k, k, k, k]
|
| 43 |
+
assert len(e) == 5
|
| 44 |
+
raises(TypeError, lambda: ArrayComprehension(i*j, (i, 1, 3), (j, 2, [1, 3, 2])))
|
| 45 |
+
raises(ValueError, lambda: ArrayComprehension(i*j, (i, 1, 3), (j, 2, 1)))
|
| 46 |
+
raises(ValueError, lambda: ArrayComprehension(i*j, (i, 1, 3), (j, 2, j+1)))
|
| 47 |
+
raises(ValueError, lambda: len(ArrayComprehension(i*j, (i, 1, 3), (j, 2, j+4))))
|
| 48 |
+
raises(TypeError, lambda: ArrayComprehension(i*j, (i, 0, i + 1.5), (j, 0, 2)))
|
| 49 |
+
raises(ValueError, lambda: b.tolist())
|
| 50 |
+
raises(ValueError, lambda: b.tomatrix())
|
| 51 |
+
raises(ValueError, lambda: c.tomatrix())
|
| 52 |
+
|
| 53 |
+
def test_arraycomprehensionmap():
|
| 54 |
+
a = ArrayComprehensionMap(lambda i: i+1, (i, 1, 5))
|
| 55 |
+
assert a.doit().tolist() == [2, 3, 4, 5, 6]
|
| 56 |
+
assert a.shape == (5,)
|
| 57 |
+
assert a.is_shape_numeric
|
| 58 |
+
assert a.tolist() == [2, 3, 4, 5, 6]
|
| 59 |
+
assert len(a) == 5
|
| 60 |
+
assert isinstance(a.doit(), ImmutableDenseNDimArray)
|
| 61 |
+
expr = ArrayComprehensionMap(lambda i: i+1, (i, 1, k))
|
| 62 |
+
assert expr.doit() == expr
|
| 63 |
+
assert expr.subs(k, 4) == ArrayComprehensionMap(lambda i: i+1, (i, 1, 4))
|
| 64 |
+
assert expr.subs(k, 4).doit() == ImmutableDenseNDimArray([2, 3, 4, 5])
|
| 65 |
+
b = ArrayComprehensionMap(lambda i: i+1, (i, 1, 2), (i, 1, 3), (i, 1, 4), (i, 1, 5))
|
| 66 |
+
assert b.doit().tolist() == [[[[2, 3, 4, 5, 6], [3, 5, 7, 9, 11], [4, 7, 10, 13, 16], [5, 9, 13, 17, 21]],
|
| 67 |
+
[[3, 5, 7, 9, 11], [5, 9, 13, 17, 21], [7, 13, 19, 25, 31], [9, 17, 25, 33, 41]],
|
| 68 |
+
[[4, 7, 10, 13, 16], [7, 13, 19, 25, 31], [10, 19, 28, 37, 46], [13, 25, 37, 49, 61]]],
|
| 69 |
+
[[[3, 5, 7, 9, 11], [5, 9, 13, 17, 21], [7, 13, 19, 25, 31], [9, 17, 25, 33, 41]],
|
| 70 |
+
[[5, 9, 13, 17, 21], [9, 17, 25, 33, 41], [13, 25, 37, 49, 61], [17, 33, 49, 65, 81]],
|
| 71 |
+
[[7, 13, 19, 25, 31], [13, 25, 37, 49, 61], [19, 37, 55, 73, 91], [25, 49, 73, 97, 121]]]]
|
| 72 |
+
|
| 73 |
+
# tests about lambda expression
|
| 74 |
+
assert ArrayComprehensionMap(lambda: 3, (i, 1, 5)).doit().tolist() == [3, 3, 3, 3, 3]
|
| 75 |
+
assert ArrayComprehensionMap(lambda i: i+1, (i, 1, 5)).doit().tolist() == [2, 3, 4, 5, 6]
|
| 76 |
+
raises(ValueError, lambda: ArrayComprehensionMap(i*j, (i, 1, 3), (j, 2, 4)))
|
| 77 |
+
a = ArrayComprehensionMap(lambda i, j: i+j, (i, 1, 5))
|
| 78 |
+
raises(ValueError, lambda: a.doit())
|
evalkit_internvl/lib/python3.10/site-packages/sympy/tensor/array/tests/test_arrayop.py
ADDED
|
@@ -0,0 +1,361 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import itertools
|
| 2 |
+
import random
|
| 3 |
+
|
| 4 |
+
from sympy.combinatorics import Permutation
|
| 5 |
+
from sympy.combinatorics.permutations import _af_invert
|
| 6 |
+
from sympy.testing.pytest import raises
|
| 7 |
+
|
| 8 |
+
from sympy.core.function import diff
|
| 9 |
+
from sympy.core.symbol import symbols
|
| 10 |
+
from sympy.functions.elementary.complexes import (adjoint, conjugate, transpose)
|
| 11 |
+
from sympy.functions.elementary.exponential import (exp, log)
|
| 12 |
+
from sympy.functions.elementary.trigonometric import (cos, sin)
|
| 13 |
+
from sympy.tensor.array import Array, ImmutableDenseNDimArray, ImmutableSparseNDimArray, MutableSparseNDimArray
|
| 14 |
+
|
| 15 |
+
from sympy.tensor.array.arrayop import tensorproduct, tensorcontraction, derive_by_array, permutedims, Flatten, \
|
| 16 |
+
tensordiagonal
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def test_import_NDimArray():
|
| 20 |
+
from sympy.tensor.array import NDimArray
|
| 21 |
+
del NDimArray
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def test_tensorproduct():
|
| 25 |
+
x,y,z,t = symbols('x y z t')
|
| 26 |
+
from sympy.abc import a,b,c,d
|
| 27 |
+
assert tensorproduct() == 1
|
| 28 |
+
assert tensorproduct([x]) == Array([x])
|
| 29 |
+
assert tensorproduct([x], [y]) == Array([[x*y]])
|
| 30 |
+
assert tensorproduct([x], [y], [z]) == Array([[[x*y*z]]])
|
| 31 |
+
assert tensorproduct([x], [y], [z], [t]) == Array([[[[x*y*z*t]]]])
|
| 32 |
+
|
| 33 |
+
assert tensorproduct(x) == x
|
| 34 |
+
assert tensorproduct(x, y) == x*y
|
| 35 |
+
assert tensorproduct(x, y, z) == x*y*z
|
| 36 |
+
assert tensorproduct(x, y, z, t) == x*y*z*t
|
| 37 |
+
|
| 38 |
+
for ArrayType in [ImmutableDenseNDimArray, ImmutableSparseNDimArray]:
|
| 39 |
+
A = ArrayType([x, y])
|
| 40 |
+
B = ArrayType([1, 2, 3])
|
| 41 |
+
C = ArrayType([a, b, c, d])
|
| 42 |
+
|
| 43 |
+
assert tensorproduct(A, B, C) == ArrayType([[[a*x, b*x, c*x, d*x], [2*a*x, 2*b*x, 2*c*x, 2*d*x], [3*a*x, 3*b*x, 3*c*x, 3*d*x]],
|
| 44 |
+
[[a*y, b*y, c*y, d*y], [2*a*y, 2*b*y, 2*c*y, 2*d*y], [3*a*y, 3*b*y, 3*c*y, 3*d*y]]])
|
| 45 |
+
|
| 46 |
+
assert tensorproduct([x, y], [1, 2, 3]) == tensorproduct(A, B)
|
| 47 |
+
|
| 48 |
+
assert tensorproduct(A, 2) == ArrayType([2*x, 2*y])
|
| 49 |
+
assert tensorproduct(A, [2]) == ArrayType([[2*x], [2*y]])
|
| 50 |
+
assert tensorproduct([2], A) == ArrayType([[2*x, 2*y]])
|
| 51 |
+
assert tensorproduct(a, A) == ArrayType([a*x, a*y])
|
| 52 |
+
assert tensorproduct(a, A, B) == ArrayType([[a*x, 2*a*x, 3*a*x], [a*y, 2*a*y, 3*a*y]])
|
| 53 |
+
assert tensorproduct(A, B, a) == ArrayType([[a*x, 2*a*x, 3*a*x], [a*y, 2*a*y, 3*a*y]])
|
| 54 |
+
assert tensorproduct(B, a, A) == ArrayType([[a*x, a*y], [2*a*x, 2*a*y], [3*a*x, 3*a*y]])
|
| 55 |
+
|
| 56 |
+
# tests for large scale sparse array
|
| 57 |
+
for SparseArrayType in [ImmutableSparseNDimArray, MutableSparseNDimArray]:
|
| 58 |
+
a = SparseArrayType({1:2, 3:4},(1000, 2000))
|
| 59 |
+
b = SparseArrayType({1:2, 3:4},(1000, 2000))
|
| 60 |
+
assert tensorproduct(a, b) == ImmutableSparseNDimArray({2000001: 4, 2000003: 8, 6000001: 8, 6000003: 16}, (1000, 2000, 1000, 2000))
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def test_tensorcontraction():
|
| 64 |
+
from sympy.abc import a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x
|
| 65 |
+
B = Array(range(18), (2, 3, 3))
|
| 66 |
+
assert tensorcontraction(B, (1, 2)) == Array([12, 39])
|
| 67 |
+
C1 = Array([a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x], (2, 3, 2, 2))
|
| 68 |
+
|
| 69 |
+
assert tensorcontraction(C1, (0, 2)) == Array([[a + o, b + p], [e + s, f + t], [i + w, j + x]])
|
| 70 |
+
assert tensorcontraction(C1, (0, 2, 3)) == Array([a + p, e + t, i + x])
|
| 71 |
+
assert tensorcontraction(C1, (2, 3)) == Array([[a + d, e + h, i + l], [m + p, q + t, u + x]])
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def test_derivative_by_array():
|
| 75 |
+
from sympy.abc import i, j, t, x, y, z
|
| 76 |
+
|
| 77 |
+
bexpr = x*y**2*exp(z)*log(t)
|
| 78 |
+
sexpr = sin(bexpr)
|
| 79 |
+
cexpr = cos(bexpr)
|
| 80 |
+
|
| 81 |
+
a = Array([sexpr])
|
| 82 |
+
|
| 83 |
+
assert derive_by_array(sexpr, t) == x*y**2*exp(z)*cos(x*y**2*exp(z)*log(t))/t
|
| 84 |
+
assert derive_by_array(sexpr, [x, y, z]) == Array([bexpr/x*cexpr, 2*y*bexpr/y**2*cexpr, bexpr*cexpr])
|
| 85 |
+
assert derive_by_array(a, [x, y, z]) == Array([[bexpr/x*cexpr], [2*y*bexpr/y**2*cexpr], [bexpr*cexpr]])
|
| 86 |
+
|
| 87 |
+
assert derive_by_array(sexpr, [[x, y], [z, t]]) == Array([[bexpr/x*cexpr, 2*y*bexpr/y**2*cexpr], [bexpr*cexpr, bexpr/log(t)/t*cexpr]])
|
| 88 |
+
assert derive_by_array(a, [[x, y], [z, t]]) == Array([[[bexpr/x*cexpr], [2*y*bexpr/y**2*cexpr]], [[bexpr*cexpr], [bexpr/log(t)/t*cexpr]]])
|
| 89 |
+
assert derive_by_array([[x, y], [z, t]], [x, y]) == Array([[[1, 0], [0, 0]], [[0, 1], [0, 0]]])
|
| 90 |
+
assert derive_by_array([[x, y], [z, t]], [[x, y], [z, t]]) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]],
|
| 91 |
+
[[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
|
| 92 |
+
|
| 93 |
+
assert diff(sexpr, t) == x*y**2*exp(z)*cos(x*y**2*exp(z)*log(t))/t
|
| 94 |
+
assert diff(sexpr, Array([x, y, z])) == Array([bexpr/x*cexpr, 2*y*bexpr/y**2*cexpr, bexpr*cexpr])
|
| 95 |
+
assert diff(a, Array([x, y, z])) == Array([[bexpr/x*cexpr], [2*y*bexpr/y**2*cexpr], [bexpr*cexpr]])
|
| 96 |
+
|
| 97 |
+
assert diff(sexpr, Array([[x, y], [z, t]])) == Array([[bexpr/x*cexpr, 2*y*bexpr/y**2*cexpr], [bexpr*cexpr, bexpr/log(t)/t*cexpr]])
|
| 98 |
+
assert diff(a, Array([[x, y], [z, t]])) == Array([[[bexpr/x*cexpr], [2*y*bexpr/y**2*cexpr]], [[bexpr*cexpr], [bexpr/log(t)/t*cexpr]]])
|
| 99 |
+
assert diff(Array([[x, y], [z, t]]), Array([x, y])) == Array([[[1, 0], [0, 0]], [[0, 1], [0, 0]]])
|
| 100 |
+
assert diff(Array([[x, y], [z, t]]), Array([[x, y], [z, t]])) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]],
|
| 101 |
+
[[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
|
| 102 |
+
|
| 103 |
+
# test for large scale sparse array
|
| 104 |
+
for SparseArrayType in [ImmutableSparseNDimArray, MutableSparseNDimArray]:
|
| 105 |
+
b = MutableSparseNDimArray({0:i, 1:j}, (10000, 20000))
|
| 106 |
+
assert derive_by_array(b, i) == ImmutableSparseNDimArray({0: 1}, (10000, 20000))
|
| 107 |
+
assert derive_by_array(b, (i, j)) == ImmutableSparseNDimArray({0: 1, 200000001: 1}, (2, 10000, 20000))
|
| 108 |
+
|
| 109 |
+
#https://github.com/sympy/sympy/issues/20655
|
| 110 |
+
U = Array([x, y, z])
|
| 111 |
+
E = 2
|
| 112 |
+
assert derive_by_array(E, U) == ImmutableDenseNDimArray([0, 0, 0])
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def test_issue_emerged_while_discussing_10972():
|
| 116 |
+
ua = Array([-1,0])
|
| 117 |
+
Fa = Array([[0, 1], [-1, 0]])
|
| 118 |
+
po = tensorproduct(Fa, ua, Fa, ua)
|
| 119 |
+
assert tensorcontraction(po, (1, 2), (4, 5)) == Array([[0, 0], [0, 1]])
|
| 120 |
+
|
| 121 |
+
sa = symbols('a0:144')
|
| 122 |
+
po = Array(sa, [2, 2, 3, 3, 2, 2])
|
| 123 |
+
assert tensorcontraction(po, (0, 1), (2, 3), (4, 5)) == sa[0] + sa[108] + sa[111] + sa[124] + sa[127] + sa[140] + sa[143] + sa[16] + sa[19] + sa[3] + sa[32] + sa[35]
|
| 124 |
+
assert tensorcontraction(po, (0, 1, 4, 5), (2, 3)) == sa[0] + sa[111] + sa[127] + sa[143] + sa[16] + sa[32]
|
| 125 |
+
assert tensorcontraction(po, (0, 1), (4, 5)) == Array([[sa[0] + sa[108] + sa[111] + sa[3], sa[112] + sa[115] + sa[4] + sa[7],
|
| 126 |
+
sa[11] + sa[116] + sa[119] + sa[8]], [sa[12] + sa[120] + sa[123] + sa[15],
|
| 127 |
+
sa[124] + sa[127] + sa[16] + sa[19], sa[128] + sa[131] + sa[20] + sa[23]],
|
| 128 |
+
[sa[132] + sa[135] + sa[24] + sa[27], sa[136] + sa[139] + sa[28] + sa[31],
|
| 129 |
+
sa[140] + sa[143] + sa[32] + sa[35]]])
|
| 130 |
+
assert tensorcontraction(po, (0, 1), (2, 3)) == Array([[sa[0] + sa[108] + sa[124] + sa[140] + sa[16] + sa[32], sa[1] + sa[109] + sa[125] + sa[141] + sa[17] + sa[33]],
|
| 131 |
+
[sa[110] + sa[126] + sa[142] + sa[18] + sa[2] + sa[34], sa[111] + sa[127] + sa[143] + sa[19] + sa[3] + sa[35]]])
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def test_array_permutedims():
|
| 135 |
+
sa = symbols('a0:144')
|
| 136 |
+
|
| 137 |
+
for ArrayType in [ImmutableDenseNDimArray, ImmutableSparseNDimArray]:
|
| 138 |
+
m1 = ArrayType(sa[:6], (2, 3))
|
| 139 |
+
assert permutedims(m1, (1, 0)) == transpose(m1)
|
| 140 |
+
assert m1.tomatrix().T == permutedims(m1, (1, 0)).tomatrix()
|
| 141 |
+
|
| 142 |
+
assert m1.tomatrix().T == transpose(m1).tomatrix()
|
| 143 |
+
assert m1.tomatrix().C == conjugate(m1).tomatrix()
|
| 144 |
+
assert m1.tomatrix().H == adjoint(m1).tomatrix()
|
| 145 |
+
|
| 146 |
+
assert m1.tomatrix().T == m1.transpose().tomatrix()
|
| 147 |
+
assert m1.tomatrix().C == m1.conjugate().tomatrix()
|
| 148 |
+
assert m1.tomatrix().H == m1.adjoint().tomatrix()
|
| 149 |
+
|
| 150 |
+
raises(ValueError, lambda: permutedims(m1, (0,)))
|
| 151 |
+
raises(ValueError, lambda: permutedims(m1, (0, 0)))
|
| 152 |
+
raises(ValueError, lambda: permutedims(m1, (1, 2, 0)))
|
| 153 |
+
|
| 154 |
+
# Some tests with random arrays:
|
| 155 |
+
dims = 6
|
| 156 |
+
shape = [random.randint(1,5) for i in range(dims)]
|
| 157 |
+
elems = [random.random() for i in range(tensorproduct(*shape))]
|
| 158 |
+
ra = ArrayType(elems, shape)
|
| 159 |
+
perm = list(range(dims))
|
| 160 |
+
# Randomize the permutation:
|
| 161 |
+
random.shuffle(perm)
|
| 162 |
+
# Test inverse permutation:
|
| 163 |
+
assert permutedims(permutedims(ra, perm), _af_invert(perm)) == ra
|
| 164 |
+
# Test that permuted shape corresponds to action by `Permutation`:
|
| 165 |
+
assert permutedims(ra, perm).shape == tuple(Permutation(perm)(shape))
|
| 166 |
+
|
| 167 |
+
z = ArrayType.zeros(4,5,6,7)
|
| 168 |
+
|
| 169 |
+
assert permutedims(z, (2, 3, 1, 0)).shape == (6, 7, 5, 4)
|
| 170 |
+
assert permutedims(z, [2, 3, 1, 0]).shape == (6, 7, 5, 4)
|
| 171 |
+
assert permutedims(z, Permutation([2, 3, 1, 0])).shape == (6, 7, 5, 4)
|
| 172 |
+
|
| 173 |
+
po = ArrayType(sa, [2, 2, 3, 3, 2, 2])
|
| 174 |
+
|
| 175 |
+
raises(ValueError, lambda: permutedims(po, (1, 1)))
|
| 176 |
+
raises(ValueError, lambda: po.transpose())
|
| 177 |
+
raises(ValueError, lambda: po.adjoint())
|
| 178 |
+
|
| 179 |
+
assert permutedims(po, reversed(range(po.rank()))) == ArrayType(
|
| 180 |
+
[[[[[[sa[0], sa[72]], [sa[36], sa[108]]], [[sa[12], sa[84]], [sa[48], sa[120]]], [[sa[24],
|
| 181 |
+
sa[96]], [sa[60], sa[132]]]],
|
| 182 |
+
[[[sa[4], sa[76]], [sa[40], sa[112]]], [[sa[16],
|
| 183 |
+
sa[88]], [sa[52], sa[124]]],
|
| 184 |
+
[[sa[28], sa[100]], [sa[64], sa[136]]]],
|
| 185 |
+
[[[sa[8],
|
| 186 |
+
sa[80]], [sa[44], sa[116]]], [[sa[20], sa[92]], [sa[56], sa[128]]], [[sa[32],
|
| 187 |
+
sa[104]], [sa[68], sa[140]]]]],
|
| 188 |
+
[[[[sa[2], sa[74]], [sa[38], sa[110]]], [[sa[14],
|
| 189 |
+
sa[86]], [sa[50], sa[122]]], [[sa[26], sa[98]], [sa[62], sa[134]]]],
|
| 190 |
+
[[[sa[6],
|
| 191 |
+
sa[78]], [sa[42], sa[114]]], [[sa[18], sa[90]], [sa[54], sa[126]]], [[sa[30],
|
| 192 |
+
sa[102]], [sa[66], sa[138]]]],
|
| 193 |
+
[[[sa[10], sa[82]], [sa[46], sa[118]]], [[sa[22],
|
| 194 |
+
sa[94]], [sa[58], sa[130]]],
|
| 195 |
+
[[sa[34], sa[106]], [sa[70], sa[142]]]]]],
|
| 196 |
+
[[[[[sa[1],
|
| 197 |
+
sa[73]], [sa[37], sa[109]]], [[sa[13], sa[85]], [sa[49], sa[121]]], [[sa[25],
|
| 198 |
+
sa[97]], [sa[61], sa[133]]]],
|
| 199 |
+
[[[sa[5], sa[77]], [sa[41], sa[113]]], [[sa[17],
|
| 200 |
+
sa[89]], [sa[53], sa[125]]],
|
| 201 |
+
[[sa[29], sa[101]], [sa[65], sa[137]]]],
|
| 202 |
+
[[[sa[9],
|
| 203 |
+
sa[81]], [sa[45], sa[117]]], [[sa[21], sa[93]], [sa[57], sa[129]]], [[sa[33],
|
| 204 |
+
sa[105]], [sa[69], sa[141]]]]],
|
| 205 |
+
[[[[sa[3], sa[75]], [sa[39], sa[111]]], [[sa[15],
|
| 206 |
+
sa[87]], [sa[51], sa[123]]], [[sa[27], sa[99]], [sa[63], sa[135]]]],
|
| 207 |
+
[[[sa[7],
|
| 208 |
+
sa[79]], [sa[43], sa[115]]], [[sa[19], sa[91]], [sa[55], sa[127]]], [[sa[31],
|
| 209 |
+
sa[103]], [sa[67], sa[139]]]],
|
| 210 |
+
[[[sa[11], sa[83]], [sa[47], sa[119]]], [[sa[23],
|
| 211 |
+
sa[95]], [sa[59], sa[131]]],
|
| 212 |
+
[[sa[35], sa[107]], [sa[71], sa[143]]]]]]])
|
| 213 |
+
|
| 214 |
+
assert permutedims(po, (1, 0, 2, 3, 4, 5)) == ArrayType(
|
| 215 |
+
[[[[[[sa[0], sa[1]], [sa[2], sa[3]]], [[sa[4], sa[5]], [sa[6], sa[7]]], [[sa[8], sa[9]], [sa[10],
|
| 216 |
+
sa[11]]]],
|
| 217 |
+
[[[sa[12], sa[13]], [sa[14], sa[15]]], [[sa[16], sa[17]], [sa[18],
|
| 218 |
+
sa[19]]], [[sa[20], sa[21]], [sa[22], sa[23]]]],
|
| 219 |
+
[[[sa[24], sa[25]], [sa[26],
|
| 220 |
+
sa[27]]], [[sa[28], sa[29]], [sa[30], sa[31]]], [[sa[32], sa[33]], [sa[34],
|
| 221 |
+
sa[35]]]]],
|
| 222 |
+
[[[[sa[72], sa[73]], [sa[74], sa[75]]], [[sa[76], sa[77]], [sa[78],
|
| 223 |
+
sa[79]]], [[sa[80], sa[81]], [sa[82], sa[83]]]],
|
| 224 |
+
[[[sa[84], sa[85]], [sa[86],
|
| 225 |
+
sa[87]]], [[sa[88], sa[89]], [sa[90], sa[91]]], [[sa[92], sa[93]], [sa[94],
|
| 226 |
+
sa[95]]]],
|
| 227 |
+
[[[sa[96], sa[97]], [sa[98], sa[99]]], [[sa[100], sa[101]], [sa[102],
|
| 228 |
+
sa[103]]],
|
| 229 |
+
[[sa[104], sa[105]], [sa[106], sa[107]]]]]], [[[[[sa[36], sa[37]], [sa[38],
|
| 230 |
+
sa[39]]],
|
| 231 |
+
[[sa[40], sa[41]], [sa[42], sa[43]]],
|
| 232 |
+
[[sa[44], sa[45]], [sa[46],
|
| 233 |
+
sa[47]]]],
|
| 234 |
+
[[[sa[48], sa[49]], [sa[50], sa[51]]],
|
| 235 |
+
[[sa[52], sa[53]], [sa[54],
|
| 236 |
+
sa[55]]],
|
| 237 |
+
[[sa[56], sa[57]], [sa[58], sa[59]]]],
|
| 238 |
+
[[[sa[60], sa[61]], [sa[62],
|
| 239 |
+
sa[63]]],
|
| 240 |
+
[[sa[64], sa[65]], [sa[66], sa[67]]],
|
| 241 |
+
[[sa[68], sa[69]], [sa[70],
|
| 242 |
+
sa[71]]]]], [
|
| 243 |
+
[[[sa[108], sa[109]], [sa[110], sa[111]]],
|
| 244 |
+
[[sa[112], sa[113]], [sa[114],
|
| 245 |
+
sa[115]]],
|
| 246 |
+
[[sa[116], sa[117]], [sa[118], sa[119]]]],
|
| 247 |
+
[[[sa[120], sa[121]], [sa[122],
|
| 248 |
+
sa[123]]],
|
| 249 |
+
[[sa[124], sa[125]], [sa[126], sa[127]]],
|
| 250 |
+
[[sa[128], sa[129]], [sa[130],
|
| 251 |
+
sa[131]]]],
|
| 252 |
+
[[[sa[132], sa[133]], [sa[134], sa[135]]],
|
| 253 |
+
[[sa[136], sa[137]], [sa[138],
|
| 254 |
+
sa[139]]],
|
| 255 |
+
[[sa[140], sa[141]], [sa[142], sa[143]]]]]]])
|
| 256 |
+
|
| 257 |
+
assert permutedims(po, (0, 2, 1, 4, 3, 5)) == ArrayType(
|
| 258 |
+
[[[[[[sa[0], sa[1]], [sa[4], sa[5]], [sa[8], sa[9]]], [[sa[2], sa[3]], [sa[6], sa[7]], [sa[10],
|
| 259 |
+
sa[11]]]],
|
| 260 |
+
[[[sa[36], sa[37]], [sa[40], sa[41]], [sa[44], sa[45]]], [[sa[38],
|
| 261 |
+
sa[39]], [sa[42], sa[43]], [sa[46], sa[47]]]]],
|
| 262 |
+
[[[[sa[12], sa[13]], [sa[16],
|
| 263 |
+
sa[17]], [sa[20], sa[21]]], [[sa[14], sa[15]], [sa[18], sa[19]], [sa[22],
|
| 264 |
+
sa[23]]]],
|
| 265 |
+
[[[sa[48], sa[49]], [sa[52], sa[53]], [sa[56], sa[57]]], [[sa[50],
|
| 266 |
+
sa[51]], [sa[54], sa[55]], [sa[58], sa[59]]]]],
|
| 267 |
+
[[[[sa[24], sa[25]], [sa[28],
|
| 268 |
+
sa[29]], [sa[32], sa[33]]], [[sa[26], sa[27]], [sa[30], sa[31]], [sa[34],
|
| 269 |
+
sa[35]]]],
|
| 270 |
+
[[[sa[60], sa[61]], [sa[64], sa[65]], [sa[68], sa[69]]], [[sa[62],
|
| 271 |
+
sa[63]], [sa[66], sa[67]], [sa[70], sa[71]]]]]],
|
| 272 |
+
[[[[[sa[72], sa[73]], [sa[76],
|
| 273 |
+
sa[77]], [sa[80], sa[81]]], [[sa[74], sa[75]], [sa[78], sa[79]], [sa[82],
|
| 274 |
+
sa[83]]]],
|
| 275 |
+
[[[sa[108], sa[109]], [sa[112], sa[113]], [sa[116], sa[117]]], [[sa[110],
|
| 276 |
+
sa[111]], [sa[114], sa[115]],
|
| 277 |
+
[sa[118], sa[119]]]]],
|
| 278 |
+
[[[[sa[84], sa[85]], [sa[88],
|
| 279 |
+
sa[89]], [sa[92], sa[93]]], [[sa[86], sa[87]], [sa[90], sa[91]], [sa[94],
|
| 280 |
+
sa[95]]]],
|
| 281 |
+
[[[sa[120], sa[121]], [sa[124], sa[125]], [sa[128], sa[129]]], [[sa[122],
|
| 282 |
+
sa[123]], [sa[126], sa[127]],
|
| 283 |
+
[sa[130], sa[131]]]]],
|
| 284 |
+
[[[[sa[96], sa[97]], [sa[100],
|
| 285 |
+
sa[101]], [sa[104], sa[105]]], [[sa[98], sa[99]], [sa[102], sa[103]], [sa[106],
|
| 286 |
+
sa[107]]]],
|
| 287 |
+
[[[sa[132], sa[133]], [sa[136], sa[137]], [sa[140], sa[141]]], [[sa[134],
|
| 288 |
+
sa[135]], [sa[138], sa[139]],
|
| 289 |
+
[sa[142], sa[143]]]]]]])
|
| 290 |
+
|
| 291 |
+
po2 = po.reshape(4, 9, 2, 2)
|
| 292 |
+
assert po2 == ArrayType([[[[sa[0], sa[1]], [sa[2], sa[3]]], [[sa[4], sa[5]], [sa[6], sa[7]]], [[sa[8], sa[9]], [sa[10], sa[11]]], [[sa[12], sa[13]], [sa[14], sa[15]]], [[sa[16], sa[17]], [sa[18], sa[19]]], [[sa[20], sa[21]], [sa[22], sa[23]]], [[sa[24], sa[25]], [sa[26], sa[27]]], [[sa[28], sa[29]], [sa[30], sa[31]]], [[sa[32], sa[33]], [sa[34], sa[35]]]], [[[sa[36], sa[37]], [sa[38], sa[39]]], [[sa[40], sa[41]], [sa[42], sa[43]]], [[sa[44], sa[45]], [sa[46], sa[47]]], [[sa[48], sa[49]], [sa[50], sa[51]]], [[sa[52], sa[53]], [sa[54], sa[55]]], [[sa[56], sa[57]], [sa[58], sa[59]]], [[sa[60], sa[61]], [sa[62], sa[63]]], [[sa[64], sa[65]], [sa[66], sa[67]]], [[sa[68], sa[69]], [sa[70], sa[71]]]], [[[sa[72], sa[73]], [sa[74], sa[75]]], [[sa[76], sa[77]], [sa[78], sa[79]]], [[sa[80], sa[81]], [sa[82], sa[83]]], [[sa[84], sa[85]], [sa[86], sa[87]]], [[sa[88], sa[89]], [sa[90], sa[91]]], [[sa[92], sa[93]], [sa[94], sa[95]]], [[sa[96], sa[97]], [sa[98], sa[99]]], [[sa[100], sa[101]], [sa[102], sa[103]]], [[sa[104], sa[105]], [sa[106], sa[107]]]], [[[sa[108], sa[109]], [sa[110], sa[111]]], [[sa[112], sa[113]], [sa[114], sa[115]]], [[sa[116], sa[117]], [sa[118], sa[119]]], [[sa[120], sa[121]], [sa[122], sa[123]]], [[sa[124], sa[125]], [sa[126], sa[127]]], [[sa[128], sa[129]], [sa[130], sa[131]]], [[sa[132], sa[133]], [sa[134], sa[135]]], [[sa[136], sa[137]], [sa[138], sa[139]]], [[sa[140], sa[141]], [sa[142], sa[143]]]]])
|
| 293 |
+
|
| 294 |
+
assert permutedims(po2, (3, 2, 0, 1)) == ArrayType([[[[sa[0], sa[4], sa[8], sa[12], sa[16], sa[20], sa[24], sa[28], sa[32]], [sa[36], sa[40], sa[44], sa[48], sa[52], sa[56], sa[60], sa[64], sa[68]], [sa[72], sa[76], sa[80], sa[84], sa[88], sa[92], sa[96], sa[100], sa[104]], [sa[108], sa[112], sa[116], sa[120], sa[124], sa[128], sa[132], sa[136], sa[140]]], [[sa[2], sa[6], sa[10], sa[14], sa[18], sa[22], sa[26], sa[30], sa[34]], [sa[38], sa[42], sa[46], sa[50], sa[54], sa[58], sa[62], sa[66], sa[70]], [sa[74], sa[78], sa[82], sa[86], sa[90], sa[94], sa[98], sa[102], sa[106]], [sa[110], sa[114], sa[118], sa[122], sa[126], sa[130], sa[134], sa[138], sa[142]]]], [[[sa[1], sa[5], sa[9], sa[13], sa[17], sa[21], sa[25], sa[29], sa[33]], [sa[37], sa[41], sa[45], sa[49], sa[53], sa[57], sa[61], sa[65], sa[69]], [sa[73], sa[77], sa[81], sa[85], sa[89], sa[93], sa[97], sa[101], sa[105]], [sa[109], sa[113], sa[117], sa[121], sa[125], sa[129], sa[133], sa[137], sa[141]]], [[sa[3], sa[7], sa[11], sa[15], sa[19], sa[23], sa[27], sa[31], sa[35]], [sa[39], sa[43], sa[47], sa[51], sa[55], sa[59], sa[63], sa[67], sa[71]], [sa[75], sa[79], sa[83], sa[87], sa[91], sa[95], sa[99], sa[103], sa[107]], [sa[111], sa[115], sa[119], sa[123], sa[127], sa[131], sa[135], sa[139], sa[143]]]]])
|
| 295 |
+
|
| 296 |
+
# test for large scale sparse array
|
| 297 |
+
for SparseArrayType in [ImmutableSparseNDimArray, MutableSparseNDimArray]:
|
| 298 |
+
A = SparseArrayType({1:1, 10000:2}, (10000, 20000, 10000))
|
| 299 |
+
assert permutedims(A, (0, 1, 2)) == A
|
| 300 |
+
assert permutedims(A, (1, 0, 2)) == SparseArrayType({1: 1, 100000000: 2}, (20000, 10000, 10000))
|
| 301 |
+
B = SparseArrayType({1:1, 20000:2}, (10000, 20000))
|
| 302 |
+
assert B.transpose() == SparseArrayType({10000: 1, 1: 2}, (20000, 10000))
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
def test_permutedims_with_indices():
|
| 306 |
+
A = Array(range(32)).reshape(2, 2, 2, 2, 2)
|
| 307 |
+
indices_new = list("abcde")
|
| 308 |
+
indices_old = list("ebdac")
|
| 309 |
+
new_A = permutedims(A, index_order_new=indices_new, index_order_old=indices_old)
|
| 310 |
+
for a, b, c, d, e in itertools.product(range(2), range(2), range(2), range(2), range(2)):
|
| 311 |
+
assert new_A[a, b, c, d, e] == A[e, b, d, a, c]
|
| 312 |
+
indices_old = list("cabed")
|
| 313 |
+
new_A = permutedims(A, index_order_new=indices_new, index_order_old=indices_old)
|
| 314 |
+
for a, b, c, d, e in itertools.product(range(2), range(2), range(2), range(2), range(2)):
|
| 315 |
+
assert new_A[a, b, c, d, e] == A[c, a, b, e, d]
|
| 316 |
+
raises(ValueError, lambda: permutedims(A, index_order_old=list("aacde"), index_order_new=list("abcde")))
|
| 317 |
+
raises(ValueError, lambda: permutedims(A, index_order_old=list("abcde"), index_order_new=list("abcce")))
|
| 318 |
+
raises(ValueError, lambda: permutedims(A, index_order_old=list("abcde"), index_order_new=list("abce")))
|
| 319 |
+
raises(ValueError, lambda: permutedims(A, index_order_old=list("abce"), index_order_new=list("abce")))
|
| 320 |
+
raises(ValueError, lambda: permutedims(A, [2, 1, 0, 3, 4], index_order_old=list("abcde")))
|
| 321 |
+
raises(ValueError, lambda: permutedims(A, [2, 1, 0, 3, 4], index_order_new=list("abcde")))
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
def test_flatten():
|
| 325 |
+
from sympy.matrices.dense import Matrix
|
| 326 |
+
for ArrayType in [ImmutableDenseNDimArray, ImmutableSparseNDimArray, Matrix]:
|
| 327 |
+
A = ArrayType(range(24)).reshape(4, 6)
|
| 328 |
+
assert list(Flatten(A)) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
|
| 329 |
+
|
| 330 |
+
for i, v in enumerate(Flatten(A)):
|
| 331 |
+
assert i == v
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
def test_tensordiagonal():
|
| 335 |
+
from sympy.matrices.dense import eye
|
| 336 |
+
expr = Array(range(9)).reshape(3, 3)
|
| 337 |
+
raises(ValueError, lambda: tensordiagonal(expr, [0], [1]))
|
| 338 |
+
raises(ValueError, lambda: tensordiagonal(expr, [0, 0]))
|
| 339 |
+
assert tensordiagonal(eye(3), [0, 1]) == Array([1, 1, 1])
|
| 340 |
+
assert tensordiagonal(expr, [0, 1]) == Array([0, 4, 8])
|
| 341 |
+
x, y, z = symbols("x y z")
|
| 342 |
+
expr2 = tensorproduct([x, y, z], expr)
|
| 343 |
+
assert tensordiagonal(expr2, [1, 2]) == Array([[0, 4*x, 8*x], [0, 4*y, 8*y], [0, 4*z, 8*z]])
|
| 344 |
+
assert tensordiagonal(expr2, [0, 1]) == Array([[0, 3*y, 6*z], [x, 4*y, 7*z], [2*x, 5*y, 8*z]])
|
| 345 |
+
assert tensordiagonal(expr2, [0, 1, 2]) == Array([0, 4*y, 8*z])
|
| 346 |
+
# assert tensordiagonal(expr2, [0]) == permutedims(expr2, [1, 2, 0])
|
| 347 |
+
# assert tensordiagonal(expr2, [1]) == permutedims(expr2, [0, 2, 1])
|
| 348 |
+
# assert tensordiagonal(expr2, [2]) == expr2
|
| 349 |
+
# assert tensordiagonal(expr2, [1], [2]) == expr2
|
| 350 |
+
# assert tensordiagonal(expr2, [0], [1]) == permutedims(expr2, [2, 0, 1])
|
| 351 |
+
|
| 352 |
+
a, b, c, X, Y, Z = symbols("a b c X Y Z")
|
| 353 |
+
expr3 = tensorproduct([x, y, z], [1, 2, 3], [a, b, c], [X, Y, Z])
|
| 354 |
+
assert tensordiagonal(expr3, [0, 1, 2, 3]) == Array([x*a*X, 2*y*b*Y, 3*z*c*Z])
|
| 355 |
+
assert tensordiagonal(expr3, [0, 1], [2, 3]) == tensorproduct([x, 2*y, 3*z], [a*X, b*Y, c*Z])
|
| 356 |
+
|
| 357 |
+
# assert tensordiagonal(expr3, [0], [1, 2], [3]) == tensorproduct([x, y, z], [a, 2*b, 3*c], [X, Y, Z])
|
| 358 |
+
assert tensordiagonal(tensordiagonal(expr3, [2, 3]), [0, 1]) == tensorproduct([a*X, b*Y, c*Z], [x, 2*y, 3*z])
|
| 359 |
+
|
| 360 |
+
raises(ValueError, lambda: tensordiagonal([[1, 2, 3], [4, 5, 6]], [0, 1]))
|
| 361 |
+
raises(ValueError, lambda: tensordiagonal(expr3.reshape(3, 3, 9), [1, 2]))
|
evalkit_internvl/lib/python3.10/site-packages/sympy/tensor/array/tests/test_mutable_ndim_array.py
ADDED
|
@@ -0,0 +1,374 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from copy import copy
|
| 2 |
+
|
| 3 |
+
from sympy.tensor.array.dense_ndim_array import MutableDenseNDimArray
|
| 4 |
+
from sympy.core.function import diff
|
| 5 |
+
from sympy.core.numbers import Rational
|
| 6 |
+
from sympy.core.singleton import S
|
| 7 |
+
from sympy.core.symbol import Symbol
|
| 8 |
+
from sympy.core.sympify import sympify
|
| 9 |
+
from sympy.matrices import SparseMatrix
|
| 10 |
+
from sympy.matrices import Matrix
|
| 11 |
+
from sympy.tensor.array.sparse_ndim_array import MutableSparseNDimArray
|
| 12 |
+
from sympy.testing.pytest import raises
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def test_ndim_array_initiation():
|
| 16 |
+
arr_with_one_element = MutableDenseNDimArray([23])
|
| 17 |
+
assert len(arr_with_one_element) == 1
|
| 18 |
+
assert arr_with_one_element[0] == 23
|
| 19 |
+
assert arr_with_one_element.rank() == 1
|
| 20 |
+
raises(ValueError, lambda: arr_with_one_element[1])
|
| 21 |
+
|
| 22 |
+
arr_with_symbol_element = MutableDenseNDimArray([Symbol('x')])
|
| 23 |
+
assert len(arr_with_symbol_element) == 1
|
| 24 |
+
assert arr_with_symbol_element[0] == Symbol('x')
|
| 25 |
+
assert arr_with_symbol_element.rank() == 1
|
| 26 |
+
|
| 27 |
+
number5 = 5
|
| 28 |
+
vector = MutableDenseNDimArray.zeros(number5)
|
| 29 |
+
assert len(vector) == number5
|
| 30 |
+
assert vector.shape == (number5,)
|
| 31 |
+
assert vector.rank() == 1
|
| 32 |
+
raises(ValueError, lambda: arr_with_one_element[5])
|
| 33 |
+
|
| 34 |
+
vector = MutableSparseNDimArray.zeros(number5)
|
| 35 |
+
assert len(vector) == number5
|
| 36 |
+
assert vector.shape == (number5,)
|
| 37 |
+
assert vector._sparse_array == {}
|
| 38 |
+
assert vector.rank() == 1
|
| 39 |
+
|
| 40 |
+
n_dim_array = MutableDenseNDimArray(range(3**4), (3, 3, 3, 3,))
|
| 41 |
+
assert len(n_dim_array) == 3 * 3 * 3 * 3
|
| 42 |
+
assert n_dim_array.shape == (3, 3, 3, 3)
|
| 43 |
+
assert n_dim_array.rank() == 4
|
| 44 |
+
raises(ValueError, lambda: n_dim_array[0, 0, 0, 3])
|
| 45 |
+
raises(ValueError, lambda: n_dim_array[3, 0, 0, 0])
|
| 46 |
+
raises(ValueError, lambda: n_dim_array[3**4])
|
| 47 |
+
|
| 48 |
+
array_shape = (3, 3, 3, 3)
|
| 49 |
+
sparse_array = MutableSparseNDimArray.zeros(*array_shape)
|
| 50 |
+
assert len(sparse_array._sparse_array) == 0
|
| 51 |
+
assert len(sparse_array) == 3 * 3 * 3 * 3
|
| 52 |
+
assert n_dim_array.shape == array_shape
|
| 53 |
+
assert n_dim_array.rank() == 4
|
| 54 |
+
|
| 55 |
+
one_dim_array = MutableDenseNDimArray([2, 3, 1])
|
| 56 |
+
assert len(one_dim_array) == 3
|
| 57 |
+
assert one_dim_array.shape == (3,)
|
| 58 |
+
assert one_dim_array.rank() == 1
|
| 59 |
+
assert one_dim_array.tolist() == [2, 3, 1]
|
| 60 |
+
|
| 61 |
+
shape = (3, 3)
|
| 62 |
+
array_with_many_args = MutableSparseNDimArray.zeros(*shape)
|
| 63 |
+
assert len(array_with_many_args) == 3 * 3
|
| 64 |
+
assert array_with_many_args.shape == shape
|
| 65 |
+
assert array_with_many_args[0, 0] == 0
|
| 66 |
+
assert array_with_many_args.rank() == 2
|
| 67 |
+
|
| 68 |
+
shape = (int(3), int(3))
|
| 69 |
+
array_with_long_shape = MutableSparseNDimArray.zeros(*shape)
|
| 70 |
+
assert len(array_with_long_shape) == 3 * 3
|
| 71 |
+
assert array_with_long_shape.shape == shape
|
| 72 |
+
assert array_with_long_shape[int(0), int(0)] == 0
|
| 73 |
+
assert array_with_long_shape.rank() == 2
|
| 74 |
+
|
| 75 |
+
vector_with_long_shape = MutableDenseNDimArray(range(5), int(5))
|
| 76 |
+
assert len(vector_with_long_shape) == 5
|
| 77 |
+
assert vector_with_long_shape.shape == (int(5),)
|
| 78 |
+
assert vector_with_long_shape.rank() == 1
|
| 79 |
+
raises(ValueError, lambda: vector_with_long_shape[int(5)])
|
| 80 |
+
|
| 81 |
+
from sympy.abc import x
|
| 82 |
+
for ArrayType in [MutableDenseNDimArray, MutableSparseNDimArray]:
|
| 83 |
+
rank_zero_array = ArrayType(x)
|
| 84 |
+
assert len(rank_zero_array) == 1
|
| 85 |
+
assert rank_zero_array.shape == ()
|
| 86 |
+
assert rank_zero_array.rank() == 0
|
| 87 |
+
assert rank_zero_array[()] == x
|
| 88 |
+
raises(ValueError, lambda: rank_zero_array[0])
|
| 89 |
+
|
| 90 |
+
def test_sympify():
|
| 91 |
+
from sympy.abc import x, y, z, t
|
| 92 |
+
arr = MutableDenseNDimArray([[x, y], [1, z*t]])
|
| 93 |
+
arr_other = sympify(arr)
|
| 94 |
+
assert arr_other.shape == (2, 2)
|
| 95 |
+
assert arr_other == arr
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def test_reshape():
|
| 99 |
+
array = MutableDenseNDimArray(range(50), 50)
|
| 100 |
+
assert array.shape == (50,)
|
| 101 |
+
assert array.rank() == 1
|
| 102 |
+
|
| 103 |
+
array = array.reshape(5, 5, 2)
|
| 104 |
+
assert array.shape == (5, 5, 2)
|
| 105 |
+
assert array.rank() == 3
|
| 106 |
+
assert len(array) == 50
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def test_iterator():
|
| 110 |
+
array = MutableDenseNDimArray(range(4), (2, 2))
|
| 111 |
+
assert array[0] == MutableDenseNDimArray([0, 1])
|
| 112 |
+
assert array[1] == MutableDenseNDimArray([2, 3])
|
| 113 |
+
|
| 114 |
+
array = array.reshape(4)
|
| 115 |
+
j = 0
|
| 116 |
+
for i in array:
|
| 117 |
+
assert i == j
|
| 118 |
+
j += 1
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def test_getitem():
|
| 122 |
+
for ArrayType in [MutableDenseNDimArray, MutableSparseNDimArray]:
|
| 123 |
+
array = ArrayType(range(24)).reshape(2, 3, 4)
|
| 124 |
+
assert array.tolist() == [[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]], [[12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23]]]
|
| 125 |
+
assert array[0] == ArrayType([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]])
|
| 126 |
+
assert array[0, 0] == ArrayType([0, 1, 2, 3])
|
| 127 |
+
value = 0
|
| 128 |
+
for i in range(2):
|
| 129 |
+
for j in range(3):
|
| 130 |
+
for k in range(4):
|
| 131 |
+
assert array[i, j, k] == value
|
| 132 |
+
value += 1
|
| 133 |
+
|
| 134 |
+
raises(ValueError, lambda: array[3, 4, 5])
|
| 135 |
+
raises(ValueError, lambda: array[3, 4, 5, 6])
|
| 136 |
+
raises(ValueError, lambda: array[3, 4, 5, 3:4])
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def test_sparse():
|
| 140 |
+
sparse_array = MutableSparseNDimArray([0, 0, 0, 1], (2, 2))
|
| 141 |
+
assert len(sparse_array) == 2 * 2
|
| 142 |
+
# dictionary where all data is, only non-zero entries are actually stored:
|
| 143 |
+
assert len(sparse_array._sparse_array) == 1
|
| 144 |
+
|
| 145 |
+
assert sparse_array.tolist() == [[0, 0], [0, 1]]
|
| 146 |
+
|
| 147 |
+
for i, j in zip(sparse_array, [[0, 0], [0, 1]]):
|
| 148 |
+
assert i == MutableSparseNDimArray(j)
|
| 149 |
+
|
| 150 |
+
sparse_array[0, 0] = 123
|
| 151 |
+
assert len(sparse_array._sparse_array) == 2
|
| 152 |
+
assert sparse_array[0, 0] == 123
|
| 153 |
+
assert sparse_array/0 == MutableSparseNDimArray([[S.ComplexInfinity, S.NaN], [S.NaN, S.ComplexInfinity]], (2, 2))
|
| 154 |
+
|
| 155 |
+
# when element in sparse array become zero it will disappear from
|
| 156 |
+
# dictionary
|
| 157 |
+
sparse_array[0, 0] = 0
|
| 158 |
+
assert len(sparse_array._sparse_array) == 1
|
| 159 |
+
sparse_array[1, 1] = 0
|
| 160 |
+
assert len(sparse_array._sparse_array) == 0
|
| 161 |
+
assert sparse_array[0, 0] == 0
|
| 162 |
+
|
| 163 |
+
# test for large scale sparse array
|
| 164 |
+
# equality test
|
| 165 |
+
a = MutableSparseNDimArray.zeros(100000, 200000)
|
| 166 |
+
b = MutableSparseNDimArray.zeros(100000, 200000)
|
| 167 |
+
assert a == b
|
| 168 |
+
a[1, 1] = 1
|
| 169 |
+
b[1, 1] = 2
|
| 170 |
+
assert a != b
|
| 171 |
+
|
| 172 |
+
# __mul__ and __rmul__
|
| 173 |
+
assert a * 3 == MutableSparseNDimArray({200001: 3}, (100000, 200000))
|
| 174 |
+
assert 3 * a == MutableSparseNDimArray({200001: 3}, (100000, 200000))
|
| 175 |
+
assert a * 0 == MutableSparseNDimArray({}, (100000, 200000))
|
| 176 |
+
assert 0 * a == MutableSparseNDimArray({}, (100000, 200000))
|
| 177 |
+
|
| 178 |
+
# __truediv__
|
| 179 |
+
assert a/3 == MutableSparseNDimArray({200001: Rational(1, 3)}, (100000, 200000))
|
| 180 |
+
|
| 181 |
+
# __neg__
|
| 182 |
+
assert -a == MutableSparseNDimArray({200001: -1}, (100000, 200000))
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def test_calculation():
|
| 186 |
+
|
| 187 |
+
a = MutableDenseNDimArray([1]*9, (3, 3))
|
| 188 |
+
b = MutableDenseNDimArray([9]*9, (3, 3))
|
| 189 |
+
|
| 190 |
+
c = a + b
|
| 191 |
+
for i in c:
|
| 192 |
+
assert i == MutableDenseNDimArray([10, 10, 10])
|
| 193 |
+
|
| 194 |
+
assert c == MutableDenseNDimArray([10]*9, (3, 3))
|
| 195 |
+
assert c == MutableSparseNDimArray([10]*9, (3, 3))
|
| 196 |
+
|
| 197 |
+
c = b - a
|
| 198 |
+
for i in c:
|
| 199 |
+
assert i == MutableSparseNDimArray([8, 8, 8])
|
| 200 |
+
|
| 201 |
+
assert c == MutableDenseNDimArray([8]*9, (3, 3))
|
| 202 |
+
assert c == MutableSparseNDimArray([8]*9, (3, 3))
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def test_ndim_array_converting():
|
| 206 |
+
dense_array = MutableDenseNDimArray([1, 2, 3, 4], (2, 2))
|
| 207 |
+
alist = dense_array.tolist()
|
| 208 |
+
|
| 209 |
+
assert alist == [[1, 2], [3, 4]]
|
| 210 |
+
|
| 211 |
+
matrix = dense_array.tomatrix()
|
| 212 |
+
assert (isinstance(matrix, Matrix))
|
| 213 |
+
|
| 214 |
+
for i in range(len(dense_array)):
|
| 215 |
+
assert dense_array[dense_array._get_tuple_index(i)] == matrix[i]
|
| 216 |
+
assert matrix.shape == dense_array.shape
|
| 217 |
+
|
| 218 |
+
assert MutableDenseNDimArray(matrix) == dense_array
|
| 219 |
+
assert MutableDenseNDimArray(matrix.as_immutable()) == dense_array
|
| 220 |
+
assert MutableDenseNDimArray(matrix.as_mutable()) == dense_array
|
| 221 |
+
|
| 222 |
+
sparse_array = MutableSparseNDimArray([1, 2, 3, 4], (2, 2))
|
| 223 |
+
alist = sparse_array.tolist()
|
| 224 |
+
|
| 225 |
+
assert alist == [[1, 2], [3, 4]]
|
| 226 |
+
|
| 227 |
+
matrix = sparse_array.tomatrix()
|
| 228 |
+
assert(isinstance(matrix, SparseMatrix))
|
| 229 |
+
|
| 230 |
+
for i in range(len(sparse_array)):
|
| 231 |
+
assert sparse_array[sparse_array._get_tuple_index(i)] == matrix[i]
|
| 232 |
+
assert matrix.shape == sparse_array.shape
|
| 233 |
+
|
| 234 |
+
assert MutableSparseNDimArray(matrix) == sparse_array
|
| 235 |
+
assert MutableSparseNDimArray(matrix.as_immutable()) == sparse_array
|
| 236 |
+
assert MutableSparseNDimArray(matrix.as_mutable()) == sparse_array
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def test_converting_functions():
|
| 240 |
+
arr_list = [1, 2, 3, 4]
|
| 241 |
+
arr_matrix = Matrix(((1, 2), (3, 4)))
|
| 242 |
+
|
| 243 |
+
# list
|
| 244 |
+
arr_ndim_array = MutableDenseNDimArray(arr_list, (2, 2))
|
| 245 |
+
assert (isinstance(arr_ndim_array, MutableDenseNDimArray))
|
| 246 |
+
assert arr_matrix.tolist() == arr_ndim_array.tolist()
|
| 247 |
+
|
| 248 |
+
# Matrix
|
| 249 |
+
arr_ndim_array = MutableDenseNDimArray(arr_matrix)
|
| 250 |
+
assert (isinstance(arr_ndim_array, MutableDenseNDimArray))
|
| 251 |
+
assert arr_matrix.tolist() == arr_ndim_array.tolist()
|
| 252 |
+
assert arr_matrix.shape == arr_ndim_array.shape
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
def test_equality():
|
| 256 |
+
first_list = [1, 2, 3, 4]
|
| 257 |
+
second_list = [1, 2, 3, 4]
|
| 258 |
+
third_list = [4, 3, 2, 1]
|
| 259 |
+
assert first_list == second_list
|
| 260 |
+
assert first_list != third_list
|
| 261 |
+
|
| 262 |
+
first_ndim_array = MutableDenseNDimArray(first_list, (2, 2))
|
| 263 |
+
second_ndim_array = MutableDenseNDimArray(second_list, (2, 2))
|
| 264 |
+
third_ndim_array = MutableDenseNDimArray(third_list, (2, 2))
|
| 265 |
+
fourth_ndim_array = MutableDenseNDimArray(first_list, (2, 2))
|
| 266 |
+
|
| 267 |
+
assert first_ndim_array == second_ndim_array
|
| 268 |
+
second_ndim_array[0, 0] = 0
|
| 269 |
+
assert first_ndim_array != second_ndim_array
|
| 270 |
+
assert first_ndim_array != third_ndim_array
|
| 271 |
+
assert first_ndim_array == fourth_ndim_array
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
def test_arithmetic():
|
| 275 |
+
a = MutableDenseNDimArray([3 for i in range(9)], (3, 3))
|
| 276 |
+
b = MutableDenseNDimArray([7 for i in range(9)], (3, 3))
|
| 277 |
+
|
| 278 |
+
c1 = a + b
|
| 279 |
+
c2 = b + a
|
| 280 |
+
assert c1 == c2
|
| 281 |
+
|
| 282 |
+
d1 = a - b
|
| 283 |
+
d2 = b - a
|
| 284 |
+
assert d1 == d2 * (-1)
|
| 285 |
+
|
| 286 |
+
e1 = a * 5
|
| 287 |
+
e2 = 5 * a
|
| 288 |
+
e3 = copy(a)
|
| 289 |
+
e3 *= 5
|
| 290 |
+
assert e1 == e2 == e3
|
| 291 |
+
|
| 292 |
+
f1 = a / 5
|
| 293 |
+
f2 = copy(a)
|
| 294 |
+
f2 /= 5
|
| 295 |
+
assert f1 == f2
|
| 296 |
+
assert f1[0, 0] == f1[0, 1] == f1[0, 2] == f1[1, 0] == f1[1, 1] == \
|
| 297 |
+
f1[1, 2] == f1[2, 0] == f1[2, 1] == f1[2, 2] == Rational(3, 5)
|
| 298 |
+
|
| 299 |
+
assert type(a) == type(b) == type(c1) == type(c2) == type(d1) == type(d2) \
|
| 300 |
+
== type(e1) == type(e2) == type(e3) == type(f1)
|
| 301 |
+
|
| 302 |
+
z0 = -a
|
| 303 |
+
assert z0 == MutableDenseNDimArray([-3 for i in range(9)], (3, 3))
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
def test_higher_dimenions():
|
| 307 |
+
m3 = MutableDenseNDimArray(range(10, 34), (2, 3, 4))
|
| 308 |
+
|
| 309 |
+
assert m3.tolist() == [[[10, 11, 12, 13],
|
| 310 |
+
[14, 15, 16, 17],
|
| 311 |
+
[18, 19, 20, 21]],
|
| 312 |
+
|
| 313 |
+
[[22, 23, 24, 25],
|
| 314 |
+
[26, 27, 28, 29],
|
| 315 |
+
[30, 31, 32, 33]]]
|
| 316 |
+
|
| 317 |
+
assert m3._get_tuple_index(0) == (0, 0, 0)
|
| 318 |
+
assert m3._get_tuple_index(1) == (0, 0, 1)
|
| 319 |
+
assert m3._get_tuple_index(4) == (0, 1, 0)
|
| 320 |
+
assert m3._get_tuple_index(12) == (1, 0, 0)
|
| 321 |
+
|
| 322 |
+
assert str(m3) == '[[[10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21]], [[22, 23, 24, 25], [26, 27, 28, 29], [30, 31, 32, 33]]]'
|
| 323 |
+
|
| 324 |
+
m3_rebuilt = MutableDenseNDimArray([[[10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21]], [[22, 23, 24, 25], [26, 27, 28, 29], [30, 31, 32, 33]]])
|
| 325 |
+
assert m3 == m3_rebuilt
|
| 326 |
+
|
| 327 |
+
m3_other = MutableDenseNDimArray([[[10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21]], [[22, 23, 24, 25], [26, 27, 28, 29], [30, 31, 32, 33]]], (2, 3, 4))
|
| 328 |
+
|
| 329 |
+
assert m3 == m3_other
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
def test_slices():
|
| 333 |
+
md = MutableDenseNDimArray(range(10, 34), (2, 3, 4))
|
| 334 |
+
|
| 335 |
+
assert md[:] == MutableDenseNDimArray(range(10, 34), (2, 3, 4))
|
| 336 |
+
assert md[:, :, 0].tomatrix() == Matrix([[10, 14, 18], [22, 26, 30]])
|
| 337 |
+
assert md[0, 1:2, :].tomatrix() == Matrix([[14, 15, 16, 17]])
|
| 338 |
+
assert md[0, 1:3, :].tomatrix() == Matrix([[14, 15, 16, 17], [18, 19, 20, 21]])
|
| 339 |
+
assert md[:, :, :] == md
|
| 340 |
+
|
| 341 |
+
sd = MutableSparseNDimArray(range(10, 34), (2, 3, 4))
|
| 342 |
+
assert sd == MutableSparseNDimArray(md)
|
| 343 |
+
|
| 344 |
+
assert sd[:] == MutableSparseNDimArray(range(10, 34), (2, 3, 4))
|
| 345 |
+
assert sd[:, :, 0].tomatrix() == Matrix([[10, 14, 18], [22, 26, 30]])
|
| 346 |
+
assert sd[0, 1:2, :].tomatrix() == Matrix([[14, 15, 16, 17]])
|
| 347 |
+
assert sd[0, 1:3, :].tomatrix() == Matrix([[14, 15, 16, 17], [18, 19, 20, 21]])
|
| 348 |
+
assert sd[:, :, :] == sd
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
def test_slices_assign():
|
| 352 |
+
a = MutableDenseNDimArray(range(12), shape=(4, 3))
|
| 353 |
+
b = MutableSparseNDimArray(range(12), shape=(4, 3))
|
| 354 |
+
|
| 355 |
+
for i in [a, b]:
|
| 356 |
+
assert i.tolist() == [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]
|
| 357 |
+
i[0, :] = [2, 2, 2]
|
| 358 |
+
assert i.tolist() == [[2, 2, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]
|
| 359 |
+
i[0, 1:] = [8, 8]
|
| 360 |
+
assert i.tolist() == [[2, 8, 8], [3, 4, 5], [6, 7, 8], [9, 10, 11]]
|
| 361 |
+
i[1:3, 1] = [20, 44]
|
| 362 |
+
assert i.tolist() == [[2, 8, 8], [3, 20, 5], [6, 44, 8], [9, 10, 11]]
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
def test_diff():
|
| 366 |
+
from sympy.abc import x, y, z
|
| 367 |
+
md = MutableDenseNDimArray([[x, y], [x*z, x*y*z]])
|
| 368 |
+
assert md.diff(x) == MutableDenseNDimArray([[1, 0], [z, y*z]])
|
| 369 |
+
assert diff(md, x) == MutableDenseNDimArray([[1, 0], [z, y*z]])
|
| 370 |
+
|
| 371 |
+
sd = MutableSparseNDimArray(md)
|
| 372 |
+
assert sd == MutableSparseNDimArray([x, y, x*z, x*y*z], (2, 2))
|
| 373 |
+
assert sd.diff(x) == MutableSparseNDimArray([[1, 0], [z, y*z]])
|
| 374 |
+
assert diff(sd, x) == MutableSparseNDimArray([[1, 0], [z, y*z]])
|
evalkit_internvl/lib/python3.10/site-packages/sympy/tensor/array/tests/test_ndim_array_conversions.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.tensor.array import (ImmutableDenseNDimArray,
|
| 2 |
+
ImmutableSparseNDimArray, MutableDenseNDimArray, MutableSparseNDimArray)
|
| 3 |
+
from sympy.abc import x, y, z
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def test_NDim_array_conv():
|
| 7 |
+
MD = MutableDenseNDimArray([x, y, z])
|
| 8 |
+
MS = MutableSparseNDimArray([x, y, z])
|
| 9 |
+
ID = ImmutableDenseNDimArray([x, y, z])
|
| 10 |
+
IS = ImmutableSparseNDimArray([x, y, z])
|
| 11 |
+
|
| 12 |
+
assert MD.as_immutable() == ID
|
| 13 |
+
assert MD.as_mutable() == MD
|
| 14 |
+
|
| 15 |
+
assert MS.as_immutable() == IS
|
| 16 |
+
assert MS.as_mutable() == MS
|
| 17 |
+
|
| 18 |
+
assert ID.as_immutable() == ID
|
| 19 |
+
assert ID.as_mutable() == MD
|
| 20 |
+
|
| 21 |
+
assert IS.as_immutable() == IS
|
| 22 |
+
assert IS.as_mutable() == MS
|
evalkit_tf437/lib/python3.10/site-packages/accelerate/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (1.08 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/accelerate/__pycache__/big_modeling.cpython-310.pyc
ADDED
|
Binary file (21.3 kB). View file
|
|
|
evalkit_tf437/lib/python3.10/site-packages/accelerate/__pycache__/checkpointing.cpython-310.pyc
ADDED
|
Binary file (6.5 kB). View file
|
|
|