Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- pllava/lib/python3.10/site-packages/sympy/solvers/__pycache__/bivariate.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/__pycache__/decompogen.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/__pycache__/deutils.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/__pycache__/inequalities.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/__pycache__/pde.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/__pycache__/polysys.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/__pycache__/simplex.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/benchmarks/bench_solvers.py +12 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/decompogen.py +126 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/deutils.py +273 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/diophantine/__init__.py +5 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/diophantine/__pycache__/__init__.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/diophantine/diophantine.py +0 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/diophantine/tests/__init__.py +0 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/diophantine/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/diophantine/tests/__pycache__/test_diophantine.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/diophantine/tests/test_diophantine.py +1051 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/inequalities.py +986 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/ode/__init__.py +16 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/__init__.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/lie_group.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/nonhomogeneous.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/subscheck.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/systems.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/ode/nonhomogeneous.py +499 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/ode/ode.py +0 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/ode/riccati.py +893 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/ode/single.py +0 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/ode/subscheck.py +392 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/ode/systems.py +2135 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/ode/tests/__init__.py +0 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/ode/tests/__pycache__/test_lie_group.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/ode/tests/__pycache__/test_ode.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/ode/tests/__pycache__/test_single.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/ode/tests/__pycache__/test_subscheck.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/pde.py +971 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/polysys.py +437 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/simplex.py +1141 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/solvers.py +0 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/solveset.py +0 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/tests/__init__.py +0 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/test_constantsimp.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/test_decompogen.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/test_inequalities.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/test_numeric.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/test_pde.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/test_polysys.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/test_recurr.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/test_simplex.cpython-310.pyc +0 -0
- pllava/lib/python3.10/site-packages/sympy/solvers/tests/test_constantsimp.py +179 -0
pllava/lib/python3.10/site-packages/sympy/solvers/__pycache__/bivariate.cpython-310.pyc
ADDED
|
Binary file (13.8 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/solvers/__pycache__/decompogen.cpython-310.pyc
ADDED
|
Binary file (3.49 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/solvers/__pycache__/deutils.cpython-310.pyc
ADDED
|
Binary file (8.04 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/solvers/__pycache__/inequalities.cpython-310.pyc
ADDED
|
Binary file (23.9 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/solvers/__pycache__/pde.cpython-310.pyc
ADDED
|
Binary file (29.5 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/solvers/__pycache__/polysys.cpython-310.pyc
ADDED
|
Binary file (12.9 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/solvers/__pycache__/simplex.cpython-310.pyc
ADDED
|
Binary file (32.7 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/solvers/benchmarks/bench_solvers.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core.symbol import Symbol
|
| 2 |
+
from sympy.matrices.dense import (eye, zeros)
|
| 3 |
+
from sympy.solvers.solvers import solve_linear_system
|
| 4 |
+
|
| 5 |
+
N = 8
|
| 6 |
+
M = zeros(N, N + 1)
|
| 7 |
+
M[:, :N] = eye(N)
|
| 8 |
+
S = [Symbol('A%i' % i) for i in range(N)]
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def timeit_linsolve_trivial():
|
| 12 |
+
solve_linear_system(M, *S)
|
pllava/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)
|
pllava/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
|
pllava/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 |
+
]
|
pllava/lib/python3.10/site-packages/sympy/solvers/diophantine/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (275 Bytes). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/solvers/diophantine/diophantine.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
pllava/lib/python3.10/site-packages/sympy/solvers/diophantine/tests/__init__.py
ADDED
|
File without changes
|
pllava/lib/python3.10/site-packages/sympy/solvers/diophantine/tests/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (183 Bytes). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/solvers/diophantine/tests/__pycache__/test_diophantine.cpython-310.pyc
ADDED
|
Binary file (46.5 kB). View file
|
|
|
pllava/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)}
|
pllava/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()})
|
pllava/lib/python3.10/site-packages/sympy/solvers/ode/__init__.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .ode import (allhints, checkinfsol, classify_ode,
|
| 2 |
+
constantsimp, dsolve, homogeneous_order)
|
| 3 |
+
|
| 4 |
+
from .lie_group import infinitesimals
|
| 5 |
+
|
| 6 |
+
from .subscheck import checkodesol
|
| 7 |
+
|
| 8 |
+
from .systems import (canonical_odes, linear_ode_to_matrix,
|
| 9 |
+
linodesolve)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
__all__ = [
|
| 13 |
+
'allhints', 'checkinfsol', 'checkodesol', 'classify_ode', 'constantsimp',
|
| 14 |
+
'dsolve', 'homogeneous_order', 'infinitesimals', 'canonical_odes', 'linear_ode_to_matrix',
|
| 15 |
+
'linodesolve'
|
| 16 |
+
]
|
pllava/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (586 Bytes). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/lie_group.cpython-310.pyc
ADDED
|
Binary file (30.5 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/nonhomogeneous.cpython-310.pyc
ADDED
|
Binary file (14.8 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/subscheck.cpython-310.pyc
ADDED
|
Binary file (12.2 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/systems.cpython-310.pyc
ADDED
|
Binary file (66.5 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/solvers/ode/nonhomogeneous.py
ADDED
|
@@ -0,0 +1,499 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r"""
|
| 2 |
+
This File contains helper functions for nth_linear_constant_coeff_undetermined_coefficients,
|
| 3 |
+
nth_linear_euler_eq_nonhomogeneous_undetermined_coefficients,
|
| 4 |
+
nth_linear_constant_coeff_variation_of_parameters,
|
| 5 |
+
and nth_linear_euler_eq_nonhomogeneous_variation_of_parameters.
|
| 6 |
+
|
| 7 |
+
All the functions in this file are used by more than one solvers so, instead of creating
|
| 8 |
+
instances in other classes for using them it is better to keep it here as separate helpers.
|
| 9 |
+
|
| 10 |
+
"""
|
| 11 |
+
from collections import defaultdict
|
| 12 |
+
from sympy.core import Add, S
|
| 13 |
+
from sympy.core.function import diff, expand, _mexpand, expand_mul
|
| 14 |
+
from sympy.core.relational import Eq
|
| 15 |
+
from sympy.core.sorting import default_sort_key
|
| 16 |
+
from sympy.core.symbol import Dummy, Wild
|
| 17 |
+
from sympy.functions import exp, cos, cosh, im, log, re, sin, sinh, \
|
| 18 |
+
atan2, conjugate
|
| 19 |
+
from sympy.integrals import Integral
|
| 20 |
+
from sympy.polys import (Poly, RootOf, rootof, roots)
|
| 21 |
+
from sympy.simplify import collect, simplify, separatevars, powsimp, trigsimp # type: ignore
|
| 22 |
+
from sympy.utilities import numbered_symbols
|
| 23 |
+
from sympy.solvers.solvers import solve
|
| 24 |
+
from sympy.matrices import wronskian
|
| 25 |
+
from .subscheck import sub_func_doit
|
| 26 |
+
from sympy.solvers.ode.ode import get_numbered_constants
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _test_term(coeff, func, order):
|
| 30 |
+
r"""
|
| 31 |
+
Linear Euler ODEs have the form K*x**order*diff(y(x), x, order) = F(x),
|
| 32 |
+
where K is independent of x and y(x), order>= 0.
|
| 33 |
+
So we need to check that for each term, coeff == K*x**order from
|
| 34 |
+
some K. We have a few cases, since coeff may have several
|
| 35 |
+
different types.
|
| 36 |
+
"""
|
| 37 |
+
x = func.args[0]
|
| 38 |
+
f = func.func
|
| 39 |
+
if order < 0:
|
| 40 |
+
raise ValueError("order should be greater than 0")
|
| 41 |
+
if coeff == 0:
|
| 42 |
+
return True
|
| 43 |
+
if order == 0:
|
| 44 |
+
if x in coeff.free_symbols:
|
| 45 |
+
return False
|
| 46 |
+
return True
|
| 47 |
+
if coeff.is_Mul:
|
| 48 |
+
if coeff.has(f(x)):
|
| 49 |
+
return False
|
| 50 |
+
return x**order in coeff.args
|
| 51 |
+
elif coeff.is_Pow:
|
| 52 |
+
return coeff.as_base_exp() == (x, order)
|
| 53 |
+
elif order == 1:
|
| 54 |
+
return x == coeff
|
| 55 |
+
return False
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def _get_euler_characteristic_eq_sols(eq, func, match_obj):
|
| 59 |
+
r"""
|
| 60 |
+
Returns the solution of homogeneous part of the linear euler ODE and
|
| 61 |
+
the list of roots of characteristic equation.
|
| 62 |
+
|
| 63 |
+
The parameter ``match_obj`` is a dict of order:coeff terms, where order is the order
|
| 64 |
+
of the derivative on each term, and coeff is the coefficient of that derivative.
|
| 65 |
+
|
| 66 |
+
"""
|
| 67 |
+
x = func.args[0]
|
| 68 |
+
f = func.func
|
| 69 |
+
|
| 70 |
+
# First, set up characteristic equation.
|
| 71 |
+
chareq, symbol = S.Zero, Dummy('x')
|
| 72 |
+
|
| 73 |
+
for i in match_obj:
|
| 74 |
+
if i >= 0:
|
| 75 |
+
chareq += (match_obj[i]*diff(x**symbol, x, i)*x**-symbol).expand()
|
| 76 |
+
|
| 77 |
+
chareq = Poly(chareq, symbol)
|
| 78 |
+
chareqroots = [rootof(chareq, k) for k in range(chareq.degree())]
|
| 79 |
+
collectterms = []
|
| 80 |
+
|
| 81 |
+
# A generator of constants
|
| 82 |
+
constants = list(get_numbered_constants(eq, num=chareq.degree()*2))
|
| 83 |
+
constants.reverse()
|
| 84 |
+
|
| 85 |
+
# Create a dict root: multiplicity or charroots
|
| 86 |
+
charroots = defaultdict(int)
|
| 87 |
+
for root in chareqroots:
|
| 88 |
+
charroots[root] += 1
|
| 89 |
+
gsol = S.Zero
|
| 90 |
+
ln = log
|
| 91 |
+
for root, multiplicity in charroots.items():
|
| 92 |
+
for i in range(multiplicity):
|
| 93 |
+
if isinstance(root, RootOf):
|
| 94 |
+
gsol += (x**root) * constants.pop()
|
| 95 |
+
if multiplicity != 1:
|
| 96 |
+
raise ValueError("Value should be 1")
|
| 97 |
+
collectterms = [(0, root, 0)] + collectterms
|
| 98 |
+
elif root.is_real:
|
| 99 |
+
gsol += ln(x)**i*(x**root) * constants.pop()
|
| 100 |
+
collectterms = [(i, root, 0)] + collectterms
|
| 101 |
+
else:
|
| 102 |
+
reroot = re(root)
|
| 103 |
+
imroot = im(root)
|
| 104 |
+
gsol += ln(x)**i * (x**reroot) * (
|
| 105 |
+
constants.pop() * sin(abs(imroot)*ln(x))
|
| 106 |
+
+ constants.pop() * cos(imroot*ln(x)))
|
| 107 |
+
collectterms = [(i, reroot, imroot)] + collectterms
|
| 108 |
+
|
| 109 |
+
gsol = Eq(f(x), gsol)
|
| 110 |
+
|
| 111 |
+
gensols = []
|
| 112 |
+
# Keep track of when to use sin or cos for nonzero imroot
|
| 113 |
+
for i, reroot, imroot in collectterms:
|
| 114 |
+
if imroot == 0:
|
| 115 |
+
gensols.append(ln(x)**i*x**reroot)
|
| 116 |
+
else:
|
| 117 |
+
sin_form = ln(x)**i*x**reroot*sin(abs(imroot)*ln(x))
|
| 118 |
+
if sin_form in gensols:
|
| 119 |
+
cos_form = ln(x)**i*x**reroot*cos(imroot*ln(x))
|
| 120 |
+
gensols.append(cos_form)
|
| 121 |
+
else:
|
| 122 |
+
gensols.append(sin_form)
|
| 123 |
+
return gsol, gensols
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def _solve_variation_of_parameters(eq, func, roots, homogen_sol, order, match_obj, simplify_flag=True):
|
| 127 |
+
r"""
|
| 128 |
+
Helper function for the method of variation of parameters and nonhomogeneous euler eq.
|
| 129 |
+
|
| 130 |
+
See the
|
| 131 |
+
:py:meth:`~sympy.solvers.ode.single.NthLinearConstantCoeffVariationOfParameters`
|
| 132 |
+
docstring for more information on this method.
|
| 133 |
+
|
| 134 |
+
The parameter are ``match_obj`` should be a dictionary that has the following
|
| 135 |
+
keys:
|
| 136 |
+
|
| 137 |
+
``list``
|
| 138 |
+
A list of solutions to the homogeneous equation.
|
| 139 |
+
|
| 140 |
+
``sol``
|
| 141 |
+
The general solution.
|
| 142 |
+
|
| 143 |
+
"""
|
| 144 |
+
f = func.func
|
| 145 |
+
x = func.args[0]
|
| 146 |
+
r = match_obj
|
| 147 |
+
psol = 0
|
| 148 |
+
wr = wronskian(roots, x)
|
| 149 |
+
|
| 150 |
+
if simplify_flag:
|
| 151 |
+
wr = simplify(wr) # We need much better simplification for
|
| 152 |
+
# some ODEs. See issue 4662, for example.
|
| 153 |
+
# To reduce commonly occurring sin(x)**2 + cos(x)**2 to 1
|
| 154 |
+
wr = trigsimp(wr, deep=True, recursive=True)
|
| 155 |
+
if not wr:
|
| 156 |
+
# The wronskian will be 0 iff the solutions are not linearly
|
| 157 |
+
# independent.
|
| 158 |
+
raise NotImplementedError("Cannot find " + str(order) +
|
| 159 |
+
" solutions to the homogeneous equation necessary to apply " +
|
| 160 |
+
"variation of parameters to " + str(eq) + " (Wronskian == 0)")
|
| 161 |
+
if len(roots) != order:
|
| 162 |
+
raise NotImplementedError("Cannot find " + str(order) +
|
| 163 |
+
" solutions to the homogeneous equation necessary to apply " +
|
| 164 |
+
"variation of parameters to " +
|
| 165 |
+
str(eq) + " (number of terms != order)")
|
| 166 |
+
negoneterm = S.NegativeOne**(order)
|
| 167 |
+
for i in roots:
|
| 168 |
+
psol += negoneterm*Integral(wronskian([sol for sol in roots if sol != i], x)*r[-1]/wr, x)*i/r[order]
|
| 169 |
+
negoneterm *= -1
|
| 170 |
+
|
| 171 |
+
if simplify_flag:
|
| 172 |
+
psol = simplify(psol)
|
| 173 |
+
psol = trigsimp(psol, deep=True)
|
| 174 |
+
return Eq(f(x), homogen_sol.rhs + psol)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def _get_const_characteristic_eq_sols(r, func, order):
|
| 178 |
+
r"""
|
| 179 |
+
Returns the roots of characteristic equation of constant coefficient
|
| 180 |
+
linear ODE and list of collectterms which is later on used by simplification
|
| 181 |
+
to use collect on solution.
|
| 182 |
+
|
| 183 |
+
The parameter `r` is a dict of order:coeff terms, where order is the order of the
|
| 184 |
+
derivative on each term, and coeff is the coefficient of that derivative.
|
| 185 |
+
|
| 186 |
+
"""
|
| 187 |
+
x = func.args[0]
|
| 188 |
+
# First, set up characteristic equation.
|
| 189 |
+
chareq, symbol = S.Zero, Dummy('x')
|
| 190 |
+
|
| 191 |
+
for i in r.keys():
|
| 192 |
+
if isinstance(i, str) or i < 0:
|
| 193 |
+
pass
|
| 194 |
+
else:
|
| 195 |
+
chareq += r[i]*symbol**i
|
| 196 |
+
|
| 197 |
+
chareq = Poly(chareq, symbol)
|
| 198 |
+
# Can't just call roots because it doesn't return rootof for unsolveable
|
| 199 |
+
# polynomials.
|
| 200 |
+
chareqroots = roots(chareq, multiple=True)
|
| 201 |
+
if len(chareqroots) != order:
|
| 202 |
+
chareqroots = [rootof(chareq, k) for k in range(chareq.degree())]
|
| 203 |
+
|
| 204 |
+
chareq_is_complex = not all(i.is_real for i in chareq.all_coeffs())
|
| 205 |
+
|
| 206 |
+
# Create a dict root: multiplicity or charroots
|
| 207 |
+
charroots = defaultdict(int)
|
| 208 |
+
for root in chareqroots:
|
| 209 |
+
charroots[root] += 1
|
| 210 |
+
# We need to keep track of terms so we can run collect() at the end.
|
| 211 |
+
# This is necessary for constantsimp to work properly.
|
| 212 |
+
collectterms = []
|
| 213 |
+
gensols = []
|
| 214 |
+
conjugate_roots = [] # used to prevent double-use of conjugate roots
|
| 215 |
+
# Loop over roots in theorder provided by roots/rootof...
|
| 216 |
+
for root in chareqroots:
|
| 217 |
+
# but don't repoeat multiple roots.
|
| 218 |
+
if root not in charroots:
|
| 219 |
+
continue
|
| 220 |
+
multiplicity = charroots.pop(root)
|
| 221 |
+
for i in range(multiplicity):
|
| 222 |
+
if chareq_is_complex:
|
| 223 |
+
gensols.append(x**i*exp(root*x))
|
| 224 |
+
collectterms = [(i, root, 0)] + collectterms
|
| 225 |
+
continue
|
| 226 |
+
reroot = re(root)
|
| 227 |
+
imroot = im(root)
|
| 228 |
+
if imroot.has(atan2) and reroot.has(atan2):
|
| 229 |
+
# Remove this condition when re and im stop returning
|
| 230 |
+
# circular atan2 usages.
|
| 231 |
+
gensols.append(x**i*exp(root*x))
|
| 232 |
+
collectterms = [(i, root, 0)] + collectterms
|
| 233 |
+
else:
|
| 234 |
+
if root in conjugate_roots:
|
| 235 |
+
collectterms = [(i, reroot, imroot)] + collectterms
|
| 236 |
+
continue
|
| 237 |
+
if imroot == 0:
|
| 238 |
+
gensols.append(x**i*exp(reroot*x))
|
| 239 |
+
collectterms = [(i, reroot, 0)] + collectterms
|
| 240 |
+
continue
|
| 241 |
+
conjugate_roots.append(conjugate(root))
|
| 242 |
+
gensols.append(x**i*exp(reroot*x) * sin(abs(imroot) * x))
|
| 243 |
+
gensols.append(x**i*exp(reroot*x) * cos( imroot * x))
|
| 244 |
+
|
| 245 |
+
# This ordering is important
|
| 246 |
+
collectterms = [(i, reroot, imroot)] + collectterms
|
| 247 |
+
return gensols, collectterms
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
# Ideally these kind of simplification functions shouldn't be part of solvers.
|
| 251 |
+
# odesimp should be improved to handle these kind of specific simplifications.
|
| 252 |
+
def _get_simplified_sol(sol, func, collectterms):
|
| 253 |
+
r"""
|
| 254 |
+
Helper function which collects the solution on
|
| 255 |
+
collectterms. Ideally this should be handled by odesimp.It is used
|
| 256 |
+
only when the simplify is set to True in dsolve.
|
| 257 |
+
|
| 258 |
+
The parameter ``collectterms`` is a list of tuple (i, reroot, imroot) where `i` is
|
| 259 |
+
the multiplicity of the root, reroot is real part and imroot being the imaginary part.
|
| 260 |
+
|
| 261 |
+
"""
|
| 262 |
+
f = func.func
|
| 263 |
+
x = func.args[0]
|
| 264 |
+
collectterms.sort(key=default_sort_key)
|
| 265 |
+
collectterms.reverse()
|
| 266 |
+
assert len(sol) == 1 and sol[0].lhs == f(x)
|
| 267 |
+
sol = sol[0].rhs
|
| 268 |
+
sol = expand_mul(sol)
|
| 269 |
+
for i, reroot, imroot in collectterms:
|
| 270 |
+
sol = collect(sol, x**i*exp(reroot*x)*sin(abs(imroot)*x))
|
| 271 |
+
sol = collect(sol, x**i*exp(reroot*x)*cos(imroot*x))
|
| 272 |
+
for i, reroot, imroot in collectterms:
|
| 273 |
+
sol = collect(sol, x**i*exp(reroot*x))
|
| 274 |
+
sol = powsimp(sol)
|
| 275 |
+
return Eq(f(x), sol)
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
def _undetermined_coefficients_match(expr, x, func=None, eq_homogeneous=S.Zero):
|
| 279 |
+
r"""
|
| 280 |
+
Returns a trial function match if undetermined coefficients can be applied
|
| 281 |
+
to ``expr``, and ``None`` otherwise.
|
| 282 |
+
|
| 283 |
+
A trial expression can be found for an expression for use with the method
|
| 284 |
+
of undetermined coefficients if the expression is an
|
| 285 |
+
additive/multiplicative combination of constants, polynomials in `x` (the
|
| 286 |
+
independent variable of expr), `\sin(a x + b)`, `\cos(a x + b)`, and
|
| 287 |
+
`e^{a x}` terms (in other words, it has a finite number of linearly
|
| 288 |
+
independent derivatives).
|
| 289 |
+
|
| 290 |
+
Note that you may still need to multiply each term returned here by
|
| 291 |
+
sufficient `x` to make it linearly independent with the solutions to the
|
| 292 |
+
homogeneous equation.
|
| 293 |
+
|
| 294 |
+
This is intended for internal use by ``undetermined_coefficients`` hints.
|
| 295 |
+
|
| 296 |
+
SymPy currently has no way to convert `\sin^n(x) \cos^m(y)` into a sum of
|
| 297 |
+
only `\sin(a x)` and `\cos(b x)` terms, so these are not implemented. So,
|
| 298 |
+
for example, you will need to manually convert `\sin^2(x)` into `[1 +
|
| 299 |
+
\cos(2 x)]/2` to properly apply the method of undetermined coefficients on
|
| 300 |
+
it.
|
| 301 |
+
|
| 302 |
+
Examples
|
| 303 |
+
========
|
| 304 |
+
|
| 305 |
+
>>> from sympy import log, exp
|
| 306 |
+
>>> from sympy.solvers.ode.nonhomogeneous import _undetermined_coefficients_match
|
| 307 |
+
>>> from sympy.abc import x
|
| 308 |
+
>>> _undetermined_coefficients_match(9*x*exp(x) + exp(-x), x)
|
| 309 |
+
{'test': True, 'trialset': {x*exp(x), exp(-x), exp(x)}}
|
| 310 |
+
>>> _undetermined_coefficients_match(log(x), x)
|
| 311 |
+
{'test': False}
|
| 312 |
+
|
| 313 |
+
"""
|
| 314 |
+
a = Wild('a', exclude=[x])
|
| 315 |
+
b = Wild('b', exclude=[x])
|
| 316 |
+
expr = powsimp(expr, combine='exp') # exp(x)*exp(2*x + 1) => exp(3*x + 1)
|
| 317 |
+
retdict = {}
|
| 318 |
+
|
| 319 |
+
def _test_term(expr, x):
|
| 320 |
+
r"""
|
| 321 |
+
Test if ``expr`` fits the proper form for undetermined coefficients.
|
| 322 |
+
"""
|
| 323 |
+
if not expr.has(x):
|
| 324 |
+
return True
|
| 325 |
+
elif expr.is_Add:
|
| 326 |
+
return all(_test_term(i, x) for i in expr.args)
|
| 327 |
+
elif expr.is_Mul:
|
| 328 |
+
if expr.has(sin, cos):
|
| 329 |
+
foundtrig = False
|
| 330 |
+
# Make sure that there is only one trig function in the args.
|
| 331 |
+
# See the docstring.
|
| 332 |
+
for i in expr.args:
|
| 333 |
+
if i.has(sin, cos):
|
| 334 |
+
if foundtrig:
|
| 335 |
+
return False
|
| 336 |
+
else:
|
| 337 |
+
foundtrig = True
|
| 338 |
+
return all(_test_term(i, x) for i in expr.args)
|
| 339 |
+
elif expr.is_Function:
|
| 340 |
+
if expr.func in (sin, cos, exp, sinh, cosh):
|
| 341 |
+
if expr.args[0].match(a*x + b):
|
| 342 |
+
return True
|
| 343 |
+
else:
|
| 344 |
+
return False
|
| 345 |
+
else:
|
| 346 |
+
return False
|
| 347 |
+
elif expr.is_Pow and expr.base.is_Symbol and expr.exp.is_Integer and \
|
| 348 |
+
expr.exp >= 0:
|
| 349 |
+
return True
|
| 350 |
+
elif expr.is_Pow and expr.base.is_number:
|
| 351 |
+
if expr.exp.match(a*x + b):
|
| 352 |
+
return True
|
| 353 |
+
else:
|
| 354 |
+
return False
|
| 355 |
+
elif expr.is_Symbol or expr.is_number:
|
| 356 |
+
return True
|
| 357 |
+
else:
|
| 358 |
+
return False
|
| 359 |
+
|
| 360 |
+
def _get_trial_set(expr, x, exprs=set()):
|
| 361 |
+
r"""
|
| 362 |
+
Returns a set of trial terms for undetermined coefficients.
|
| 363 |
+
|
| 364 |
+
The idea behind undetermined coefficients is that the terms expression
|
| 365 |
+
repeat themselves after a finite number of derivatives, except for the
|
| 366 |
+
coefficients (they are linearly dependent). So if we collect these,
|
| 367 |
+
we should have the terms of our trial function.
|
| 368 |
+
"""
|
| 369 |
+
def _remove_coefficient(expr, x):
|
| 370 |
+
r"""
|
| 371 |
+
Returns the expression without a coefficient.
|
| 372 |
+
|
| 373 |
+
Similar to expr.as_independent(x)[1], except it only works
|
| 374 |
+
multiplicatively.
|
| 375 |
+
"""
|
| 376 |
+
term = S.One
|
| 377 |
+
if expr.is_Mul:
|
| 378 |
+
for i in expr.args:
|
| 379 |
+
if i.has(x):
|
| 380 |
+
term *= i
|
| 381 |
+
elif expr.has(x):
|
| 382 |
+
term = expr
|
| 383 |
+
return term
|
| 384 |
+
|
| 385 |
+
expr = expand_mul(expr)
|
| 386 |
+
if expr.is_Add:
|
| 387 |
+
for term in expr.args:
|
| 388 |
+
if _remove_coefficient(term, x) in exprs:
|
| 389 |
+
pass
|
| 390 |
+
else:
|
| 391 |
+
exprs.add(_remove_coefficient(term, x))
|
| 392 |
+
exprs = exprs.union(_get_trial_set(term, x, exprs))
|
| 393 |
+
else:
|
| 394 |
+
term = _remove_coefficient(expr, x)
|
| 395 |
+
tmpset = exprs.union({term})
|
| 396 |
+
oldset = set()
|
| 397 |
+
while tmpset != oldset:
|
| 398 |
+
# If you get stuck in this loop, then _test_term is probably
|
| 399 |
+
# broken
|
| 400 |
+
oldset = tmpset.copy()
|
| 401 |
+
expr = expr.diff(x)
|
| 402 |
+
term = _remove_coefficient(expr, x)
|
| 403 |
+
if term.is_Add:
|
| 404 |
+
tmpset = tmpset.union(_get_trial_set(term, x, tmpset))
|
| 405 |
+
else:
|
| 406 |
+
tmpset.add(term)
|
| 407 |
+
exprs = tmpset
|
| 408 |
+
return exprs
|
| 409 |
+
|
| 410 |
+
def is_homogeneous_solution(term):
|
| 411 |
+
r""" This function checks whether the given trialset contains any root
|
| 412 |
+
of homogeneous equation"""
|
| 413 |
+
return expand(sub_func_doit(eq_homogeneous, func, term)).is_zero
|
| 414 |
+
|
| 415 |
+
retdict['test'] = _test_term(expr, x)
|
| 416 |
+
if retdict['test']:
|
| 417 |
+
# Try to generate a list of trial solutions that will have the
|
| 418 |
+
# undetermined coefficients. Note that if any of these are not linearly
|
| 419 |
+
# independent with any of the solutions to the homogeneous equation,
|
| 420 |
+
# then they will need to be multiplied by sufficient x to make them so.
|
| 421 |
+
# This function DOES NOT do that (it doesn't even look at the
|
| 422 |
+
# homogeneous equation).
|
| 423 |
+
temp_set = set()
|
| 424 |
+
for i in Add.make_args(expr):
|
| 425 |
+
act = _get_trial_set(i, x)
|
| 426 |
+
if eq_homogeneous is not S.Zero:
|
| 427 |
+
while any(is_homogeneous_solution(ts) for ts in act):
|
| 428 |
+
act = {x*ts for ts in act}
|
| 429 |
+
temp_set = temp_set.union(act)
|
| 430 |
+
|
| 431 |
+
retdict['trialset'] = temp_set
|
| 432 |
+
return retdict
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
def _solve_undetermined_coefficients(eq, func, order, match, trialset):
|
| 436 |
+
r"""
|
| 437 |
+
Helper function for the method of undetermined coefficients.
|
| 438 |
+
|
| 439 |
+
See the
|
| 440 |
+
:py:meth:`~sympy.solvers.ode.single.NthLinearConstantCoeffUndeterminedCoefficients`
|
| 441 |
+
docstring for more information on this method.
|
| 442 |
+
|
| 443 |
+
The parameter ``trialset`` is the set of trial functions as returned by
|
| 444 |
+
``_undetermined_coefficients_match()['trialset']``.
|
| 445 |
+
|
| 446 |
+
The parameter ``match`` should be a dictionary that has the following
|
| 447 |
+
keys:
|
| 448 |
+
|
| 449 |
+
``list``
|
| 450 |
+
A list of solutions to the homogeneous equation.
|
| 451 |
+
|
| 452 |
+
``sol``
|
| 453 |
+
The general solution.
|
| 454 |
+
|
| 455 |
+
"""
|
| 456 |
+
r = match
|
| 457 |
+
coeffs = numbered_symbols('a', cls=Dummy)
|
| 458 |
+
coefflist = []
|
| 459 |
+
gensols = r['list']
|
| 460 |
+
gsol = r['sol']
|
| 461 |
+
f = func.func
|
| 462 |
+
x = func.args[0]
|
| 463 |
+
|
| 464 |
+
if len(gensols) != order:
|
| 465 |
+
raise NotImplementedError("Cannot find " + str(order) +
|
| 466 |
+
" solutions to the homogeneous equation necessary to apply" +
|
| 467 |
+
" undetermined coefficients to " + str(eq) +
|
| 468 |
+
" (number of terms != order)")
|
| 469 |
+
|
| 470 |
+
trialfunc = 0
|
| 471 |
+
for i in trialset:
|
| 472 |
+
c = next(coeffs)
|
| 473 |
+
coefflist.append(c)
|
| 474 |
+
trialfunc += c*i
|
| 475 |
+
|
| 476 |
+
eqs = sub_func_doit(eq, f(x), trialfunc)
|
| 477 |
+
|
| 478 |
+
coeffsdict = dict(list(zip(trialset, [0]*(len(trialset) + 1))))
|
| 479 |
+
|
| 480 |
+
eqs = _mexpand(eqs)
|
| 481 |
+
|
| 482 |
+
for i in Add.make_args(eqs):
|
| 483 |
+
s = separatevars(i, dict=True, symbols=[x])
|
| 484 |
+
if coeffsdict.get(s[x]):
|
| 485 |
+
coeffsdict[s[x]] += s['coeff']
|
| 486 |
+
else:
|
| 487 |
+
coeffsdict[s[x]] = s['coeff']
|
| 488 |
+
|
| 489 |
+
coeffvals = solve(list(coeffsdict.values()), coefflist)
|
| 490 |
+
|
| 491 |
+
if not coeffvals:
|
| 492 |
+
raise NotImplementedError(
|
| 493 |
+
"Could not solve `%s` using the "
|
| 494 |
+
"method of undetermined coefficients "
|
| 495 |
+
"(unable to solve for coefficients)." % eq)
|
| 496 |
+
|
| 497 |
+
psol = trialfunc.subs(coeffvals)
|
| 498 |
+
|
| 499 |
+
return Eq(f(x), gsol.rhs + psol)
|
pllava/lib/python3.10/site-packages/sympy/solvers/ode/ode.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
pllava/lib/python3.10/site-packages/sympy/solvers/ode/riccati.py
ADDED
|
@@ -0,0 +1,893 @@
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r"""
|
| 2 |
+
This module contains :py:meth:`~sympy.solvers.ode.riccati.solve_riccati`,
|
| 3 |
+
a function which gives all rational particular solutions to first order
|
| 4 |
+
Riccati ODEs. A general first order Riccati ODE is given by -
|
| 5 |
+
|
| 6 |
+
.. math:: y' = b_0(x) + b_1(x)w + b_2(x)w^2
|
| 7 |
+
|
| 8 |
+
where `b_0, b_1` and `b_2` can be arbitrary rational functions of `x`
|
| 9 |
+
with `b_2 \ne 0`. When `b_2 = 0`, the equation is not a Riccati ODE
|
| 10 |
+
anymore and becomes a Linear ODE. Similarly, when `b_0 = 0`, the equation
|
| 11 |
+
is a Bernoulli ODE. The algorithm presented below can find rational
|
| 12 |
+
solution(s) to all ODEs with `b_2 \ne 0` that have a rational solution,
|
| 13 |
+
or prove that no rational solution exists for the equation.
|
| 14 |
+
|
| 15 |
+
Background
|
| 16 |
+
==========
|
| 17 |
+
|
| 18 |
+
A Riccati equation can be transformed to its normal form
|
| 19 |
+
|
| 20 |
+
.. math:: y' + y^2 = a(x)
|
| 21 |
+
|
| 22 |
+
using the transformation
|
| 23 |
+
|
| 24 |
+
.. math:: y = -b_2(x) - \frac{b'_2(x)}{2 b_2(x)} - \frac{b_1(x)}{2}
|
| 25 |
+
|
| 26 |
+
where `a(x)` is given by
|
| 27 |
+
|
| 28 |
+
.. math:: a(x) = \frac{1}{4}\left(\frac{b_2'}{b_2} + b_1\right)^2 - \frac{1}{2}\left(\frac{b_2'}{b_2} + b_1\right)' - b_0 b_2
|
| 29 |
+
|
| 30 |
+
Thus, we can develop an algorithm to solve for the Riccati equation
|
| 31 |
+
in its normal form, which would in turn give us the solution for
|
| 32 |
+
the original Riccati equation.
|
| 33 |
+
|
| 34 |
+
Algorithm
|
| 35 |
+
=========
|
| 36 |
+
|
| 37 |
+
The algorithm implemented here is presented in the Ph.D thesis
|
| 38 |
+
"Rational and Algebraic Solutions of First-Order Algebraic ODEs"
|
| 39 |
+
by N. Thieu Vo. The entire thesis can be found here -
|
| 40 |
+
https://www3.risc.jku.at/publications/download/risc_5387/PhDThesisThieu.pdf
|
| 41 |
+
|
| 42 |
+
We have only implemented the Rational Riccati solver (Algorithm 11,
|
| 43 |
+
Pg 78-82 in Thesis). Before we proceed towards the implementation
|
| 44 |
+
of the algorithm, a few definitions to understand are -
|
| 45 |
+
|
| 46 |
+
1. Valuation of a Rational Function at `\infty`:
|
| 47 |
+
The valuation of a rational function `p(x)` at `\infty` is equal
|
| 48 |
+
to the difference between the degree of the denominator and the
|
| 49 |
+
numerator of `p(x)`.
|
| 50 |
+
|
| 51 |
+
NOTE: A general definition of valuation of a rational function
|
| 52 |
+
at any value of `x` can be found in Pg 63 of the thesis, but
|
| 53 |
+
is not of any interest for this algorithm.
|
| 54 |
+
|
| 55 |
+
2. Zeros and Poles of a Rational Function:
|
| 56 |
+
Let `a(x) = \frac{S(x)}{T(x)}, T \ne 0` be a rational function
|
| 57 |
+
of `x`. Then -
|
| 58 |
+
|
| 59 |
+
a. The Zeros of `a(x)` are the roots of `S(x)`.
|
| 60 |
+
b. The Poles of `a(x)` are the roots of `T(x)`. However, `\infty`
|
| 61 |
+
can also be a pole of a(x). We say that `a(x)` has a pole at
|
| 62 |
+
`\infty` if `a(\frac{1}{x})` has a pole at 0.
|
| 63 |
+
|
| 64 |
+
Every pole is associated with an order that is equal to the multiplicity
|
| 65 |
+
of its appearance as a root of `T(x)`. A pole is called a simple pole if
|
| 66 |
+
it has an order 1. Similarly, a pole is called a multiple pole if it has
|
| 67 |
+
an order `\ge` 2.
|
| 68 |
+
|
| 69 |
+
Necessary Conditions
|
| 70 |
+
====================
|
| 71 |
+
|
| 72 |
+
For a Riccati equation in its normal form,
|
| 73 |
+
|
| 74 |
+
.. math:: y' + y^2 = a(x)
|
| 75 |
+
|
| 76 |
+
we can define
|
| 77 |
+
|
| 78 |
+
a. A pole is called a movable pole if it is a pole of `y(x)` and is not
|
| 79 |
+
a pole of `a(x)`.
|
| 80 |
+
b. Similarly, a pole is called a non-movable pole if it is a pole of both
|
| 81 |
+
`y(x)` and `a(x)`.
|
| 82 |
+
|
| 83 |
+
Then, the algorithm states that a rational solution exists only if -
|
| 84 |
+
|
| 85 |
+
a. Every pole of `a(x)` must be either a simple pole or a multiple pole
|
| 86 |
+
of even order.
|
| 87 |
+
b. The valuation of `a(x)` at `\infty` must be even or be `\ge` 2.
|
| 88 |
+
|
| 89 |
+
This algorithm finds all possible rational solutions for the Riccati ODE.
|
| 90 |
+
If no rational solutions are found, it means that no rational solutions
|
| 91 |
+
exist.
|
| 92 |
+
|
| 93 |
+
The algorithm works for Riccati ODEs where the coefficients are rational
|
| 94 |
+
functions in the independent variable `x` with rational number coefficients
|
| 95 |
+
i.e. in `Q(x)`. The coefficients in the rational function cannot be floats,
|
| 96 |
+
irrational numbers, symbols or any other kind of expression. The reasons
|
| 97 |
+
for this are -
|
| 98 |
+
|
| 99 |
+
1. When using symbols, different symbols could take the same value and this
|
| 100 |
+
would affect the multiplicity of poles if symbols are present here.
|
| 101 |
+
|
| 102 |
+
2. An integer degree bound is required to calculate a polynomial solution
|
| 103 |
+
to an auxiliary differential equation, which in turn gives the particular
|
| 104 |
+
solution for the original ODE. If symbols/floats/irrational numbers are
|
| 105 |
+
present, we cannot determine if the expression for the degree bound is an
|
| 106 |
+
integer or not.
|
| 107 |
+
|
| 108 |
+
Solution
|
| 109 |
+
========
|
| 110 |
+
|
| 111 |
+
With these definitions, we can state a general form for the solution of
|
| 112 |
+
the equation. `y(x)` must have the form -
|
| 113 |
+
|
| 114 |
+
.. math:: y(x) = \sum_{i=1}^{n} \sum_{j=1}^{r_i} \frac{c_{ij}}{(x - x_i)^j} + \sum_{i=1}^{m} \frac{1}{x - \chi_i} + \sum_{i=0}^{N} d_i x^i
|
| 115 |
+
|
| 116 |
+
where `x_1, x_2, \dots, x_n` are non-movable poles of `a(x)`,
|
| 117 |
+
`\chi_1, \chi_2, \dots, \chi_m` are movable poles of `a(x)`, and the values
|
| 118 |
+
of `N, n, r_1, r_2, \dots, r_n` can be determined from `a(x)`. The
|
| 119 |
+
coefficient vectors `(d_0, d_1, \dots, d_N)` and `(c_{i1}, c_{i2}, \dots, c_{i r_i})`
|
| 120 |
+
can be determined from `a(x)`. We will have 2 choices each of these vectors
|
| 121 |
+
and part of the procedure is figuring out which of the 2 should be used
|
| 122 |
+
to get the solution correctly.
|
| 123 |
+
|
| 124 |
+
Implementation
|
| 125 |
+
==============
|
| 126 |
+
|
| 127 |
+
In this implementation, we use ``Poly`` to represent a rational function
|
| 128 |
+
rather than using ``Expr`` since ``Poly`` is much faster. Since we cannot
|
| 129 |
+
represent rational functions directly using ``Poly``, we instead represent
|
| 130 |
+
a rational function with 2 ``Poly`` objects - one for its numerator and
|
| 131 |
+
the other for its denominator.
|
| 132 |
+
|
| 133 |
+
The code is written to match the steps given in the thesis (Pg 82)
|
| 134 |
+
|
| 135 |
+
Step 0 : Match the equation -
|
| 136 |
+
Find `b_0, b_1` and `b_2`. If `b_2 = 0` or no such functions exist, raise
|
| 137 |
+
an error
|
| 138 |
+
|
| 139 |
+
Step 1 : Transform the equation to its normal form as explained in the
|
| 140 |
+
theory section.
|
| 141 |
+
|
| 142 |
+
Step 2 : Initialize an empty set of solutions, ``sol``.
|
| 143 |
+
|
| 144 |
+
Step 3 : If `a(x) = 0`, append `\frac{1}/{(x - C1)}` to ``sol``.
|
| 145 |
+
|
| 146 |
+
Step 4 : If `a(x)` is a rational non-zero number, append `\pm \sqrt{a}`
|
| 147 |
+
to ``sol``.
|
| 148 |
+
|
| 149 |
+
Step 5 : Find the poles and their multiplicities of `a(x)`. Let
|
| 150 |
+
the number of poles be `n`. Also find the valuation of `a(x)` at
|
| 151 |
+
`\infty` using ``val_at_inf``.
|
| 152 |
+
|
| 153 |
+
NOTE: Although the algorithm considers `\infty` as a pole, it is
|
| 154 |
+
not mentioned if it a part of the set of finite poles. `\infty`
|
| 155 |
+
is NOT a part of the set of finite poles. If a pole exists at
|
| 156 |
+
`\infty`, we use its multiplicity to find the laurent series of
|
| 157 |
+
`a(x)` about `\infty`.
|
| 158 |
+
|
| 159 |
+
Step 6 : Find `n` c-vectors (one for each pole) and 1 d-vector using
|
| 160 |
+
``construct_c`` and ``construct_d``. Now, determine all the ``2**(n + 1)``
|
| 161 |
+
combinations of choosing between 2 choices for each of the `n` c-vectors
|
| 162 |
+
and 1 d-vector.
|
| 163 |
+
|
| 164 |
+
NOTE: The equation for `d_{-1}` in Case 4 (Pg 80) has a printinig
|
| 165 |
+
mistake. The term `- d_N` must be replaced with `-N d_N`. The same
|
| 166 |
+
has been explained in the code as well.
|
| 167 |
+
|
| 168 |
+
For each of these above combinations, do
|
| 169 |
+
|
| 170 |
+
Step 8 : Compute `m` in ``compute_m_ybar``. `m` is the degree bound of
|
| 171 |
+
the polynomial solution we must find for the auxiliary equation.
|
| 172 |
+
|
| 173 |
+
Step 9 : In ``compute_m_ybar``, compute ybar as well where ``ybar`` is
|
| 174 |
+
one part of y(x) -
|
| 175 |
+
|
| 176 |
+
.. math:: \overline{y}(x) = \sum_{i=1}^{n} \sum_{j=1}^{r_i} \frac{c_{ij}}{(x - x_i)^j} + \sum_{i=0}^{N} d_i x^i
|
| 177 |
+
|
| 178 |
+
Step 10 : If `m` is a non-negative integer -
|
| 179 |
+
|
| 180 |
+
Step 11: Find a polynomial solution of degree `m` for the auxiliary equation.
|
| 181 |
+
|
| 182 |
+
There are 2 cases possible -
|
| 183 |
+
|
| 184 |
+
a. `m` is a non-negative integer: We can solve for the coefficients
|
| 185 |
+
in `p(x)` using Undetermined Coefficients.
|
| 186 |
+
|
| 187 |
+
b. `m` is not a non-negative integer: In this case, we cannot find
|
| 188 |
+
a polynomial solution to the auxiliary equation, and hence, we ignore
|
| 189 |
+
this value of `m`.
|
| 190 |
+
|
| 191 |
+
Step 12 : For each `p(x)` that exists, append `ybar + \frac{p'(x)}{p(x)}`
|
| 192 |
+
to ``sol``.
|
| 193 |
+
|
| 194 |
+
Step 13 : For each solution in ``sol``, apply an inverse transformation,
|
| 195 |
+
so that the solutions of the original equation are found using the
|
| 196 |
+
solutions of the equation in its normal form.
|
| 197 |
+
"""
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
from itertools import product
|
| 201 |
+
from sympy.core import S
|
| 202 |
+
from sympy.core.add import Add
|
| 203 |
+
from sympy.core.numbers import oo, Float
|
| 204 |
+
from sympy.core.function import count_ops
|
| 205 |
+
from sympy.core.relational import Eq
|
| 206 |
+
from sympy.core.symbol import symbols, Symbol, Dummy
|
| 207 |
+
from sympy.functions import sqrt, exp
|
| 208 |
+
from sympy.functions.elementary.complexes import sign
|
| 209 |
+
from sympy.integrals.integrals import Integral
|
| 210 |
+
from sympy.polys.domains import ZZ
|
| 211 |
+
from sympy.polys.polytools import Poly
|
| 212 |
+
from sympy.polys.polyroots import roots
|
| 213 |
+
from sympy.solvers.solveset import linsolve
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def riccati_normal(w, x, b1, b2):
|
| 217 |
+
"""
|
| 218 |
+
Given a solution `w(x)` to the equation
|
| 219 |
+
|
| 220 |
+
.. math:: w'(x) = b_0(x) + b_1(x)*w(x) + b_2(x)*w(x)^2
|
| 221 |
+
|
| 222 |
+
and rational function coefficients `b_1(x)` and
|
| 223 |
+
`b_2(x)`, this function transforms the solution to
|
| 224 |
+
give a solution `y(x)` for its corresponding normal
|
| 225 |
+
Riccati ODE
|
| 226 |
+
|
| 227 |
+
.. math:: y'(x) + y(x)^2 = a(x)
|
| 228 |
+
|
| 229 |
+
using the transformation
|
| 230 |
+
|
| 231 |
+
.. math:: y(x) = -b_2(x)*w(x) - b'_2(x)/(2*b_2(x)) - b_1(x)/2
|
| 232 |
+
"""
|
| 233 |
+
return -b2*w - b2.diff(x)/(2*b2) - b1/2
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def riccati_inverse_normal(y, x, b1, b2, bp=None):
|
| 237 |
+
"""
|
| 238 |
+
Inverse transforming the solution to the normal
|
| 239 |
+
Riccati ODE to get the solution to the Riccati ODE.
|
| 240 |
+
"""
|
| 241 |
+
# bp is the expression which is independent of the solution
|
| 242 |
+
# and hence, it need not be computed again
|
| 243 |
+
if bp is None:
|
| 244 |
+
bp = -b2.diff(x)/(2*b2**2) - b1/(2*b2)
|
| 245 |
+
# w(x) = -y(x)/b2(x) - b2'(x)/(2*b2(x)^2) - b1(x)/(2*b2(x))
|
| 246 |
+
return -y/b2 + bp
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def riccati_reduced(eq, f, x):
|
| 250 |
+
"""
|
| 251 |
+
Convert a Riccati ODE into its corresponding
|
| 252 |
+
normal Riccati ODE.
|
| 253 |
+
"""
|
| 254 |
+
match, funcs = match_riccati(eq, f, x)
|
| 255 |
+
# If equation is not a Riccati ODE, exit
|
| 256 |
+
if not match:
|
| 257 |
+
return False
|
| 258 |
+
# Using the rational functions, find the expression for a(x)
|
| 259 |
+
b0, b1, b2 = funcs
|
| 260 |
+
a = -b0*b2 + b1**2/4 - b1.diff(x)/2 + 3*b2.diff(x)**2/(4*b2**2) + b1*b2.diff(x)/(2*b2) - \
|
| 261 |
+
b2.diff(x, 2)/(2*b2)
|
| 262 |
+
# Normal form of Riccati ODE is f'(x) + f(x)^2 = a(x)
|
| 263 |
+
return f(x).diff(x) + f(x)**2 - a
|
| 264 |
+
|
| 265 |
+
def linsolve_dict(eq, syms):
|
| 266 |
+
"""
|
| 267 |
+
Get the output of linsolve as a dict
|
| 268 |
+
"""
|
| 269 |
+
# Convert tuple type return value of linsolve
|
| 270 |
+
# to a dictionary for ease of use
|
| 271 |
+
sol = linsolve(eq, syms)
|
| 272 |
+
if not sol:
|
| 273 |
+
return {}
|
| 274 |
+
return dict(zip(syms, list(sol)[0]))
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
def match_riccati(eq, f, x):
|
| 278 |
+
"""
|
| 279 |
+
A function that matches and returns the coefficients
|
| 280 |
+
if an equation is a Riccati ODE
|
| 281 |
+
|
| 282 |
+
Parameters
|
| 283 |
+
==========
|
| 284 |
+
|
| 285 |
+
eq: Equation to be matched
|
| 286 |
+
f: Dependent variable
|
| 287 |
+
x: Independent variable
|
| 288 |
+
|
| 289 |
+
Returns
|
| 290 |
+
=======
|
| 291 |
+
|
| 292 |
+
match: True if equation is a Riccati ODE, False otherwise
|
| 293 |
+
funcs: [b0, b1, b2] if match is True, [] otherwise. Here,
|
| 294 |
+
b0, b1 and b2 are rational functions which match the equation.
|
| 295 |
+
"""
|
| 296 |
+
# Group terms based on f(x)
|
| 297 |
+
if isinstance(eq, Eq):
|
| 298 |
+
eq = eq.lhs - eq.rhs
|
| 299 |
+
eq = eq.expand().collect(f(x))
|
| 300 |
+
cf = eq.coeff(f(x).diff(x))
|
| 301 |
+
|
| 302 |
+
# There must be an f(x).diff(x) term.
|
| 303 |
+
# eq must be an Add object since we are using the expanded
|
| 304 |
+
# equation and it must have atleast 2 terms (b2 != 0)
|
| 305 |
+
if cf != 0 and isinstance(eq, Add):
|
| 306 |
+
|
| 307 |
+
# Divide all coefficients by the coefficient of f(x).diff(x)
|
| 308 |
+
# and add the terms again to get the same equation
|
| 309 |
+
eq = Add(*((x/cf).cancel() for x in eq.args)).collect(f(x))
|
| 310 |
+
|
| 311 |
+
# Match the equation with the pattern
|
| 312 |
+
b1 = -eq.coeff(f(x))
|
| 313 |
+
b2 = -eq.coeff(f(x)**2)
|
| 314 |
+
b0 = (f(x).diff(x) - b1*f(x) - b2*f(x)**2 - eq).expand()
|
| 315 |
+
funcs = [b0, b1, b2]
|
| 316 |
+
|
| 317 |
+
# Check if coefficients are not symbols and floats
|
| 318 |
+
if any(len(x.atoms(Symbol)) > 1 or len(x.atoms(Float)) for x in funcs):
|
| 319 |
+
return False, []
|
| 320 |
+
|
| 321 |
+
# If b_0(x) contains f(x), it is not a Riccati ODE
|
| 322 |
+
if len(b0.atoms(f)) or not all((b2 != 0, b0.is_rational_function(x),
|
| 323 |
+
b1.is_rational_function(x), b2.is_rational_function(x))):
|
| 324 |
+
return False, []
|
| 325 |
+
return True, funcs
|
| 326 |
+
return False, []
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
def val_at_inf(num, den, x):
|
| 330 |
+
# Valuation of a rational function at oo = deg(denom) - deg(numer)
|
| 331 |
+
return den.degree(x) - num.degree(x)
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
def check_necessary_conds(val_inf, muls):
|
| 335 |
+
"""
|
| 336 |
+
The necessary conditions for a rational solution
|
| 337 |
+
to exist are as follows -
|
| 338 |
+
|
| 339 |
+
i) Every pole of a(x) must be either a simple pole
|
| 340 |
+
or a multiple pole of even order.
|
| 341 |
+
|
| 342 |
+
ii) The valuation of a(x) at infinity must be even
|
| 343 |
+
or be greater than or equal to 2.
|
| 344 |
+
|
| 345 |
+
Here, a simple pole is a pole with multiplicity 1
|
| 346 |
+
and a multiple pole is a pole with multiplicity
|
| 347 |
+
greater than 1.
|
| 348 |
+
"""
|
| 349 |
+
return (val_inf >= 2 or (val_inf <= 0 and val_inf%2 == 0)) and \
|
| 350 |
+
all(mul == 1 or (mul%2 == 0 and mul >= 2) for mul in muls)
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
def inverse_transform_poly(num, den, x):
|
| 354 |
+
"""
|
| 355 |
+
A function to make the substitution
|
| 356 |
+
x -> 1/x in a rational function that
|
| 357 |
+
is represented using Poly objects for
|
| 358 |
+
numerator and denominator.
|
| 359 |
+
"""
|
| 360 |
+
# Declare for reuse
|
| 361 |
+
one = Poly(1, x)
|
| 362 |
+
xpoly = Poly(x, x)
|
| 363 |
+
|
| 364 |
+
# Check if degree of numerator is same as denominator
|
| 365 |
+
pwr = val_at_inf(num, den, x)
|
| 366 |
+
if pwr >= 0:
|
| 367 |
+
# Denominator has greater degree. Substituting x with
|
| 368 |
+
# 1/x would make the extra power go to the numerator
|
| 369 |
+
if num.expr != 0:
|
| 370 |
+
num = num.transform(one, xpoly) * x**pwr
|
| 371 |
+
den = den.transform(one, xpoly)
|
| 372 |
+
else:
|
| 373 |
+
# Numerator has greater degree. Substituting x with
|
| 374 |
+
# 1/x would make the extra power go to the denominator
|
| 375 |
+
num = num.transform(one, xpoly)
|
| 376 |
+
den = den.transform(one, xpoly) * x**(-pwr)
|
| 377 |
+
return num.cancel(den, include=True)
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
def limit_at_inf(num, den, x):
|
| 381 |
+
"""
|
| 382 |
+
Find the limit of a rational function
|
| 383 |
+
at oo
|
| 384 |
+
"""
|
| 385 |
+
# pwr = degree(num) - degree(den)
|
| 386 |
+
pwr = -val_at_inf(num, den, x)
|
| 387 |
+
# Numerator has a greater degree than denominator
|
| 388 |
+
# Limit at infinity would depend on the sign of the
|
| 389 |
+
# leading coefficients of numerator and denominator
|
| 390 |
+
if pwr > 0:
|
| 391 |
+
return oo*sign(num.LC()/den.LC())
|
| 392 |
+
# Degree of numerator is equal to that of denominator
|
| 393 |
+
# Limit at infinity is just the ratio of leading coeffs
|
| 394 |
+
elif pwr == 0:
|
| 395 |
+
return num.LC()/den.LC()
|
| 396 |
+
# Degree of numerator is less than that of denominator
|
| 397 |
+
# Limit at infinity is just 0
|
| 398 |
+
else:
|
| 399 |
+
return 0
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
def construct_c_case_1(num, den, x, pole):
|
| 403 |
+
# Find the coefficient of 1/(x - pole)**2 in the
|
| 404 |
+
# Laurent series expansion of a(x) about pole.
|
| 405 |
+
num1, den1 = (num*Poly((x - pole)**2, x, extension=True)).cancel(den, include=True)
|
| 406 |
+
r = (num1.subs(x, pole))/(den1.subs(x, pole))
|
| 407 |
+
|
| 408 |
+
# If multiplicity is 2, the coefficient to be added
|
| 409 |
+
# in the c-vector is c = (1 +- sqrt(1 + 4*r))/2
|
| 410 |
+
if r != -S(1)/4:
|
| 411 |
+
return [[(1 + sqrt(1 + 4*r))/2], [(1 - sqrt(1 + 4*r))/2]]
|
| 412 |
+
return [[S.Half]]
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
def construct_c_case_2(num, den, x, pole, mul):
|
| 416 |
+
# Generate the coefficients using the recurrence
|
| 417 |
+
# relation mentioned in (5.14) in the thesis (Pg 80)
|
| 418 |
+
|
| 419 |
+
# r_i = mul/2
|
| 420 |
+
ri = mul//2
|
| 421 |
+
|
| 422 |
+
# Find the Laurent series coefficients about the pole
|
| 423 |
+
ser = rational_laurent_series(num, den, x, pole, mul, 6)
|
| 424 |
+
|
| 425 |
+
# Start with an empty memo to store the coefficients
|
| 426 |
+
# This is for the plus case
|
| 427 |
+
cplus = [0 for i in range(ri)]
|
| 428 |
+
|
| 429 |
+
# Base Case
|
| 430 |
+
cplus[ri-1] = sqrt(ser[2*ri])
|
| 431 |
+
|
| 432 |
+
# Iterate backwards to find all coefficients
|
| 433 |
+
s = ri - 1
|
| 434 |
+
sm = 0
|
| 435 |
+
for s in range(ri-1, 0, -1):
|
| 436 |
+
sm = 0
|
| 437 |
+
for j in range(s+1, ri):
|
| 438 |
+
sm += cplus[j-1]*cplus[ri+s-j-1]
|
| 439 |
+
if s!= 1:
|
| 440 |
+
cplus[s-1] = (ser[ri+s] - sm)/(2*cplus[ri-1])
|
| 441 |
+
|
| 442 |
+
# Memo for the minus case
|
| 443 |
+
cminus = [-x for x in cplus]
|
| 444 |
+
|
| 445 |
+
# Find the 0th coefficient in the recurrence
|
| 446 |
+
cplus[0] = (ser[ri+s] - sm - ri*cplus[ri-1])/(2*cplus[ri-1])
|
| 447 |
+
cminus[0] = (ser[ri+s] - sm - ri*cminus[ri-1])/(2*cminus[ri-1])
|
| 448 |
+
|
| 449 |
+
# Add both the plus and minus cases' coefficients
|
| 450 |
+
if cplus != cminus:
|
| 451 |
+
return [cplus, cminus]
|
| 452 |
+
return cplus
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
def construct_c_case_3():
|
| 456 |
+
# If multiplicity is 1, the coefficient to be added
|
| 457 |
+
# in the c-vector is 1 (no choice)
|
| 458 |
+
return [[1]]
|
| 459 |
+
|
| 460 |
+
|
| 461 |
+
def construct_c(num, den, x, poles, muls):
|
| 462 |
+
"""
|
| 463 |
+
Helper function to calculate the coefficients
|
| 464 |
+
in the c-vector for each pole.
|
| 465 |
+
"""
|
| 466 |
+
c = []
|
| 467 |
+
for pole, mul in zip(poles, muls):
|
| 468 |
+
c.append([])
|
| 469 |
+
|
| 470 |
+
# Case 3
|
| 471 |
+
if mul == 1:
|
| 472 |
+
# Add the coefficients from Case 3
|
| 473 |
+
c[-1].extend(construct_c_case_3())
|
| 474 |
+
|
| 475 |
+
# Case 1
|
| 476 |
+
elif mul == 2:
|
| 477 |
+
# Add the coefficients from Case 1
|
| 478 |
+
c[-1].extend(construct_c_case_1(num, den, x, pole))
|
| 479 |
+
|
| 480 |
+
# Case 2
|
| 481 |
+
else:
|
| 482 |
+
# Add the coefficients from Case 2
|
| 483 |
+
c[-1].extend(construct_c_case_2(num, den, x, pole, mul))
|
| 484 |
+
|
| 485 |
+
return c
|
| 486 |
+
|
| 487 |
+
|
| 488 |
+
def construct_d_case_4(ser, N):
|
| 489 |
+
# Initialize an empty vector
|
| 490 |
+
dplus = [0 for i in range(N+2)]
|
| 491 |
+
# d_N = sqrt(a_{2*N})
|
| 492 |
+
dplus[N] = sqrt(ser[2*N])
|
| 493 |
+
|
| 494 |
+
# Use the recurrence relations to find
|
| 495 |
+
# the value of d_s
|
| 496 |
+
for s in range(N-1, -2, -1):
|
| 497 |
+
sm = 0
|
| 498 |
+
for j in range(s+1, N):
|
| 499 |
+
sm += dplus[j]*dplus[N+s-j]
|
| 500 |
+
if s != -1:
|
| 501 |
+
dplus[s] = (ser[N+s] - sm)/(2*dplus[N])
|
| 502 |
+
|
| 503 |
+
# Coefficients for the case of d_N = -sqrt(a_{2*N})
|
| 504 |
+
dminus = [-x for x in dplus]
|
| 505 |
+
|
| 506 |
+
# The third equation in Eq 5.15 of the thesis is WRONG!
|
| 507 |
+
# d_N must be replaced with N*d_N in that equation.
|
| 508 |
+
dplus[-1] = (ser[N+s] - N*dplus[N] - sm)/(2*dplus[N])
|
| 509 |
+
dminus[-1] = (ser[N+s] - N*dminus[N] - sm)/(2*dminus[N])
|
| 510 |
+
|
| 511 |
+
if dplus != dminus:
|
| 512 |
+
return [dplus, dminus]
|
| 513 |
+
return dplus
|
| 514 |
+
|
| 515 |
+
|
| 516 |
+
def construct_d_case_5(ser):
|
| 517 |
+
# List to store coefficients for plus case
|
| 518 |
+
dplus = [0, 0]
|
| 519 |
+
|
| 520 |
+
# d_0 = sqrt(a_0)
|
| 521 |
+
dplus[0] = sqrt(ser[0])
|
| 522 |
+
|
| 523 |
+
# d_(-1) = a_(-1)/(2*d_0)
|
| 524 |
+
dplus[-1] = ser[-1]/(2*dplus[0])
|
| 525 |
+
|
| 526 |
+
# Coefficients for the minus case are just the negative
|
| 527 |
+
# of the coefficients for the positive case.
|
| 528 |
+
dminus = [-x for x in dplus]
|
| 529 |
+
|
| 530 |
+
if dplus != dminus:
|
| 531 |
+
return [dplus, dminus]
|
| 532 |
+
return dplus
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
def construct_d_case_6(num, den, x):
|
| 536 |
+
# s_oo = lim x->0 1/x**2 * a(1/x) which is equivalent to
|
| 537 |
+
# s_oo = lim x->oo x**2 * a(x)
|
| 538 |
+
s_inf = limit_at_inf(Poly(x**2, x)*num, den, x)
|
| 539 |
+
|
| 540 |
+
# d_(-1) = (1 +- sqrt(1 + 4*s_oo))/2
|
| 541 |
+
if s_inf != -S(1)/4:
|
| 542 |
+
return [[(1 + sqrt(1 + 4*s_inf))/2], [(1 - sqrt(1 + 4*s_inf))/2]]
|
| 543 |
+
return [[S.Half]]
|
| 544 |
+
|
| 545 |
+
|
| 546 |
+
def construct_d(num, den, x, val_inf):
|
| 547 |
+
"""
|
| 548 |
+
Helper function to calculate the coefficients
|
| 549 |
+
in the d-vector based on the valuation of the
|
| 550 |
+
function at oo.
|
| 551 |
+
"""
|
| 552 |
+
N = -val_inf//2
|
| 553 |
+
# Multiplicity of oo as a pole
|
| 554 |
+
mul = -val_inf if val_inf < 0 else 0
|
| 555 |
+
ser = rational_laurent_series(num, den, x, oo, mul, 1)
|
| 556 |
+
|
| 557 |
+
# Case 4
|
| 558 |
+
if val_inf < 0:
|
| 559 |
+
d = construct_d_case_4(ser, N)
|
| 560 |
+
|
| 561 |
+
# Case 5
|
| 562 |
+
elif val_inf == 0:
|
| 563 |
+
d = construct_d_case_5(ser)
|
| 564 |
+
|
| 565 |
+
# Case 6
|
| 566 |
+
else:
|
| 567 |
+
d = construct_d_case_6(num, den, x)
|
| 568 |
+
|
| 569 |
+
return d
|
| 570 |
+
|
| 571 |
+
|
| 572 |
+
def rational_laurent_series(num, den, x, r, m, n):
|
| 573 |
+
r"""
|
| 574 |
+
The function computes the Laurent series coefficients
|
| 575 |
+
of a rational function.
|
| 576 |
+
|
| 577 |
+
Parameters
|
| 578 |
+
==========
|
| 579 |
+
|
| 580 |
+
num: A Poly object that is the numerator of `f(x)`.
|
| 581 |
+
den: A Poly object that is the denominator of `f(x)`.
|
| 582 |
+
x: The variable of expansion of the series.
|
| 583 |
+
r: The point of expansion of the series.
|
| 584 |
+
m: Multiplicity of r if r is a pole of `f(x)`. Should
|
| 585 |
+
be zero otherwise.
|
| 586 |
+
n: Order of the term upto which the series is expanded.
|
| 587 |
+
|
| 588 |
+
Returns
|
| 589 |
+
=======
|
| 590 |
+
|
| 591 |
+
series: A dictionary that has power of the term as key
|
| 592 |
+
and coefficient of that term as value.
|
| 593 |
+
|
| 594 |
+
Below is a basic outline of how the Laurent series of a
|
| 595 |
+
rational function `f(x)` about `x_0` is being calculated -
|
| 596 |
+
|
| 597 |
+
1. Substitute `x + x_0` in place of `x`. If `x_0`
|
| 598 |
+
is a pole of `f(x)`, multiply the expression by `x^m`
|
| 599 |
+
where `m` is the multiplicity of `x_0`. Denote the
|
| 600 |
+
the resulting expression as g(x). We do this substitution
|
| 601 |
+
so that we can now find the Laurent series of g(x) about
|
| 602 |
+
`x = 0`.
|
| 603 |
+
|
| 604 |
+
2. We can then assume that the Laurent series of `g(x)`
|
| 605 |
+
takes the following form -
|
| 606 |
+
|
| 607 |
+
.. math:: g(x) = \frac{num(x)}{den(x)} = \sum_{m = 0}^{\infty} a_m x^m
|
| 608 |
+
|
| 609 |
+
where `a_m` denotes the Laurent series coefficients.
|
| 610 |
+
|
| 611 |
+
3. Multiply the denominator to the RHS of the equation
|
| 612 |
+
and form a recurrence relation for the coefficients `a_m`.
|
| 613 |
+
"""
|
| 614 |
+
one = Poly(1, x, extension=True)
|
| 615 |
+
|
| 616 |
+
if r == oo:
|
| 617 |
+
# Series at x = oo is equal to first transforming
|
| 618 |
+
# the function from x -> 1/x and finding the
|
| 619 |
+
# series at x = 0
|
| 620 |
+
num, den = inverse_transform_poly(num, den, x)
|
| 621 |
+
r = S(0)
|
| 622 |
+
|
| 623 |
+
if r:
|
| 624 |
+
# For an expansion about a non-zero point, a
|
| 625 |
+
# transformation from x -> x + r must be made
|
| 626 |
+
num = num.transform(Poly(x + r, x, extension=True), one)
|
| 627 |
+
den = den.transform(Poly(x + r, x, extension=True), one)
|
| 628 |
+
|
| 629 |
+
# Remove the pole from the denominator if the series
|
| 630 |
+
# expansion is about one of the poles
|
| 631 |
+
num, den = (num*x**m).cancel(den, include=True)
|
| 632 |
+
|
| 633 |
+
# Equate coefficients for the first terms (base case)
|
| 634 |
+
maxdegree = 1 + max(num.degree(), den.degree())
|
| 635 |
+
syms = symbols(f'a:{maxdegree}', cls=Dummy)
|
| 636 |
+
diff = num - den * Poly(syms[::-1], x)
|
| 637 |
+
coeff_diffs = diff.all_coeffs()[::-1][:maxdegree]
|
| 638 |
+
(coeffs, ) = linsolve(coeff_diffs, syms)
|
| 639 |
+
|
| 640 |
+
# Use the recursion relation for the rest
|
| 641 |
+
recursion = den.all_coeffs()[::-1]
|
| 642 |
+
div, rec_rhs = recursion[0], recursion[1:]
|
| 643 |
+
series = list(coeffs)
|
| 644 |
+
while len(series) < n:
|
| 645 |
+
next_coeff = Add(*(c*series[-1-n] for n, c in enumerate(rec_rhs))) / div
|
| 646 |
+
series.append(-next_coeff)
|
| 647 |
+
series = {m - i: val for i, val in enumerate(series)}
|
| 648 |
+
return series
|
| 649 |
+
|
| 650 |
+
def compute_m_ybar(x, poles, choice, N):
|
| 651 |
+
"""
|
| 652 |
+
Helper function to calculate -
|
| 653 |
+
|
| 654 |
+
1. m - The degree bound for the polynomial
|
| 655 |
+
solution that must be found for the auxiliary
|
| 656 |
+
differential equation.
|
| 657 |
+
|
| 658 |
+
2. ybar - Part of the solution which can be
|
| 659 |
+
computed using the poles, c and d vectors.
|
| 660 |
+
"""
|
| 661 |
+
ybar = 0
|
| 662 |
+
m = Poly(choice[-1][-1], x, extension=True)
|
| 663 |
+
|
| 664 |
+
# Calculate the first (nested) summation for ybar
|
| 665 |
+
# as given in Step 9 of the Thesis (Pg 82)
|
| 666 |
+
dybar = []
|
| 667 |
+
for i, polei in enumerate(poles):
|
| 668 |
+
for j, cij in enumerate(choice[i]):
|
| 669 |
+
dybar.append(cij/(x - polei)**(j + 1))
|
| 670 |
+
m -=Poly(choice[i][0], x, extension=True) # can't accumulate Poly and use with Add
|
| 671 |
+
ybar += Add(*dybar)
|
| 672 |
+
|
| 673 |
+
# Calculate the second summation for ybar
|
| 674 |
+
for i in range(N+1):
|
| 675 |
+
ybar += choice[-1][i]*x**i
|
| 676 |
+
return (m.expr, ybar)
|
| 677 |
+
|
| 678 |
+
|
| 679 |
+
def solve_aux_eq(numa, dena, numy, deny, x, m):
|
| 680 |
+
"""
|
| 681 |
+
Helper function to find a polynomial solution
|
| 682 |
+
of degree m for the auxiliary differential
|
| 683 |
+
equation.
|
| 684 |
+
"""
|
| 685 |
+
# Assume that the solution is of the type
|
| 686 |
+
# p(x) = C_0 + C_1*x + ... + C_{m-1}*x**(m-1) + x**m
|
| 687 |
+
psyms = symbols(f'C0:{m}', cls=Dummy)
|
| 688 |
+
K = ZZ[psyms]
|
| 689 |
+
psol = Poly(K.gens, x, domain=K) + Poly(x**m, x, domain=K)
|
| 690 |
+
|
| 691 |
+
# Eq (5.16) in Thesis - Pg 81
|
| 692 |
+
auxeq = (dena*(numy.diff(x)*deny - numy*deny.diff(x) + numy**2) - numa*deny**2)*psol
|
| 693 |
+
if m >= 1:
|
| 694 |
+
px = psol.diff(x)
|
| 695 |
+
auxeq += px*(2*numy*deny*dena)
|
| 696 |
+
if m >= 2:
|
| 697 |
+
auxeq += px.diff(x)*(deny**2*dena)
|
| 698 |
+
if m != 0:
|
| 699 |
+
# m is a non-zero integer. Find the constant terms using undetermined coefficients
|
| 700 |
+
return psol, linsolve_dict(auxeq.all_coeffs(), psyms), True
|
| 701 |
+
else:
|
| 702 |
+
# m == 0 . Check if 1 (x**0) is a solution to the auxiliary equation
|
| 703 |
+
return S.One, auxeq, auxeq == 0
|
| 704 |
+
|
| 705 |
+
|
| 706 |
+
def remove_redundant_sols(sol1, sol2, x):
|
| 707 |
+
"""
|
| 708 |
+
Helper function to remove redundant
|
| 709 |
+
solutions to the differential equation.
|
| 710 |
+
"""
|
| 711 |
+
# If y1 and y2 are redundant solutions, there is
|
| 712 |
+
# some value of the arbitrary constant for which
|
| 713 |
+
# they will be equal
|
| 714 |
+
|
| 715 |
+
syms1 = sol1.atoms(Symbol, Dummy)
|
| 716 |
+
syms2 = sol2.atoms(Symbol, Dummy)
|
| 717 |
+
num1, den1 = [Poly(e, x, extension=True) for e in sol1.together().as_numer_denom()]
|
| 718 |
+
num2, den2 = [Poly(e, x, extension=True) for e in sol2.together().as_numer_denom()]
|
| 719 |
+
# Cross multiply
|
| 720 |
+
e = num1*den2 - den1*num2
|
| 721 |
+
# Check if there are any constants
|
| 722 |
+
syms = list(e.atoms(Symbol, Dummy))
|
| 723 |
+
if len(syms):
|
| 724 |
+
# Find values of constants for which solutions are equal
|
| 725 |
+
redn = linsolve(e.all_coeffs(), syms)
|
| 726 |
+
if len(redn):
|
| 727 |
+
# Return the general solution over a particular solution
|
| 728 |
+
if len(syms1) > len(syms2):
|
| 729 |
+
return sol2
|
| 730 |
+
# If both have constants, return the lesser complex solution
|
| 731 |
+
elif len(syms1) == len(syms2):
|
| 732 |
+
return sol1 if count_ops(syms1) >= count_ops(syms2) else sol2
|
| 733 |
+
else:
|
| 734 |
+
return sol1
|
| 735 |
+
|
| 736 |
+
|
| 737 |
+
def get_gen_sol_from_part_sol(part_sols, a, x):
|
| 738 |
+
""""
|
| 739 |
+
Helper function which computes the general
|
| 740 |
+
solution for a Riccati ODE from its particular
|
| 741 |
+
solutions.
|
| 742 |
+
|
| 743 |
+
There are 3 cases to find the general solution
|
| 744 |
+
from the particular solutions for a Riccati ODE
|
| 745 |
+
depending on the number of particular solution(s)
|
| 746 |
+
we have - 1, 2 or 3.
|
| 747 |
+
|
| 748 |
+
For more information, see Section 6 of
|
| 749 |
+
"Methods of Solution of the Riccati Differential Equation"
|
| 750 |
+
by D. R. Haaheim and F. M. Stein
|
| 751 |
+
"""
|
| 752 |
+
|
| 753 |
+
# If no particular solutions are found, a general
|
| 754 |
+
# solution cannot be found
|
| 755 |
+
if len(part_sols) == 0:
|
| 756 |
+
return []
|
| 757 |
+
|
| 758 |
+
# In case of a single particular solution, the general
|
| 759 |
+
# solution can be found by using the substitution
|
| 760 |
+
# y = y1 + 1/z and solving a Bernoulli ODE to find z.
|
| 761 |
+
elif len(part_sols) == 1:
|
| 762 |
+
y1 = part_sols[0]
|
| 763 |
+
i = exp(Integral(2*y1, x))
|
| 764 |
+
z = i * Integral(a/i, x)
|
| 765 |
+
z = z.doit()
|
| 766 |
+
if a == 0 or z == 0:
|
| 767 |
+
return y1
|
| 768 |
+
return y1 + 1/z
|
| 769 |
+
|
| 770 |
+
# In case of 2 particular solutions, the general solution
|
| 771 |
+
# can be found by solving a separable equation. This is
|
| 772 |
+
# the most common case, i.e. most Riccati ODEs have 2
|
| 773 |
+
# rational particular solutions.
|
| 774 |
+
elif len(part_sols) == 2:
|
| 775 |
+
y1, y2 = part_sols
|
| 776 |
+
# One of them already has a constant
|
| 777 |
+
if len(y1.atoms(Dummy)) + len(y2.atoms(Dummy)) > 0:
|
| 778 |
+
u = exp(Integral(y2 - y1, x)).doit()
|
| 779 |
+
# Introduce a constant
|
| 780 |
+
else:
|
| 781 |
+
C1 = Dummy('C1')
|
| 782 |
+
u = C1*exp(Integral(y2 - y1, x)).doit()
|
| 783 |
+
if u == 1:
|
| 784 |
+
return y2
|
| 785 |
+
return (y2*u - y1)/(u - 1)
|
| 786 |
+
|
| 787 |
+
# In case of 3 particular solutions, a closed form
|
| 788 |
+
# of the general solution can be obtained directly
|
| 789 |
+
else:
|
| 790 |
+
y1, y2, y3 = part_sols[:3]
|
| 791 |
+
C1 = Dummy('C1')
|
| 792 |
+
return (C1 + 1)*y2*(y1 - y3)/(C1*y1 + y2 - (C1 + 1)*y3)
|
| 793 |
+
|
| 794 |
+
|
| 795 |
+
def solve_riccati(fx, x, b0, b1, b2, gensol=False):
|
| 796 |
+
"""
|
| 797 |
+
The main function that gives particular/general
|
| 798 |
+
solutions to Riccati ODEs that have atleast 1
|
| 799 |
+
rational particular solution.
|
| 800 |
+
"""
|
| 801 |
+
# Step 1 : Convert to Normal Form
|
| 802 |
+
a = -b0*b2 + b1**2/4 - b1.diff(x)/2 + 3*b2.diff(x)**2/(4*b2**2) + b1*b2.diff(x)/(2*b2) - \
|
| 803 |
+
b2.diff(x, 2)/(2*b2)
|
| 804 |
+
a_t = a.together()
|
| 805 |
+
num, den = [Poly(e, x, extension=True) for e in a_t.as_numer_denom()]
|
| 806 |
+
num, den = num.cancel(den, include=True)
|
| 807 |
+
|
| 808 |
+
# Step 2
|
| 809 |
+
presol = []
|
| 810 |
+
|
| 811 |
+
# Step 3 : a(x) is 0
|
| 812 |
+
if num == 0:
|
| 813 |
+
presol.append(1/(x + Dummy('C1')))
|
| 814 |
+
|
| 815 |
+
# Step 4 : a(x) is a non-zero constant
|
| 816 |
+
elif x not in num.free_symbols.union(den.free_symbols):
|
| 817 |
+
presol.extend([sqrt(a), -sqrt(a)])
|
| 818 |
+
|
| 819 |
+
# Step 5 : Find poles and valuation at infinity
|
| 820 |
+
poles = roots(den, x)
|
| 821 |
+
poles, muls = list(poles.keys()), list(poles.values())
|
| 822 |
+
val_inf = val_at_inf(num, den, x)
|
| 823 |
+
|
| 824 |
+
if len(poles):
|
| 825 |
+
# Check necessary conditions (outlined in the module docstring)
|
| 826 |
+
if not check_necessary_conds(val_inf, muls):
|
| 827 |
+
raise ValueError("Rational Solution doesn't exist")
|
| 828 |
+
|
| 829 |
+
# Step 6
|
| 830 |
+
# Construct c-vectors for each singular point
|
| 831 |
+
c = construct_c(num, den, x, poles, muls)
|
| 832 |
+
|
| 833 |
+
# Construct d vectors for each singular point
|
| 834 |
+
d = construct_d(num, den, x, val_inf)
|
| 835 |
+
|
| 836 |
+
# Step 7 : Iterate over all possible combinations and return solutions
|
| 837 |
+
# For each possible combination, generate an array of 0's and 1's
|
| 838 |
+
# where 0 means pick 1st choice and 1 means pick the second choice.
|
| 839 |
+
|
| 840 |
+
# NOTE: We could exit from the loop if we find 3 particular solutions,
|
| 841 |
+
# but it is not implemented here as -
|
| 842 |
+
# a. Finding 3 particular solutions is very rare. Most of the time,
|
| 843 |
+
# only 2 particular solutions are found.
|
| 844 |
+
# b. In case we exit after finding 3 particular solutions, it might
|
| 845 |
+
# happen that 1 or 2 of them are redundant solutions. So, instead of
|
| 846 |
+
# spending some more time in computing the particular solutions,
|
| 847 |
+
# we will end up computing the general solution from a single
|
| 848 |
+
# particular solution which is usually slower than computing the
|
| 849 |
+
# general solution from 2 or 3 particular solutions.
|
| 850 |
+
c.append(d)
|
| 851 |
+
choices = product(*c)
|
| 852 |
+
for choice in choices:
|
| 853 |
+
m, ybar = compute_m_ybar(x, poles, choice, -val_inf//2)
|
| 854 |
+
numy, deny = [Poly(e, x, extension=True) for e in ybar.together().as_numer_denom()]
|
| 855 |
+
# Step 10 : Check if a valid solution exists. If yes, also check
|
| 856 |
+
# if m is a non-negative integer
|
| 857 |
+
if m.is_nonnegative == True and m.is_integer == True:
|
| 858 |
+
|
| 859 |
+
# Step 11 : Find polynomial solutions of degree m for the auxiliary equation
|
| 860 |
+
psol, coeffs, exists = solve_aux_eq(num, den, numy, deny, x, m)
|
| 861 |
+
|
| 862 |
+
# Step 12 : If valid polynomial solution exists, append solution.
|
| 863 |
+
if exists:
|
| 864 |
+
# m == 0 case
|
| 865 |
+
if psol == 1 and coeffs == 0:
|
| 866 |
+
# p(x) = 1, so p'(x)/p(x) term need not be added
|
| 867 |
+
presol.append(ybar)
|
| 868 |
+
# m is a positive integer and there are valid coefficients
|
| 869 |
+
elif len(coeffs):
|
| 870 |
+
# Substitute the valid coefficients to get p(x)
|
| 871 |
+
psol = psol.xreplace(coeffs)
|
| 872 |
+
# y(x) = ybar(x) + p'(x)/p(x)
|
| 873 |
+
presol.append(ybar + psol.diff(x)/psol)
|
| 874 |
+
|
| 875 |
+
# Remove redundant solutions from the list of existing solutions
|
| 876 |
+
remove = set()
|
| 877 |
+
for i in range(len(presol)):
|
| 878 |
+
for j in range(i+1, len(presol)):
|
| 879 |
+
rem = remove_redundant_sols(presol[i], presol[j], x)
|
| 880 |
+
if rem is not None:
|
| 881 |
+
remove.add(rem)
|
| 882 |
+
sols = [x for x in presol if x not in remove]
|
| 883 |
+
|
| 884 |
+
# Step 15 : Inverse transform the solutions of the equation in normal form
|
| 885 |
+
bp = -b2.diff(x)/(2*b2**2) - b1/(2*b2)
|
| 886 |
+
|
| 887 |
+
# If general solution is required, compute it from the particular solutions
|
| 888 |
+
if gensol:
|
| 889 |
+
sols = [get_gen_sol_from_part_sol(sols, a, x)]
|
| 890 |
+
|
| 891 |
+
# Inverse transform the particular solutions
|
| 892 |
+
presol = [Eq(fx, riccati_inverse_normal(y, x, b1, b2, bp).cancel(extension=True)) for y in sols]
|
| 893 |
+
return presol
|
pllava/lib/python3.10/site-packages/sympy/solvers/ode/single.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
pllava/lib/python3.10/site-packages/sympy/solvers/ode/subscheck.py
ADDED
|
@@ -0,0 +1,392 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core import S, Pow
|
| 2 |
+
from sympy.core.function import (Derivative, AppliedUndef, diff)
|
| 3 |
+
from sympy.core.relational import Equality, Eq
|
| 4 |
+
from sympy.core.symbol import Dummy
|
| 5 |
+
from sympy.core.sympify import sympify
|
| 6 |
+
|
| 7 |
+
from sympy.logic.boolalg import BooleanAtom
|
| 8 |
+
from sympy.functions import exp
|
| 9 |
+
from sympy.series import Order
|
| 10 |
+
from sympy.simplify.simplify import simplify, posify, besselsimp
|
| 11 |
+
from sympy.simplify.trigsimp import trigsimp
|
| 12 |
+
from sympy.simplify.sqrtdenest import sqrtdenest
|
| 13 |
+
from sympy.solvers import solve
|
| 14 |
+
from sympy.solvers.deutils import _preprocess, ode_order
|
| 15 |
+
from sympy.utilities.iterables import iterable, is_sequence
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def sub_func_doit(eq, func, new):
|
| 19 |
+
r"""
|
| 20 |
+
When replacing the func with something else, we usually want the
|
| 21 |
+
derivative evaluated, so this function helps in making that happen.
|
| 22 |
+
|
| 23 |
+
Examples
|
| 24 |
+
========
|
| 25 |
+
|
| 26 |
+
>>> from sympy import Derivative, symbols, Function
|
| 27 |
+
>>> from sympy.solvers.ode.subscheck import sub_func_doit
|
| 28 |
+
>>> x, z = symbols('x, z')
|
| 29 |
+
>>> y = Function('y')
|
| 30 |
+
|
| 31 |
+
>>> sub_func_doit(3*Derivative(y(x), x) - 1, y(x), x)
|
| 32 |
+
2
|
| 33 |
+
|
| 34 |
+
>>> sub_func_doit(x*Derivative(y(x), x) - y(x)**2 + y(x), y(x),
|
| 35 |
+
... 1/(x*(z + 1/x)))
|
| 36 |
+
x*(-1/(x**2*(z + 1/x)) + 1/(x**3*(z + 1/x)**2)) + 1/(x*(z + 1/x))
|
| 37 |
+
...- 1/(x**2*(z + 1/x)**2)
|
| 38 |
+
"""
|
| 39 |
+
reps= {func: new}
|
| 40 |
+
for d in eq.atoms(Derivative):
|
| 41 |
+
if d.expr == func:
|
| 42 |
+
reps[d] = new.diff(*d.variable_count)
|
| 43 |
+
else:
|
| 44 |
+
reps[d] = d.xreplace({func: new}).doit(deep=False)
|
| 45 |
+
return eq.xreplace(reps)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def checkodesol(ode, sol, func=None, order='auto', solve_for_func=True):
|
| 49 |
+
r"""
|
| 50 |
+
Substitutes ``sol`` into ``ode`` and checks that the result is ``0``.
|
| 51 |
+
|
| 52 |
+
This works when ``func`` is one function, like `f(x)` or a list of
|
| 53 |
+
functions like `[f(x), g(x)]` when `ode` is a system of ODEs. ``sol`` can
|
| 54 |
+
be a single solution or a list of solutions. Each solution may be an
|
| 55 |
+
:py:class:`~sympy.core.relational.Equality` that the solution satisfies,
|
| 56 |
+
e.g. ``Eq(f(x), C1), Eq(f(x) + C1, 0)``; or simply an
|
| 57 |
+
:py:class:`~sympy.core.expr.Expr`, e.g. ``f(x) - C1``. In most cases it
|
| 58 |
+
will not be necessary to explicitly identify the function, but if the
|
| 59 |
+
function cannot be inferred from the original equation it can be supplied
|
| 60 |
+
through the ``func`` argument.
|
| 61 |
+
|
| 62 |
+
If a sequence of solutions is passed, the same sort of container will be
|
| 63 |
+
used to return the result for each solution.
|
| 64 |
+
|
| 65 |
+
It tries the following methods, in order, until it finds zero equivalence:
|
| 66 |
+
|
| 67 |
+
1. Substitute the solution for `f` in the original equation. This only
|
| 68 |
+
works if ``ode`` is solved for `f`. It will attempt to solve it first
|
| 69 |
+
unless ``solve_for_func == False``.
|
| 70 |
+
2. Take `n` derivatives of the solution, where `n` is the order of
|
| 71 |
+
``ode``, and check to see if that is equal to the solution. This only
|
| 72 |
+
works on exact ODEs.
|
| 73 |
+
3. Take the 1st, 2nd, ..., `n`\th derivatives of the solution, each time
|
| 74 |
+
solving for the derivative of `f` of that order (this will always be
|
| 75 |
+
possible because `f` is a linear operator). Then back substitute each
|
| 76 |
+
derivative into ``ode`` in reverse order.
|
| 77 |
+
|
| 78 |
+
This function returns a tuple. The first item in the tuple is ``True`` if
|
| 79 |
+
the substitution results in ``0``, and ``False`` otherwise. The second
|
| 80 |
+
item in the tuple is what the substitution results in. It should always
|
| 81 |
+
be ``0`` if the first item is ``True``. Sometimes this function will
|
| 82 |
+
return ``False`` even when an expression is identically equal to ``0``.
|
| 83 |
+
This happens when :py:meth:`~sympy.simplify.simplify.simplify` does not
|
| 84 |
+
reduce the expression to ``0``. If an expression returned by this
|
| 85 |
+
function vanishes identically, then ``sol`` really is a solution to
|
| 86 |
+
the ``ode``.
|
| 87 |
+
|
| 88 |
+
If this function seems to hang, it is probably because of a hard
|
| 89 |
+
simplification.
|
| 90 |
+
|
| 91 |
+
To use this function to test, test the first item of the tuple.
|
| 92 |
+
|
| 93 |
+
Examples
|
| 94 |
+
========
|
| 95 |
+
|
| 96 |
+
>>> from sympy import (Eq, Function, checkodesol, symbols,
|
| 97 |
+
... Derivative, exp)
|
| 98 |
+
>>> x, C1, C2 = symbols('x,C1,C2')
|
| 99 |
+
>>> f, g = symbols('f g', cls=Function)
|
| 100 |
+
>>> checkodesol(f(x).diff(x), Eq(f(x), C1))
|
| 101 |
+
(True, 0)
|
| 102 |
+
>>> assert checkodesol(f(x).diff(x), C1)[0]
|
| 103 |
+
>>> assert not checkodesol(f(x).diff(x), x)[0]
|
| 104 |
+
>>> checkodesol(f(x).diff(x, 2), x**2)
|
| 105 |
+
(False, 2)
|
| 106 |
+
|
| 107 |
+
>>> eqs = [Eq(Derivative(f(x), x), f(x)), Eq(Derivative(g(x), x), g(x))]
|
| 108 |
+
>>> sol = [Eq(f(x), C1*exp(x)), Eq(g(x), C2*exp(x))]
|
| 109 |
+
>>> checkodesol(eqs, sol)
|
| 110 |
+
(True, [0, 0])
|
| 111 |
+
|
| 112 |
+
"""
|
| 113 |
+
if iterable(ode):
|
| 114 |
+
return checksysodesol(ode, sol, func=func)
|
| 115 |
+
|
| 116 |
+
if not isinstance(ode, Equality):
|
| 117 |
+
ode = Eq(ode, 0)
|
| 118 |
+
if func is None:
|
| 119 |
+
try:
|
| 120 |
+
_, func = _preprocess(ode.lhs)
|
| 121 |
+
except ValueError:
|
| 122 |
+
funcs = [s.atoms(AppliedUndef) for s in (
|
| 123 |
+
sol if is_sequence(sol, set) else [sol])]
|
| 124 |
+
funcs = set().union(*funcs)
|
| 125 |
+
if len(funcs) != 1:
|
| 126 |
+
raise ValueError(
|
| 127 |
+
'must pass func arg to checkodesol for this case.')
|
| 128 |
+
func = funcs.pop()
|
| 129 |
+
if not isinstance(func, AppliedUndef) or len(func.args) != 1:
|
| 130 |
+
raise ValueError(
|
| 131 |
+
"func must be a function of one variable, not %s" % func)
|
| 132 |
+
if is_sequence(sol, set):
|
| 133 |
+
return type(sol)([checkodesol(ode, i, order=order, solve_for_func=solve_for_func) for i in sol])
|
| 134 |
+
|
| 135 |
+
if not isinstance(sol, Equality):
|
| 136 |
+
sol = Eq(func, sol)
|
| 137 |
+
elif sol.rhs == func:
|
| 138 |
+
sol = sol.reversed
|
| 139 |
+
|
| 140 |
+
if order == 'auto':
|
| 141 |
+
order = ode_order(ode, func)
|
| 142 |
+
solved = sol.lhs == func and not sol.rhs.has(func)
|
| 143 |
+
if solve_for_func and not solved:
|
| 144 |
+
rhs = solve(sol, func)
|
| 145 |
+
if rhs:
|
| 146 |
+
eqs = [Eq(func, t) for t in rhs]
|
| 147 |
+
if len(rhs) == 1:
|
| 148 |
+
eqs = eqs[0]
|
| 149 |
+
return checkodesol(ode, eqs, order=order,
|
| 150 |
+
solve_for_func=False)
|
| 151 |
+
|
| 152 |
+
x = func.args[0]
|
| 153 |
+
|
| 154 |
+
# Handle series solutions here
|
| 155 |
+
if sol.has(Order):
|
| 156 |
+
assert sol.lhs == func
|
| 157 |
+
Oterm = sol.rhs.getO()
|
| 158 |
+
solrhs = sol.rhs.removeO()
|
| 159 |
+
|
| 160 |
+
Oexpr = Oterm.expr
|
| 161 |
+
assert isinstance(Oexpr, Pow)
|
| 162 |
+
sorder = Oexpr.exp
|
| 163 |
+
assert Oterm == Order(x**sorder)
|
| 164 |
+
|
| 165 |
+
odesubs = (ode.lhs-ode.rhs).subs(func, solrhs).doit().expand()
|
| 166 |
+
|
| 167 |
+
neworder = Order(x**(sorder - order))
|
| 168 |
+
odesubs = odesubs + neworder
|
| 169 |
+
assert odesubs.getO() == neworder
|
| 170 |
+
residual = odesubs.removeO()
|
| 171 |
+
|
| 172 |
+
return (residual == 0, residual)
|
| 173 |
+
|
| 174 |
+
s = True
|
| 175 |
+
testnum = 0
|
| 176 |
+
while s:
|
| 177 |
+
if testnum == 0:
|
| 178 |
+
# First pass, try substituting a solved solution directly into the
|
| 179 |
+
# ODE. This has the highest chance of succeeding.
|
| 180 |
+
ode_diff = ode.lhs - ode.rhs
|
| 181 |
+
|
| 182 |
+
if sol.lhs == func:
|
| 183 |
+
s = sub_func_doit(ode_diff, func, sol.rhs)
|
| 184 |
+
s = besselsimp(s)
|
| 185 |
+
else:
|
| 186 |
+
testnum += 1
|
| 187 |
+
continue
|
| 188 |
+
ss = simplify(s.rewrite(exp))
|
| 189 |
+
if ss:
|
| 190 |
+
# with the new numer_denom in power.py, if we do a simple
|
| 191 |
+
# expansion then testnum == 0 verifies all solutions.
|
| 192 |
+
s = ss.expand(force=True)
|
| 193 |
+
else:
|
| 194 |
+
s = 0
|
| 195 |
+
testnum += 1
|
| 196 |
+
elif testnum == 1:
|
| 197 |
+
# Second pass. If we cannot substitute f, try seeing if the nth
|
| 198 |
+
# derivative is equal, this will only work for odes that are exact,
|
| 199 |
+
# by definition.
|
| 200 |
+
s = simplify(
|
| 201 |
+
trigsimp(diff(sol.lhs, x, order) - diff(sol.rhs, x, order)) -
|
| 202 |
+
trigsimp(ode.lhs) + trigsimp(ode.rhs))
|
| 203 |
+
# s2 = simplify(
|
| 204 |
+
# diff(sol.lhs, x, order) - diff(sol.rhs, x, order) - \
|
| 205 |
+
# ode.lhs + ode.rhs)
|
| 206 |
+
testnum += 1
|
| 207 |
+
elif testnum == 2:
|
| 208 |
+
# Third pass. Try solving for df/dx and substituting that into the
|
| 209 |
+
# ODE. Thanks to Chris Smith for suggesting this method. Many of
|
| 210 |
+
# the comments below are his, too.
|
| 211 |
+
# The method:
|
| 212 |
+
# - Take each of 1..n derivatives of the solution.
|
| 213 |
+
# - Solve each nth derivative for d^(n)f/dx^(n)
|
| 214 |
+
# (the differential of that order)
|
| 215 |
+
# - Back substitute into the ODE in decreasing order
|
| 216 |
+
# (i.e., n, n-1, ...)
|
| 217 |
+
# - Check the result for zero equivalence
|
| 218 |
+
if sol.lhs == func and not sol.rhs.has(func):
|
| 219 |
+
diffsols = {0: sol.rhs}
|
| 220 |
+
elif sol.rhs == func and not sol.lhs.has(func):
|
| 221 |
+
diffsols = {0: sol.lhs}
|
| 222 |
+
else:
|
| 223 |
+
diffsols = {}
|
| 224 |
+
sol = sol.lhs - sol.rhs
|
| 225 |
+
for i in range(1, order + 1):
|
| 226 |
+
# Differentiation is a linear operator, so there should always
|
| 227 |
+
# be 1 solution. Nonetheless, we test just to make sure.
|
| 228 |
+
# We only need to solve once. After that, we automatically
|
| 229 |
+
# have the solution to the differential in the order we want.
|
| 230 |
+
if i == 1:
|
| 231 |
+
ds = sol.diff(x)
|
| 232 |
+
try:
|
| 233 |
+
sdf = solve(ds, func.diff(x, i))
|
| 234 |
+
if not sdf:
|
| 235 |
+
raise NotImplementedError
|
| 236 |
+
except NotImplementedError:
|
| 237 |
+
testnum += 1
|
| 238 |
+
break
|
| 239 |
+
else:
|
| 240 |
+
diffsols[i] = sdf[0]
|
| 241 |
+
else:
|
| 242 |
+
# This is what the solution says df/dx should be.
|
| 243 |
+
diffsols[i] = diffsols[i - 1].diff(x)
|
| 244 |
+
|
| 245 |
+
# Make sure the above didn't fail.
|
| 246 |
+
if testnum > 2:
|
| 247 |
+
continue
|
| 248 |
+
else:
|
| 249 |
+
# Substitute it into ODE to check for self consistency.
|
| 250 |
+
lhs, rhs = ode.lhs, ode.rhs
|
| 251 |
+
for i in range(order, -1, -1):
|
| 252 |
+
if i == 0 and 0 not in diffsols:
|
| 253 |
+
# We can only substitute f(x) if the solution was
|
| 254 |
+
# solved for f(x).
|
| 255 |
+
break
|
| 256 |
+
lhs = sub_func_doit(lhs, func.diff(x, i), diffsols[i])
|
| 257 |
+
rhs = sub_func_doit(rhs, func.diff(x, i), diffsols[i])
|
| 258 |
+
ode_or_bool = Eq(lhs, rhs)
|
| 259 |
+
ode_or_bool = simplify(ode_or_bool)
|
| 260 |
+
|
| 261 |
+
if isinstance(ode_or_bool, (bool, BooleanAtom)):
|
| 262 |
+
if ode_or_bool:
|
| 263 |
+
lhs = rhs = S.Zero
|
| 264 |
+
else:
|
| 265 |
+
lhs = ode_or_bool.lhs
|
| 266 |
+
rhs = ode_or_bool.rhs
|
| 267 |
+
# No sense in overworking simplify -- just prove that the
|
| 268 |
+
# numerator goes to zero
|
| 269 |
+
num = trigsimp((lhs - rhs).as_numer_denom()[0])
|
| 270 |
+
# since solutions are obtained using force=True we test
|
| 271 |
+
# using the same level of assumptions
|
| 272 |
+
## replace function with dummy so assumptions will work
|
| 273 |
+
_func = Dummy('func')
|
| 274 |
+
num = num.subs(func, _func)
|
| 275 |
+
## posify the expression
|
| 276 |
+
num, reps = posify(num)
|
| 277 |
+
s = simplify(num).xreplace(reps).xreplace({_func: func})
|
| 278 |
+
testnum += 1
|
| 279 |
+
else:
|
| 280 |
+
break
|
| 281 |
+
|
| 282 |
+
if not s:
|
| 283 |
+
return (True, s)
|
| 284 |
+
elif s is True: # The code above never was able to change s
|
| 285 |
+
raise NotImplementedError("Unable to test if " + str(sol) +
|
| 286 |
+
" is a solution to " + str(ode) + ".")
|
| 287 |
+
else:
|
| 288 |
+
return (False, s)
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
def checksysodesol(eqs, sols, func=None):
|
| 292 |
+
r"""
|
| 293 |
+
Substitutes corresponding ``sols`` for each functions into each ``eqs`` and
|
| 294 |
+
checks that the result of substitutions for each equation is ``0``. The
|
| 295 |
+
equations and solutions passed can be any iterable.
|
| 296 |
+
|
| 297 |
+
This only works when each ``sols`` have one function only, like `x(t)` or `y(t)`.
|
| 298 |
+
For each function, ``sols`` can have a single solution or a list of solutions.
|
| 299 |
+
In most cases it will not be necessary to explicitly identify the function,
|
| 300 |
+
but if the function cannot be inferred from the original equation it
|
| 301 |
+
can be supplied through the ``func`` argument.
|
| 302 |
+
|
| 303 |
+
When a sequence of equations is passed, the same sequence is used to return
|
| 304 |
+
the result for each equation with each function substituted with corresponding
|
| 305 |
+
solutions.
|
| 306 |
+
|
| 307 |
+
It tries the following method to find zero equivalence for each equation:
|
| 308 |
+
|
| 309 |
+
Substitute the solutions for functions, like `x(t)` and `y(t)` into the
|
| 310 |
+
original equations containing those functions.
|
| 311 |
+
This function returns a tuple. The first item in the tuple is ``True`` if
|
| 312 |
+
the substitution results for each equation is ``0``, and ``False`` otherwise.
|
| 313 |
+
The second item in the tuple is what the substitution results in. Each element
|
| 314 |
+
of the ``list`` should always be ``0`` corresponding to each equation if the
|
| 315 |
+
first item is ``True``. Note that sometimes this function may return ``False``,
|
| 316 |
+
but with an expression that is identically equal to ``0``, instead of returning
|
| 317 |
+
``True``. This is because :py:meth:`~sympy.simplify.simplify.simplify` cannot
|
| 318 |
+
reduce the expression to ``0``. If an expression returned by each function
|
| 319 |
+
vanishes identically, then ``sols`` really is a solution to ``eqs``.
|
| 320 |
+
|
| 321 |
+
If this function seems to hang, it is probably because of a difficult simplification.
|
| 322 |
+
|
| 323 |
+
Examples
|
| 324 |
+
========
|
| 325 |
+
|
| 326 |
+
>>> from sympy import Eq, diff, symbols, sin, cos, exp, sqrt, S, Function
|
| 327 |
+
>>> from sympy.solvers.ode.subscheck import checksysodesol
|
| 328 |
+
>>> C1, C2 = symbols('C1:3')
|
| 329 |
+
>>> t = symbols('t')
|
| 330 |
+
>>> x, y = symbols('x, y', cls=Function)
|
| 331 |
+
>>> eq = (Eq(diff(x(t),t), x(t) + y(t) + 17), Eq(diff(y(t),t), -2*x(t) + y(t) + 12))
|
| 332 |
+
>>> sol = [Eq(x(t), (C1*sin(sqrt(2)*t) + C2*cos(sqrt(2)*t))*exp(t) - S(5)/3),
|
| 333 |
+
... Eq(y(t), (sqrt(2)*C1*cos(sqrt(2)*t) - sqrt(2)*C2*sin(sqrt(2)*t))*exp(t) - S(46)/3)]
|
| 334 |
+
>>> checksysodesol(eq, sol)
|
| 335 |
+
(True, [0, 0])
|
| 336 |
+
>>> eq = (Eq(diff(x(t),t),x(t)*y(t)**4), Eq(diff(y(t),t),y(t)**3))
|
| 337 |
+
>>> sol = [Eq(x(t), C1*exp(-1/(4*(C2 + t)))), Eq(y(t), -sqrt(2)*sqrt(-1/(C2 + t))/2),
|
| 338 |
+
... Eq(x(t), C1*exp(-1/(4*(C2 + t)))), Eq(y(t), sqrt(2)*sqrt(-1/(C2 + t))/2)]
|
| 339 |
+
>>> checksysodesol(eq, sol)
|
| 340 |
+
(True, [0, 0])
|
| 341 |
+
|
| 342 |
+
"""
|
| 343 |
+
def _sympify(eq):
|
| 344 |
+
return list(map(sympify, eq if iterable(eq) else [eq]))
|
| 345 |
+
eqs = _sympify(eqs)
|
| 346 |
+
for i in range(len(eqs)):
|
| 347 |
+
if isinstance(eqs[i], Equality):
|
| 348 |
+
eqs[i] = eqs[i].lhs - eqs[i].rhs
|
| 349 |
+
if func is None:
|
| 350 |
+
funcs = []
|
| 351 |
+
for eq in eqs:
|
| 352 |
+
derivs = eq.atoms(Derivative)
|
| 353 |
+
func = set().union(*[d.atoms(AppliedUndef) for d in derivs])
|
| 354 |
+
funcs.extend(func)
|
| 355 |
+
funcs = list(set(funcs))
|
| 356 |
+
if not all(isinstance(func, AppliedUndef) and len(func.args) == 1 for func in funcs)\
|
| 357 |
+
and len({func.args for func in funcs})!=1:
|
| 358 |
+
raise ValueError("func must be a function of one variable, not %s" % func)
|
| 359 |
+
for sol in sols:
|
| 360 |
+
if len(sol.atoms(AppliedUndef)) != 1:
|
| 361 |
+
raise ValueError("solutions should have one function only")
|
| 362 |
+
if len(funcs) != len({sol.lhs for sol in sols}):
|
| 363 |
+
raise ValueError("number of solutions provided does not match the number of equations")
|
| 364 |
+
dictsol = {}
|
| 365 |
+
for sol in sols:
|
| 366 |
+
func = list(sol.atoms(AppliedUndef))[0]
|
| 367 |
+
if sol.rhs == func:
|
| 368 |
+
sol = sol.reversed
|
| 369 |
+
solved = sol.lhs == func and not sol.rhs.has(func)
|
| 370 |
+
if not solved:
|
| 371 |
+
rhs = solve(sol, func)
|
| 372 |
+
if not rhs:
|
| 373 |
+
raise NotImplementedError
|
| 374 |
+
else:
|
| 375 |
+
rhs = sol.rhs
|
| 376 |
+
dictsol[func] = rhs
|
| 377 |
+
checkeq = []
|
| 378 |
+
for eq in eqs:
|
| 379 |
+
for func in funcs:
|
| 380 |
+
eq = sub_func_doit(eq, func, dictsol[func])
|
| 381 |
+
ss = simplify(eq)
|
| 382 |
+
if ss != 0:
|
| 383 |
+
eq = ss.expand(force=True)
|
| 384 |
+
if eq != 0:
|
| 385 |
+
eq = sqrtdenest(eq).simplify()
|
| 386 |
+
else:
|
| 387 |
+
eq = 0
|
| 388 |
+
checkeq.append(eq)
|
| 389 |
+
if len(set(checkeq)) == 1 and list(set(checkeq))[0] == 0:
|
| 390 |
+
return (True, checkeq)
|
| 391 |
+
else:
|
| 392 |
+
return (False, checkeq)
|
pllava/lib/python3.10/site-packages/sympy/solvers/ode/systems.py
ADDED
|
@@ -0,0 +1,2135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from sympy.core import Add, Mul, S
|
| 2 |
+
from sympy.core.containers import Tuple
|
| 3 |
+
from sympy.core.exprtools import factor_terms
|
| 4 |
+
from sympy.core.numbers import I
|
| 5 |
+
from sympy.core.relational import Eq, Equality
|
| 6 |
+
from sympy.core.sorting import default_sort_key, ordered
|
| 7 |
+
from sympy.core.symbol import Dummy, Symbol
|
| 8 |
+
from sympy.core.function import (expand_mul, expand, Derivative,
|
| 9 |
+
AppliedUndef, Function, Subs)
|
| 10 |
+
from sympy.functions import (exp, im, cos, sin, re, Piecewise,
|
| 11 |
+
piecewise_fold, sqrt, log)
|
| 12 |
+
from sympy.functions.combinatorial.factorials import factorial
|
| 13 |
+
from sympy.matrices import zeros, Matrix, NonSquareMatrixError, MatrixBase, eye
|
| 14 |
+
from sympy.polys import Poly, together
|
| 15 |
+
from sympy.simplify import collect, radsimp, signsimp # type: ignore
|
| 16 |
+
from sympy.simplify.powsimp import powdenest, powsimp
|
| 17 |
+
from sympy.simplify.ratsimp import ratsimp
|
| 18 |
+
from sympy.simplify.simplify import simplify
|
| 19 |
+
from sympy.sets.sets import FiniteSet
|
| 20 |
+
from sympy.solvers.deutils import ode_order
|
| 21 |
+
from sympy.solvers.solveset import NonlinearError, solveset
|
| 22 |
+
from sympy.utilities.iterables import (connected_components, iterable,
|
| 23 |
+
strongly_connected_components)
|
| 24 |
+
from sympy.utilities.misc import filldedent
|
| 25 |
+
from sympy.integrals.integrals import Integral, integrate
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _get_func_order(eqs, funcs):
|
| 29 |
+
return {func: max(ode_order(eq, func) for eq in eqs) for func in funcs}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class ODEOrderError(ValueError):
|
| 33 |
+
"""Raised by linear_ode_to_matrix if the system has the wrong order"""
|
| 34 |
+
pass
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class ODENonlinearError(NonlinearError):
|
| 38 |
+
"""Raised by linear_ode_to_matrix if the system is nonlinear"""
|
| 39 |
+
pass
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _simpsol(soleq):
|
| 43 |
+
lhs = soleq.lhs
|
| 44 |
+
sol = soleq.rhs
|
| 45 |
+
sol = powsimp(sol)
|
| 46 |
+
gens = list(sol.atoms(exp))
|
| 47 |
+
p = Poly(sol, *gens, expand=False)
|
| 48 |
+
gens = [factor_terms(g) for g in gens]
|
| 49 |
+
if not gens:
|
| 50 |
+
gens = p.gens
|
| 51 |
+
syms = [Symbol('C1'), Symbol('C2')]
|
| 52 |
+
terms = []
|
| 53 |
+
for coeff, monom in zip(p.coeffs(), p.monoms()):
|
| 54 |
+
coeff = piecewise_fold(coeff)
|
| 55 |
+
if isinstance(coeff, Piecewise):
|
| 56 |
+
coeff = Piecewise(*((ratsimp(coef).collect(syms), cond) for coef, cond in coeff.args))
|
| 57 |
+
else:
|
| 58 |
+
coeff = ratsimp(coeff).collect(syms)
|
| 59 |
+
monom = Mul(*(g ** i for g, i in zip(gens, monom)))
|
| 60 |
+
terms.append(coeff * monom)
|
| 61 |
+
return Eq(lhs, Add(*terms))
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _solsimp(e, t):
|
| 65 |
+
no_t, has_t = powsimp(expand_mul(e)).as_independent(t)
|
| 66 |
+
|
| 67 |
+
no_t = ratsimp(no_t)
|
| 68 |
+
has_t = has_t.replace(exp, lambda a: exp(factor_terms(a)))
|
| 69 |
+
|
| 70 |
+
return no_t + has_t
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def simpsol(sol, wrt1, wrt2, doit=True):
|
| 74 |
+
"""Simplify solutions from dsolve_system."""
|
| 75 |
+
|
| 76 |
+
# The parameter sol is the solution as returned by dsolve (list of Eq).
|
| 77 |
+
#
|
| 78 |
+
# The parameters wrt1 and wrt2 are lists of symbols to be collected for
|
| 79 |
+
# with those in wrt1 being collected for first. This allows for collecting
|
| 80 |
+
# on any factors involving the independent variable before collecting on
|
| 81 |
+
# the integration constants or vice versa using e.g.:
|
| 82 |
+
#
|
| 83 |
+
# sol = simpsol(sol, [t], [C1, C2]) # t first, constants after
|
| 84 |
+
# sol = simpsol(sol, [C1, C2], [t]) # constants first, t after
|
| 85 |
+
#
|
| 86 |
+
# If doit=True (default) then simpsol will begin by evaluating any
|
| 87 |
+
# unevaluated integrals. Since many integrals will appear multiple times
|
| 88 |
+
# in the solutions this is done intelligently by computing each integral
|
| 89 |
+
# only once.
|
| 90 |
+
#
|
| 91 |
+
# The strategy is to first perform simple cancellation with factor_terms
|
| 92 |
+
# and then multiply out all brackets with expand_mul. This gives an Add
|
| 93 |
+
# with many terms.
|
| 94 |
+
#
|
| 95 |
+
# We split each term into two multiplicative factors dep and coeff where
|
| 96 |
+
# all factors that involve wrt1 are in dep and any constant factors are in
|
| 97 |
+
# coeff e.g.
|
| 98 |
+
# sqrt(2)*C1*exp(t) -> ( exp(t), sqrt(2)*C1 )
|
| 99 |
+
#
|
| 100 |
+
# The dep factors are simplified using powsimp to combine expanded
|
| 101 |
+
# exponential factors e.g.
|
| 102 |
+
# exp(a*t)*exp(b*t) -> exp(t*(a+b))
|
| 103 |
+
#
|
| 104 |
+
# We then collect coefficients for all terms having the same (simplified)
|
| 105 |
+
# dep. The coefficients are then simplified using together and ratsimp and
|
| 106 |
+
# lastly by recursively applying the same transformation to the
|
| 107 |
+
# coefficients to collect on wrt2.
|
| 108 |
+
#
|
| 109 |
+
# Finally the result is recombined into an Add and signsimp is used to
|
| 110 |
+
# normalise any minus signs.
|
| 111 |
+
|
| 112 |
+
def simprhs(rhs, rep, wrt1, wrt2):
|
| 113 |
+
"""Simplify the rhs of an ODE solution"""
|
| 114 |
+
if rep:
|
| 115 |
+
rhs = rhs.subs(rep)
|
| 116 |
+
rhs = factor_terms(rhs)
|
| 117 |
+
rhs = simp_coeff_dep(rhs, wrt1, wrt2)
|
| 118 |
+
rhs = signsimp(rhs)
|
| 119 |
+
return rhs
|
| 120 |
+
|
| 121 |
+
def simp_coeff_dep(expr, wrt1, wrt2=None):
|
| 122 |
+
"""Split rhs into terms, split terms into dep and coeff and collect on dep"""
|
| 123 |
+
add_dep_terms = lambda e: e.is_Add and e.has(*wrt1)
|
| 124 |
+
expandable = lambda e: e.is_Mul and any(map(add_dep_terms, e.args))
|
| 125 |
+
expand_func = lambda e: expand_mul(e, deep=False)
|
| 126 |
+
expand_mul_mod = lambda e: e.replace(expandable, expand_func)
|
| 127 |
+
terms = Add.make_args(expand_mul_mod(expr))
|
| 128 |
+
dc = {}
|
| 129 |
+
for term in terms:
|
| 130 |
+
coeff, dep = term.as_independent(*wrt1, as_Add=False)
|
| 131 |
+
# Collect together the coefficients for terms that have the same
|
| 132 |
+
# dependence on wrt1 (after dep is normalised using simpdep).
|
| 133 |
+
dep = simpdep(dep, wrt1)
|
| 134 |
+
|
| 135 |
+
# See if the dependence on t cancels out...
|
| 136 |
+
if dep is not S.One:
|
| 137 |
+
dep2 = factor_terms(dep)
|
| 138 |
+
if not dep2.has(*wrt1):
|
| 139 |
+
coeff *= dep2
|
| 140 |
+
dep = S.One
|
| 141 |
+
|
| 142 |
+
if dep not in dc:
|
| 143 |
+
dc[dep] = coeff
|
| 144 |
+
else:
|
| 145 |
+
dc[dep] += coeff
|
| 146 |
+
# Apply the method recursively to the coefficients but this time
|
| 147 |
+
# collecting on wrt2 rather than wrt2.
|
| 148 |
+
termpairs = ((simpcoeff(c, wrt2), d) for d, c in dc.items())
|
| 149 |
+
if wrt2 is not None:
|
| 150 |
+
termpairs = ((simp_coeff_dep(c, wrt2), d) for c, d in termpairs)
|
| 151 |
+
return Add(*(c * d for c, d in termpairs))
|
| 152 |
+
|
| 153 |
+
def simpdep(term, wrt1):
|
| 154 |
+
"""Normalise factors involving t with powsimp and recombine exp"""
|
| 155 |
+
def canonicalise(a):
|
| 156 |
+
# Using factor_terms here isn't quite right because it leads to things
|
| 157 |
+
# like exp(t*(1+t)) that we don't want. We do want to cancel factors
|
| 158 |
+
# and pull out a common denominator but ideally the numerator would be
|
| 159 |
+
# expressed as a standard form polynomial in t so we expand_mul
|
| 160 |
+
# and collect afterwards.
|
| 161 |
+
a = factor_terms(a)
|
| 162 |
+
num, den = a.as_numer_denom()
|
| 163 |
+
num = expand_mul(num)
|
| 164 |
+
num = collect(num, wrt1)
|
| 165 |
+
return num / den
|
| 166 |
+
|
| 167 |
+
term = powsimp(term)
|
| 168 |
+
rep = {e: exp(canonicalise(e.args[0])) for e in term.atoms(exp)}
|
| 169 |
+
term = term.subs(rep)
|
| 170 |
+
return term
|
| 171 |
+
|
| 172 |
+
def simpcoeff(coeff, wrt2):
|
| 173 |
+
"""Bring to a common fraction and cancel with ratsimp"""
|
| 174 |
+
coeff = together(coeff)
|
| 175 |
+
if coeff.is_polynomial():
|
| 176 |
+
# Calling ratsimp can be expensive. The main reason is to simplify
|
| 177 |
+
# sums of terms with irrational denominators so we limit ourselves
|
| 178 |
+
# to the case where the expression is polynomial in any symbols.
|
| 179 |
+
# Maybe there's a better approach...
|
| 180 |
+
coeff = ratsimp(radsimp(coeff))
|
| 181 |
+
# collect on secondary variables first and any remaining symbols after
|
| 182 |
+
if wrt2 is not None:
|
| 183 |
+
syms = list(wrt2) + list(ordered(coeff.free_symbols - set(wrt2)))
|
| 184 |
+
else:
|
| 185 |
+
syms = list(ordered(coeff.free_symbols))
|
| 186 |
+
coeff = collect(coeff, syms)
|
| 187 |
+
coeff = together(coeff)
|
| 188 |
+
return coeff
|
| 189 |
+
|
| 190 |
+
# There are often repeated integrals. Collect unique integrals and
|
| 191 |
+
# evaluate each once and then substitute into the final result to replace
|
| 192 |
+
# all occurrences in each of the solution equations.
|
| 193 |
+
if doit:
|
| 194 |
+
integrals = set().union(*(s.atoms(Integral) for s in sol))
|
| 195 |
+
rep = {i: factor_terms(i).doit() for i in integrals}
|
| 196 |
+
else:
|
| 197 |
+
rep = {}
|
| 198 |
+
|
| 199 |
+
sol = [Eq(s.lhs, simprhs(s.rhs, rep, wrt1, wrt2)) for s in sol]
|
| 200 |
+
return sol
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def linodesolve_type(A, t, b=None):
|
| 204 |
+
r"""
|
| 205 |
+
Helper function that determines the type of the system of ODEs for solving with :obj:`sympy.solvers.ode.systems.linodesolve()`
|
| 206 |
+
|
| 207 |
+
Explanation
|
| 208 |
+
===========
|
| 209 |
+
|
| 210 |
+
This function takes in the coefficient matrix and/or the non-homogeneous term
|
| 211 |
+
and returns the type of the equation that can be solved by :obj:`sympy.solvers.ode.systems.linodesolve()`.
|
| 212 |
+
|
| 213 |
+
If the system is constant coefficient homogeneous, then "type1" is returned
|
| 214 |
+
|
| 215 |
+
If the system is constant coefficient non-homogeneous, then "type2" is returned
|
| 216 |
+
|
| 217 |
+
If the system is non-constant coefficient homogeneous, then "type3" is returned
|
| 218 |
+
|
| 219 |
+
If the system is non-constant coefficient non-homogeneous, then "type4" is returned
|
| 220 |
+
|
| 221 |
+
If the system has a non-constant coefficient matrix which can be factorized into constant
|
| 222 |
+
coefficient matrix, then "type5" or "type6" is returned for when the system is homogeneous or
|
| 223 |
+
non-homogeneous respectively.
|
| 224 |
+
|
| 225 |
+
Note that, if the system of ODEs is of "type3" or "type4", then along with the type,
|
| 226 |
+
the commutative antiderivative of the coefficient matrix is also returned.
|
| 227 |
+
|
| 228 |
+
If the system cannot be solved by :obj:`sympy.solvers.ode.systems.linodesolve()`, then
|
| 229 |
+
NotImplementedError is raised.
|
| 230 |
+
|
| 231 |
+
Parameters
|
| 232 |
+
==========
|
| 233 |
+
|
| 234 |
+
A : Matrix
|
| 235 |
+
Coefficient matrix of the system of ODEs
|
| 236 |
+
b : Matrix or None
|
| 237 |
+
Non-homogeneous term of the system. The default value is None.
|
| 238 |
+
If this argument is None, then the system is assumed to be homogeneous.
|
| 239 |
+
|
| 240 |
+
Examples
|
| 241 |
+
========
|
| 242 |
+
|
| 243 |
+
>>> from sympy import symbols, Matrix
|
| 244 |
+
>>> from sympy.solvers.ode.systems import linodesolve_type
|
| 245 |
+
>>> t = symbols("t")
|
| 246 |
+
>>> A = Matrix([[1, 1], [2, 3]])
|
| 247 |
+
>>> b = Matrix([t, 1])
|
| 248 |
+
|
| 249 |
+
>>> linodesolve_type(A, t)
|
| 250 |
+
{'antiderivative': None, 'type_of_equation': 'type1'}
|
| 251 |
+
|
| 252 |
+
>>> linodesolve_type(A, t, b=b)
|
| 253 |
+
{'antiderivative': None, 'type_of_equation': 'type2'}
|
| 254 |
+
|
| 255 |
+
>>> A_t = Matrix([[1, t], [-t, 1]])
|
| 256 |
+
|
| 257 |
+
>>> linodesolve_type(A_t, t)
|
| 258 |
+
{'antiderivative': Matrix([
|
| 259 |
+
[ t, t**2/2],
|
| 260 |
+
[-t**2/2, t]]), 'type_of_equation': 'type3'}
|
| 261 |
+
|
| 262 |
+
>>> linodesolve_type(A_t, t, b=b)
|
| 263 |
+
{'antiderivative': Matrix([
|
| 264 |
+
[ t, t**2/2],
|
| 265 |
+
[-t**2/2, t]]), 'type_of_equation': 'type4'}
|
| 266 |
+
|
| 267 |
+
>>> A_non_commutative = Matrix([[1, t], [t, -1]])
|
| 268 |
+
>>> linodesolve_type(A_non_commutative, t)
|
| 269 |
+
Traceback (most recent call last):
|
| 270 |
+
...
|
| 271 |
+
NotImplementedError:
|
| 272 |
+
The system does not have a commutative antiderivative, it cannot be
|
| 273 |
+
solved by linodesolve.
|
| 274 |
+
|
| 275 |
+
Returns
|
| 276 |
+
=======
|
| 277 |
+
|
| 278 |
+
Dict
|
| 279 |
+
|
| 280 |
+
Raises
|
| 281 |
+
======
|
| 282 |
+
|
| 283 |
+
NotImplementedError
|
| 284 |
+
When the coefficient matrix does not have a commutative antiderivative
|
| 285 |
+
|
| 286 |
+
See Also
|
| 287 |
+
========
|
| 288 |
+
|
| 289 |
+
linodesolve: Function for which linodesolve_type gets the information
|
| 290 |
+
|
| 291 |
+
"""
|
| 292 |
+
|
| 293 |
+
match = {}
|
| 294 |
+
is_non_constant = not _matrix_is_constant(A, t)
|
| 295 |
+
is_non_homogeneous = not (b is None or b.is_zero_matrix)
|
| 296 |
+
type = "type{}".format(int("{}{}".format(int(is_non_constant), int(is_non_homogeneous)), 2) + 1)
|
| 297 |
+
|
| 298 |
+
B = None
|
| 299 |
+
match.update({"type_of_equation": type, "antiderivative": B})
|
| 300 |
+
|
| 301 |
+
if is_non_constant:
|
| 302 |
+
B, is_commuting = _is_commutative_anti_derivative(A, t)
|
| 303 |
+
if not is_commuting:
|
| 304 |
+
raise NotImplementedError(filldedent('''
|
| 305 |
+
The system does not have a commutative antiderivative, it cannot be solved
|
| 306 |
+
by linodesolve.
|
| 307 |
+
'''))
|
| 308 |
+
|
| 309 |
+
match['antiderivative'] = B
|
| 310 |
+
match.update(_first_order_type5_6_subs(A, t, b=b))
|
| 311 |
+
|
| 312 |
+
return match
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
def _first_order_type5_6_subs(A, t, b=None):
|
| 316 |
+
match = {}
|
| 317 |
+
|
| 318 |
+
factor_terms = _factor_matrix(A, t)
|
| 319 |
+
is_homogeneous = b is None or b.is_zero_matrix
|
| 320 |
+
|
| 321 |
+
if factor_terms is not None:
|
| 322 |
+
t_ = Symbol("{}_".format(t))
|
| 323 |
+
F_t = integrate(factor_terms[0], t)
|
| 324 |
+
inverse = solveset(Eq(t_, F_t), t)
|
| 325 |
+
|
| 326 |
+
# Note: A simple way to check if a function is invertible
|
| 327 |
+
# or not.
|
| 328 |
+
if isinstance(inverse, FiniteSet) and not inverse.has(Piecewise)\
|
| 329 |
+
and len(inverse) == 1:
|
| 330 |
+
|
| 331 |
+
A = factor_terms[1]
|
| 332 |
+
if not is_homogeneous:
|
| 333 |
+
b = b / factor_terms[0]
|
| 334 |
+
b = b.subs(t, list(inverse)[0])
|
| 335 |
+
type = "type{}".format(5 + (not is_homogeneous))
|
| 336 |
+
match.update({'func_coeff': A, 'tau': F_t,
|
| 337 |
+
't_': t_, 'type_of_equation': type, 'rhs': b})
|
| 338 |
+
|
| 339 |
+
return match
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
def linear_ode_to_matrix(eqs, funcs, t, order):
|
| 343 |
+
r"""
|
| 344 |
+
Convert a linear system of ODEs to matrix form
|
| 345 |
+
|
| 346 |
+
Explanation
|
| 347 |
+
===========
|
| 348 |
+
|
| 349 |
+
Express a system of linear ordinary differential equations as a single
|
| 350 |
+
matrix differential equation [1]. For example the system $x' = x + y + 1$
|
| 351 |
+
and $y' = x - y$ can be represented as
|
| 352 |
+
|
| 353 |
+
.. math:: A_1 X' = A_0 X + b
|
| 354 |
+
|
| 355 |
+
where $A_1$ and $A_0$ are $2 \times 2$ matrices and $b$, $X$ and $X'$ are
|
| 356 |
+
$2 \times 1$ matrices with $X = [x, y]^T$.
|
| 357 |
+
|
| 358 |
+
Higher-order systems are represented with additional matrices e.g. a
|
| 359 |
+
second-order system would look like
|
| 360 |
+
|
| 361 |
+
.. math:: A_2 X'' = A_1 X' + A_0 X + b
|
| 362 |
+
|
| 363 |
+
Examples
|
| 364 |
+
========
|
| 365 |
+
|
| 366 |
+
>>> from sympy import Function, Symbol, Matrix, Eq
|
| 367 |
+
>>> from sympy.solvers.ode.systems import linear_ode_to_matrix
|
| 368 |
+
>>> t = Symbol('t')
|
| 369 |
+
>>> x = Function('x')
|
| 370 |
+
>>> y = Function('y')
|
| 371 |
+
|
| 372 |
+
We can create a system of linear ODEs like
|
| 373 |
+
|
| 374 |
+
>>> eqs = [
|
| 375 |
+
... Eq(x(t).diff(t), x(t) + y(t) + 1),
|
| 376 |
+
... Eq(y(t).diff(t), x(t) - y(t)),
|
| 377 |
+
... ]
|
| 378 |
+
>>> funcs = [x(t), y(t)]
|
| 379 |
+
>>> order = 1 # 1st order system
|
| 380 |
+
|
| 381 |
+
Now ``linear_ode_to_matrix`` can represent this as a matrix
|
| 382 |
+
differential equation.
|
| 383 |
+
|
| 384 |
+
>>> (A1, A0), b = linear_ode_to_matrix(eqs, funcs, t, order)
|
| 385 |
+
>>> A1
|
| 386 |
+
Matrix([
|
| 387 |
+
[1, 0],
|
| 388 |
+
[0, 1]])
|
| 389 |
+
>>> A0
|
| 390 |
+
Matrix([
|
| 391 |
+
[1, 1],
|
| 392 |
+
[1, -1]])
|
| 393 |
+
>>> b
|
| 394 |
+
Matrix([
|
| 395 |
+
[1],
|
| 396 |
+
[0]])
|
| 397 |
+
|
| 398 |
+
The original equations can be recovered from these matrices:
|
| 399 |
+
|
| 400 |
+
>>> eqs_mat = Matrix([eq.lhs - eq.rhs for eq in eqs])
|
| 401 |
+
>>> X = Matrix(funcs)
|
| 402 |
+
>>> A1 * X.diff(t) - A0 * X - b == eqs_mat
|
| 403 |
+
True
|
| 404 |
+
|
| 405 |
+
If the system of equations has a maximum order greater than the
|
| 406 |
+
order of the system specified, a ODEOrderError exception is raised.
|
| 407 |
+
|
| 408 |
+
>>> eqs = [Eq(x(t).diff(t, 2), x(t).diff(t) + x(t)), Eq(y(t).diff(t), y(t) + x(t))]
|
| 409 |
+
>>> linear_ode_to_matrix(eqs, funcs, t, 1)
|
| 410 |
+
Traceback (most recent call last):
|
| 411 |
+
...
|
| 412 |
+
ODEOrderError: Cannot represent system in 1-order form
|
| 413 |
+
|
| 414 |
+
If the system of equations is nonlinear, then ODENonlinearError is
|
| 415 |
+
raised.
|
| 416 |
+
|
| 417 |
+
>>> eqs = [Eq(x(t).diff(t), x(t) + y(t)), Eq(y(t).diff(t), y(t)**2 + x(t))]
|
| 418 |
+
>>> linear_ode_to_matrix(eqs, funcs, t, 1)
|
| 419 |
+
Traceback (most recent call last):
|
| 420 |
+
...
|
| 421 |
+
ODENonlinearError: The system of ODEs is nonlinear.
|
| 422 |
+
|
| 423 |
+
Parameters
|
| 424 |
+
==========
|
| 425 |
+
|
| 426 |
+
eqs : list of SymPy expressions or equalities
|
| 427 |
+
The equations as expressions (assumed equal to zero).
|
| 428 |
+
funcs : list of applied functions
|
| 429 |
+
The dependent variables of the system of ODEs.
|
| 430 |
+
t : symbol
|
| 431 |
+
The independent variable.
|
| 432 |
+
order : int
|
| 433 |
+
The order of the system of ODEs.
|
| 434 |
+
|
| 435 |
+
Returns
|
| 436 |
+
=======
|
| 437 |
+
|
| 438 |
+
The tuple ``(As, b)`` where ``As`` is a tuple of matrices and ``b`` is the
|
| 439 |
+
the matrix representing the rhs of the matrix equation.
|
| 440 |
+
|
| 441 |
+
Raises
|
| 442 |
+
======
|
| 443 |
+
|
| 444 |
+
ODEOrderError
|
| 445 |
+
When the system of ODEs have an order greater than what was specified
|
| 446 |
+
ODENonlinearError
|
| 447 |
+
When the system of ODEs is nonlinear
|
| 448 |
+
|
| 449 |
+
See Also
|
| 450 |
+
========
|
| 451 |
+
|
| 452 |
+
linear_eq_to_matrix: for systems of linear algebraic equations.
|
| 453 |
+
|
| 454 |
+
References
|
| 455 |
+
==========
|
| 456 |
+
|
| 457 |
+
.. [1] https://en.wikipedia.org/wiki/Matrix_differential_equation
|
| 458 |
+
|
| 459 |
+
"""
|
| 460 |
+
from sympy.solvers.solveset import linear_eq_to_matrix
|
| 461 |
+
|
| 462 |
+
if any(ode_order(eq, func) > order for eq in eqs for func in funcs):
|
| 463 |
+
msg = "Cannot represent system in {}-order form"
|
| 464 |
+
raise ODEOrderError(msg.format(order))
|
| 465 |
+
|
| 466 |
+
As = []
|
| 467 |
+
|
| 468 |
+
for o in range(order, -1, -1):
|
| 469 |
+
# Work from the highest derivative down
|
| 470 |
+
syms = [func.diff(t, o) for func in funcs]
|
| 471 |
+
|
| 472 |
+
# Ai is the matrix for X(t).diff(t, o)
|
| 473 |
+
# eqs is minus the remainder of the equations.
|
| 474 |
+
try:
|
| 475 |
+
Ai, b = linear_eq_to_matrix(eqs, syms)
|
| 476 |
+
except NonlinearError:
|
| 477 |
+
raise ODENonlinearError("The system of ODEs is nonlinear.")
|
| 478 |
+
|
| 479 |
+
Ai = Ai.applyfunc(expand_mul)
|
| 480 |
+
|
| 481 |
+
As.append(Ai if o == order else -Ai)
|
| 482 |
+
|
| 483 |
+
if o:
|
| 484 |
+
eqs = [-eq for eq in b]
|
| 485 |
+
else:
|
| 486 |
+
rhs = b
|
| 487 |
+
|
| 488 |
+
return As, rhs
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
def matrix_exp(A, t):
|
| 492 |
+
r"""
|
| 493 |
+
Matrix exponential $\exp(A*t)$ for the matrix ``A`` and scalar ``t``.
|
| 494 |
+
|
| 495 |
+
Explanation
|
| 496 |
+
===========
|
| 497 |
+
|
| 498 |
+
This functions returns the $\exp(A*t)$ by doing a simple
|
| 499 |
+
matrix multiplication:
|
| 500 |
+
|
| 501 |
+
.. math:: \exp(A*t) = P * expJ * P^{-1}
|
| 502 |
+
|
| 503 |
+
where $expJ$ is $\exp(J*t)$. $J$ is the Jordan normal
|
| 504 |
+
form of $A$ and $P$ is matrix such that:
|
| 505 |
+
|
| 506 |
+
.. math:: A = P * J * P^{-1}
|
| 507 |
+
|
| 508 |
+
The matrix exponential $\exp(A*t)$ appears in the solution of linear
|
| 509 |
+
differential equations. For example if $x$ is a vector and $A$ is a matrix
|
| 510 |
+
then the initial value problem
|
| 511 |
+
|
| 512 |
+
.. math:: \frac{dx(t)}{dt} = A \times x(t), x(0) = x0
|
| 513 |
+
|
| 514 |
+
has the unique solution
|
| 515 |
+
|
| 516 |
+
.. math:: x(t) = \exp(A t) x0
|
| 517 |
+
|
| 518 |
+
Examples
|
| 519 |
+
========
|
| 520 |
+
|
| 521 |
+
>>> from sympy import Symbol, Matrix, pprint
|
| 522 |
+
>>> from sympy.solvers.ode.systems import matrix_exp
|
| 523 |
+
>>> t = Symbol('t')
|
| 524 |
+
|
| 525 |
+
We will consider a 2x2 matrix for comupting the exponential
|
| 526 |
+
|
| 527 |
+
>>> A = Matrix([[2, -5], [2, -4]])
|
| 528 |
+
>>> pprint(A)
|
| 529 |
+
[2 -5]
|
| 530 |
+
[ ]
|
| 531 |
+
[2 -4]
|
| 532 |
+
|
| 533 |
+
Now, exp(A*t) is given as follows:
|
| 534 |
+
|
| 535 |
+
>>> pprint(matrix_exp(A, t))
|
| 536 |
+
[ -t -t -t ]
|
| 537 |
+
[3*e *sin(t) + e *cos(t) -5*e *sin(t) ]
|
| 538 |
+
[ ]
|
| 539 |
+
[ -t -t -t ]
|
| 540 |
+
[ 2*e *sin(t) - 3*e *sin(t) + e *cos(t)]
|
| 541 |
+
|
| 542 |
+
Parameters
|
| 543 |
+
==========
|
| 544 |
+
|
| 545 |
+
A : Matrix
|
| 546 |
+
The matrix $A$ in the expression $\exp(A*t)$
|
| 547 |
+
t : Symbol
|
| 548 |
+
The independent variable
|
| 549 |
+
|
| 550 |
+
See Also
|
| 551 |
+
========
|
| 552 |
+
|
| 553 |
+
matrix_exp_jordan_form: For exponential of Jordan normal form
|
| 554 |
+
|
| 555 |
+
References
|
| 556 |
+
==========
|
| 557 |
+
|
| 558 |
+
.. [1] https://en.wikipedia.org/wiki/Jordan_normal_form
|
| 559 |
+
.. [2] https://en.wikipedia.org/wiki/Matrix_exponential
|
| 560 |
+
|
| 561 |
+
"""
|
| 562 |
+
P, expJ = matrix_exp_jordan_form(A, t)
|
| 563 |
+
return P * expJ * P.inv()
|
| 564 |
+
|
| 565 |
+
|
| 566 |
+
def matrix_exp_jordan_form(A, t):
|
| 567 |
+
r"""
|
| 568 |
+
Matrix exponential $\exp(A*t)$ for the matrix *A* and scalar *t*.
|
| 569 |
+
|
| 570 |
+
Explanation
|
| 571 |
+
===========
|
| 572 |
+
|
| 573 |
+
Returns the Jordan form of the $\exp(A*t)$ along with the matrix $P$ such that:
|
| 574 |
+
|
| 575 |
+
.. math::
|
| 576 |
+
\exp(A*t) = P * expJ * P^{-1}
|
| 577 |
+
|
| 578 |
+
Examples
|
| 579 |
+
========
|
| 580 |
+
|
| 581 |
+
>>> from sympy import Matrix, Symbol
|
| 582 |
+
>>> from sympy.solvers.ode.systems import matrix_exp, matrix_exp_jordan_form
|
| 583 |
+
>>> t = Symbol('t')
|
| 584 |
+
|
| 585 |
+
We will consider a 2x2 defective matrix. This shows that our method
|
| 586 |
+
works even for defective matrices.
|
| 587 |
+
|
| 588 |
+
>>> A = Matrix([[1, 1], [0, 1]])
|
| 589 |
+
|
| 590 |
+
It can be observed that this function gives us the Jordan normal form
|
| 591 |
+
and the required invertible matrix P.
|
| 592 |
+
|
| 593 |
+
>>> P, expJ = matrix_exp_jordan_form(A, t)
|
| 594 |
+
|
| 595 |
+
Here, it is shown that P and expJ returned by this function is correct
|
| 596 |
+
as they satisfy the formula: P * expJ * P_inverse = exp(A*t).
|
| 597 |
+
|
| 598 |
+
>>> P * expJ * P.inv() == matrix_exp(A, t)
|
| 599 |
+
True
|
| 600 |
+
|
| 601 |
+
Parameters
|
| 602 |
+
==========
|
| 603 |
+
|
| 604 |
+
A : Matrix
|
| 605 |
+
The matrix $A$ in the expression $\exp(A*t)$
|
| 606 |
+
t : Symbol
|
| 607 |
+
The independent variable
|
| 608 |
+
|
| 609 |
+
References
|
| 610 |
+
==========
|
| 611 |
+
|
| 612 |
+
.. [1] https://en.wikipedia.org/wiki/Defective_matrix
|
| 613 |
+
.. [2] https://en.wikipedia.org/wiki/Jordan_matrix
|
| 614 |
+
.. [3] https://en.wikipedia.org/wiki/Jordan_normal_form
|
| 615 |
+
|
| 616 |
+
"""
|
| 617 |
+
|
| 618 |
+
N, M = A.shape
|
| 619 |
+
if N != M:
|
| 620 |
+
raise ValueError('Needed square matrix but got shape (%s, %s)' % (N, M))
|
| 621 |
+
elif A.has(t):
|
| 622 |
+
raise ValueError('Matrix A should not depend on t')
|
| 623 |
+
|
| 624 |
+
def jordan_chains(A):
|
| 625 |
+
'''Chains from Jordan normal form analogous to M.eigenvects().
|
| 626 |
+
Returns a dict with eignevalues as keys like:
|
| 627 |
+
{e1: [[v111,v112,...], [v121, v122,...]], e2:...}
|
| 628 |
+
where vijk is the kth vector in the jth chain for eigenvalue i.
|
| 629 |
+
'''
|
| 630 |
+
P, blocks = A.jordan_cells()
|
| 631 |
+
basis = [P[:,i] for i in range(P.shape[1])]
|
| 632 |
+
n = 0
|
| 633 |
+
chains = {}
|
| 634 |
+
for b in blocks:
|
| 635 |
+
eigval = b[0, 0]
|
| 636 |
+
size = b.shape[0]
|
| 637 |
+
if eigval not in chains:
|
| 638 |
+
chains[eigval] = []
|
| 639 |
+
chains[eigval].append(basis[n:n+size])
|
| 640 |
+
n += size
|
| 641 |
+
return chains
|
| 642 |
+
|
| 643 |
+
eigenchains = jordan_chains(A)
|
| 644 |
+
|
| 645 |
+
# Needed for consistency across Python versions
|
| 646 |
+
eigenchains_iter = sorted(eigenchains.items(), key=default_sort_key)
|
| 647 |
+
isreal = not A.has(I)
|
| 648 |
+
|
| 649 |
+
blocks = []
|
| 650 |
+
vectors = []
|
| 651 |
+
seen_conjugate = set()
|
| 652 |
+
for e, chains in eigenchains_iter:
|
| 653 |
+
for chain in chains:
|
| 654 |
+
n = len(chain)
|
| 655 |
+
if isreal and e != e.conjugate() and e.conjugate() in eigenchains:
|
| 656 |
+
if e in seen_conjugate:
|
| 657 |
+
continue
|
| 658 |
+
seen_conjugate.add(e.conjugate())
|
| 659 |
+
exprt = exp(re(e) * t)
|
| 660 |
+
imrt = im(e) * t
|
| 661 |
+
imblock = Matrix([[cos(imrt), sin(imrt)],
|
| 662 |
+
[-sin(imrt), cos(imrt)]])
|
| 663 |
+
expJblock2 = Matrix(n, n, lambda i,j:
|
| 664 |
+
imblock * t**(j-i) / factorial(j-i) if j >= i
|
| 665 |
+
else zeros(2, 2))
|
| 666 |
+
expJblock = Matrix(2*n, 2*n, lambda i,j: expJblock2[i//2,j//2][i%2,j%2])
|
| 667 |
+
|
| 668 |
+
blocks.append(exprt * expJblock)
|
| 669 |
+
for i in range(n):
|
| 670 |
+
vectors.append(re(chain[i]))
|
| 671 |
+
vectors.append(im(chain[i]))
|
| 672 |
+
else:
|
| 673 |
+
vectors.extend(chain)
|
| 674 |
+
fun = lambda i,j: t**(j-i)/factorial(j-i) if j >= i else 0
|
| 675 |
+
expJblock = Matrix(n, n, fun)
|
| 676 |
+
blocks.append(exp(e * t) * expJblock)
|
| 677 |
+
|
| 678 |
+
expJ = Matrix.diag(*blocks)
|
| 679 |
+
P = Matrix(N, N, lambda i,j: vectors[j][i])
|
| 680 |
+
|
| 681 |
+
return P, expJ
|
| 682 |
+
|
| 683 |
+
|
| 684 |
+
# Note: To add a docstring example with tau
|
| 685 |
+
def linodesolve(A, t, b=None, B=None, type="auto", doit=False,
|
| 686 |
+
tau=None):
|
| 687 |
+
r"""
|
| 688 |
+
System of n equations linear first-order differential equations
|
| 689 |
+
|
| 690 |
+
Explanation
|
| 691 |
+
===========
|
| 692 |
+
|
| 693 |
+
This solver solves the system of ODEs of the following form:
|
| 694 |
+
|
| 695 |
+
.. math::
|
| 696 |
+
X'(t) = A(t) X(t) + b(t)
|
| 697 |
+
|
| 698 |
+
Here, $A(t)$ is the coefficient matrix, $X(t)$ is the vector of n independent variables,
|
| 699 |
+
$b(t)$ is the non-homogeneous term and $X'(t)$ is the derivative of $X(t)$
|
| 700 |
+
|
| 701 |
+
Depending on the properties of $A(t)$ and $b(t)$, this solver evaluates the solution
|
| 702 |
+
differently.
|
| 703 |
+
|
| 704 |
+
When $A(t)$ is constant coefficient matrix and $b(t)$ is zero vector i.e. system is homogeneous,
|
| 705 |
+
the system is "type1". The solution is:
|
| 706 |
+
|
| 707 |
+
.. math::
|
| 708 |
+
X(t) = \exp(A t) C
|
| 709 |
+
|
| 710 |
+
Here, $C$ is a vector of constants and $A$ is the constant coefficient matrix.
|
| 711 |
+
|
| 712 |
+
When $A(t)$ is constant coefficient matrix and $b(t)$ is non-zero i.e. system is non-homogeneous,
|
| 713 |
+
the system is "type2". The solution is:
|
| 714 |
+
|
| 715 |
+
.. math::
|
| 716 |
+
X(t) = e^{A t} ( \int e^{- A t} b \,dt + C)
|
| 717 |
+
|
| 718 |
+
When $A(t)$ is coefficient matrix such that its commutative with its antiderivative $B(t)$ and
|
| 719 |
+
$b(t)$ is a zero vector i.e. system is homogeneous, the system is "type3". The solution is:
|
| 720 |
+
|
| 721 |
+
.. math::
|
| 722 |
+
X(t) = \exp(B(t)) C
|
| 723 |
+
|
| 724 |
+
When $A(t)$ is commutative with its antiderivative $B(t)$ and $b(t)$ is non-zero i.e. system is
|
| 725 |
+
non-homogeneous, the system is "type4". The solution is:
|
| 726 |
+
|
| 727 |
+
.. math::
|
| 728 |
+
X(t) = e^{B(t)} ( \int e^{-B(t)} b(t) \,dt + C)
|
| 729 |
+
|
| 730 |
+
When $A(t)$ is a coefficient matrix such that it can be factorized into a scalar and a constant
|
| 731 |
+
coefficient matrix:
|
| 732 |
+
|
| 733 |
+
.. math::
|
| 734 |
+
A(t) = f(t) * A
|
| 735 |
+
|
| 736 |
+
Where $f(t)$ is a scalar expression in the independent variable $t$ and $A$ is a constant matrix,
|
| 737 |
+
then we can do the following substitutions:
|
| 738 |
+
|
| 739 |
+
.. math::
|
| 740 |
+
tau = \int f(t) dt, X(t) = Y(tau), b(t) = b(f^{-1}(tau))
|
| 741 |
+
|
| 742 |
+
Here, the substitution for the non-homogeneous term is done only when its non-zero.
|
| 743 |
+
Using these substitutions, our original system becomes:
|
| 744 |
+
|
| 745 |
+
.. math::
|
| 746 |
+
Y'(tau) = A * Y(tau) + b(tau)/f(tau)
|
| 747 |
+
|
| 748 |
+
The above system can be easily solved using the solution for "type1" or "type2" depending
|
| 749 |
+
on the homogeneity of the system. After we get the solution for $Y(tau)$, we substitute the
|
| 750 |
+
solution for $tau$ as $t$ to get back $X(t)$
|
| 751 |
+
|
| 752 |
+
.. math::
|
| 753 |
+
X(t) = Y(tau)
|
| 754 |
+
|
| 755 |
+
Systems of "type5" and "type6" have a commutative antiderivative but we use this solution
|
| 756 |
+
because its faster to compute.
|
| 757 |
+
|
| 758 |
+
The final solution is the general solution for all the four equations since a constant coefficient
|
| 759 |
+
matrix is always commutative with its antidervative.
|
| 760 |
+
|
| 761 |
+
An additional feature of this function is, if someone wants to substitute for value of the independent
|
| 762 |
+
variable, they can pass the substitution `tau` and the solution will have the independent variable
|
| 763 |
+
substituted with the passed expression(`tau`).
|
| 764 |
+
|
| 765 |
+
Parameters
|
| 766 |
+
==========
|
| 767 |
+
|
| 768 |
+
A : Matrix
|
| 769 |
+
Coefficient matrix of the system of linear first order ODEs.
|
| 770 |
+
t : Symbol
|
| 771 |
+
Independent variable in the system of ODEs.
|
| 772 |
+
b : Matrix or None
|
| 773 |
+
Non-homogeneous term in the system of ODEs. If None is passed,
|
| 774 |
+
a homogeneous system of ODEs is assumed.
|
| 775 |
+
B : Matrix or None
|
| 776 |
+
Antiderivative of the coefficient matrix. If the antiderivative
|
| 777 |
+
is not passed and the solution requires the term, then the solver
|
| 778 |
+
would compute it internally.
|
| 779 |
+
type : String
|
| 780 |
+
Type of the system of ODEs passed. Depending on the type, the
|
| 781 |
+
solution is evaluated. The type values allowed and the corresponding
|
| 782 |
+
system it solves are: "type1" for constant coefficient homogeneous
|
| 783 |
+
"type2" for constant coefficient non-homogeneous, "type3" for non-constant
|
| 784 |
+
coefficient homogeneous, "type4" for non-constant coefficient non-homogeneous,
|
| 785 |
+
"type5" and "type6" for non-constant coefficient homogeneous and non-homogeneous
|
| 786 |
+
systems respectively where the coefficient matrix can be factorized to a constant
|
| 787 |
+
coefficient matrix.
|
| 788 |
+
The default value is "auto" which will let the solver decide the correct type of
|
| 789 |
+
the system passed.
|
| 790 |
+
doit : Boolean
|
| 791 |
+
Evaluate the solution if True, default value is False
|
| 792 |
+
tau: Expression
|
| 793 |
+
Used to substitute for the value of `t` after we get the solution of the system.
|
| 794 |
+
|
| 795 |
+
Examples
|
| 796 |
+
========
|
| 797 |
+
|
| 798 |
+
To solve the system of ODEs using this function directly, several things must be
|
| 799 |
+
done in the right order. Wrong inputs to the function will lead to incorrect results.
|
| 800 |
+
|
| 801 |
+
>>> from sympy import symbols, Function, Eq
|
| 802 |
+
>>> from sympy.solvers.ode.systems import canonical_odes, linear_ode_to_matrix, linodesolve, linodesolve_type
|
| 803 |
+
>>> from sympy.solvers.ode.subscheck import checkodesol
|
| 804 |
+
>>> f, g = symbols("f, g", cls=Function)
|
| 805 |
+
>>> x, a = symbols("x, a")
|
| 806 |
+
>>> funcs = [f(x), g(x)]
|
| 807 |
+
>>> eqs = [Eq(f(x).diff(x) - f(x), a*g(x) + 1), Eq(g(x).diff(x) + g(x), a*f(x))]
|
| 808 |
+
|
| 809 |
+
Here, it is important to note that before we derive the coefficient matrix, it is
|
| 810 |
+
important to get the system of ODEs into the desired form. For that we will use
|
| 811 |
+
:obj:`sympy.solvers.ode.systems.canonical_odes()`.
|
| 812 |
+
|
| 813 |
+
>>> eqs = canonical_odes(eqs, funcs, x)
|
| 814 |
+
>>> eqs
|
| 815 |
+
[[Eq(Derivative(f(x), x), a*g(x) + f(x) + 1), Eq(Derivative(g(x), x), a*f(x) - g(x))]]
|
| 816 |
+
|
| 817 |
+
Now, we will use :obj:`sympy.solvers.ode.systems.linear_ode_to_matrix()` to get the coefficient matrix and the
|
| 818 |
+
non-homogeneous term if it is there.
|
| 819 |
+
|
| 820 |
+
>>> eqs = eqs[0]
|
| 821 |
+
>>> (A1, A0), b = linear_ode_to_matrix(eqs, funcs, x, 1)
|
| 822 |
+
>>> A = A0
|
| 823 |
+
|
| 824 |
+
We have the coefficient matrices and the non-homogeneous term ready. Now, we can use
|
| 825 |
+
:obj:`sympy.solvers.ode.systems.linodesolve_type()` to get the information for the system of ODEs
|
| 826 |
+
to finally pass it to the solver.
|
| 827 |
+
|
| 828 |
+
>>> system_info = linodesolve_type(A, x, b=b)
|
| 829 |
+
>>> sol_vector = linodesolve(A, x, b=b, B=system_info['antiderivative'], type=system_info['type_of_equation'])
|
| 830 |
+
|
| 831 |
+
Now, we can prove if the solution is correct or not by using :obj:`sympy.solvers.ode.checkodesol()`
|
| 832 |
+
|
| 833 |
+
>>> sol = [Eq(f, s) for f, s in zip(funcs, sol_vector)]
|
| 834 |
+
>>> checkodesol(eqs, sol)
|
| 835 |
+
(True, [0, 0])
|
| 836 |
+
|
| 837 |
+
We can also use the doit method to evaluate the solutions passed by the function.
|
| 838 |
+
|
| 839 |
+
>>> sol_vector_evaluated = linodesolve(A, x, b=b, type="type2", doit=True)
|
| 840 |
+
|
| 841 |
+
Now, we will look at a system of ODEs which is non-constant.
|
| 842 |
+
|
| 843 |
+
>>> eqs = [Eq(f(x).diff(x), f(x) + x*g(x)), Eq(g(x).diff(x), -x*f(x) + g(x))]
|
| 844 |
+
|
| 845 |
+
The system defined above is already in the desired form, so we do not have to convert it.
|
| 846 |
+
|
| 847 |
+
>>> (A1, A0), b = linear_ode_to_matrix(eqs, funcs, x, 1)
|
| 848 |
+
>>> A = A0
|
| 849 |
+
|
| 850 |
+
A user can also pass the commutative antiderivative required for type3 and type4 system of ODEs.
|
| 851 |
+
Passing an incorrect one will lead to incorrect results. If the coefficient matrix is not commutative
|
| 852 |
+
with its antiderivative, then :obj:`sympy.solvers.ode.systems.linodesolve_type()` raises a NotImplementedError.
|
| 853 |
+
If it does have a commutative antiderivative, then the function just returns the information about the system.
|
| 854 |
+
|
| 855 |
+
>>> system_info = linodesolve_type(A, x, b=b)
|
| 856 |
+
|
| 857 |
+
Now, we can pass the antiderivative as an argument to get the solution. If the system information is not
|
| 858 |
+
passed, then the solver will compute the required arguments internally.
|
| 859 |
+
|
| 860 |
+
>>> sol_vector = linodesolve(A, x, b=b)
|
| 861 |
+
|
| 862 |
+
Once again, we can verify the solution obtained.
|
| 863 |
+
|
| 864 |
+
>>> sol = [Eq(f, s) for f, s in zip(funcs, sol_vector)]
|
| 865 |
+
>>> checkodesol(eqs, sol)
|
| 866 |
+
(True, [0, 0])
|
| 867 |
+
|
| 868 |
+
Returns
|
| 869 |
+
=======
|
| 870 |
+
|
| 871 |
+
List
|
| 872 |
+
|
| 873 |
+
Raises
|
| 874 |
+
======
|
| 875 |
+
|
| 876 |
+
ValueError
|
| 877 |
+
This error is raised when the coefficient matrix, non-homogeneous term
|
| 878 |
+
or the antiderivative, if passed, are not a matrix or
|
| 879 |
+
do not have correct dimensions
|
| 880 |
+
NonSquareMatrixError
|
| 881 |
+
When the coefficient matrix or its antiderivative, if passed is not a
|
| 882 |
+
square matrix
|
| 883 |
+
NotImplementedError
|
| 884 |
+
If the coefficient matrix does not have a commutative antiderivative
|
| 885 |
+
|
| 886 |
+
See Also
|
| 887 |
+
========
|
| 888 |
+
|
| 889 |
+
linear_ode_to_matrix: Coefficient matrix computation function
|
| 890 |
+
canonical_odes: System of ODEs representation change
|
| 891 |
+
linodesolve_type: Getting information about systems of ODEs to pass in this solver
|
| 892 |
+
|
| 893 |
+
"""
|
| 894 |
+
|
| 895 |
+
if not isinstance(A, MatrixBase):
|
| 896 |
+
raise ValueError(filldedent('''\
|
| 897 |
+
The coefficients of the system of ODEs should be of type Matrix
|
| 898 |
+
'''))
|
| 899 |
+
|
| 900 |
+
if not A.is_square:
|
| 901 |
+
raise NonSquareMatrixError(filldedent('''\
|
| 902 |
+
The coefficient matrix must be a square
|
| 903 |
+
'''))
|
| 904 |
+
|
| 905 |
+
if b is not None:
|
| 906 |
+
if not isinstance(b, MatrixBase):
|
| 907 |
+
raise ValueError(filldedent('''\
|
| 908 |
+
The non-homogeneous terms of the system of ODEs should be of type Matrix
|
| 909 |
+
'''))
|
| 910 |
+
|
| 911 |
+
if A.rows != b.rows:
|
| 912 |
+
raise ValueError(filldedent('''\
|
| 913 |
+
The system of ODEs should have the same number of non-homogeneous terms and the number of
|
| 914 |
+
equations
|
| 915 |
+
'''))
|
| 916 |
+
|
| 917 |
+
if B is not None:
|
| 918 |
+
if not isinstance(B, MatrixBase):
|
| 919 |
+
raise ValueError(filldedent('''\
|
| 920 |
+
The antiderivative of coefficients of the system of ODEs should be of type Matrix
|
| 921 |
+
'''))
|
| 922 |
+
|
| 923 |
+
if not B.is_square:
|
| 924 |
+
raise NonSquareMatrixError(filldedent('''\
|
| 925 |
+
The antiderivative of the coefficient matrix must be a square
|
| 926 |
+
'''))
|
| 927 |
+
|
| 928 |
+
if A.rows != B.rows:
|
| 929 |
+
raise ValueError(filldedent('''\
|
| 930 |
+
The coefficient matrix and its antiderivative should have same dimensions
|
| 931 |
+
'''))
|
| 932 |
+
|
| 933 |
+
if not any(type == "type{}".format(i) for i in range(1, 7)) and not type == "auto":
|
| 934 |
+
raise ValueError(filldedent('''\
|
| 935 |
+
The input type should be a valid one
|
| 936 |
+
'''))
|
| 937 |
+
|
| 938 |
+
n = A.rows
|
| 939 |
+
|
| 940 |
+
# constants = numbered_symbols(prefix='C', cls=Dummy, start=const_idx+1)
|
| 941 |
+
Cvect = Matrix([Dummy() for _ in range(n)])
|
| 942 |
+
|
| 943 |
+
if b is None and any(type == typ for typ in ["type2", "type4", "type6"]):
|
| 944 |
+
b = zeros(n, 1)
|
| 945 |
+
|
| 946 |
+
is_transformed = tau is not None
|
| 947 |
+
passed_type = type
|
| 948 |
+
|
| 949 |
+
if type == "auto":
|
| 950 |
+
system_info = linodesolve_type(A, t, b=b)
|
| 951 |
+
type = system_info["type_of_equation"]
|
| 952 |
+
B = system_info["antiderivative"]
|
| 953 |
+
|
| 954 |
+
if type in ("type5", "type6"):
|
| 955 |
+
is_transformed = True
|
| 956 |
+
if passed_type != "auto":
|
| 957 |
+
if tau is None:
|
| 958 |
+
system_info = _first_order_type5_6_subs(A, t, b=b)
|
| 959 |
+
if not system_info:
|
| 960 |
+
raise ValueError(filldedent('''
|
| 961 |
+
The system passed isn't {}.
|
| 962 |
+
'''.format(type)))
|
| 963 |
+
|
| 964 |
+
tau = system_info['tau']
|
| 965 |
+
t = system_info['t_']
|
| 966 |
+
A = system_info['A']
|
| 967 |
+
b = system_info['b']
|
| 968 |
+
|
| 969 |
+
intx_wrtt = lambda x: Integral(x, t) if x else 0
|
| 970 |
+
if type in ("type1", "type2", "type5", "type6"):
|
| 971 |
+
P, J = matrix_exp_jordan_form(A, t)
|
| 972 |
+
P = simplify(P)
|
| 973 |
+
|
| 974 |
+
if type in ("type1", "type5"):
|
| 975 |
+
sol_vector = P * (J * Cvect)
|
| 976 |
+
else:
|
| 977 |
+
Jinv = J.subs(t, -t)
|
| 978 |
+
sol_vector = P * J * ((Jinv * P.inv() * b).applyfunc(intx_wrtt) + Cvect)
|
| 979 |
+
else:
|
| 980 |
+
if B is None:
|
| 981 |
+
B, _ = _is_commutative_anti_derivative(A, t)
|
| 982 |
+
|
| 983 |
+
if type == "type3":
|
| 984 |
+
sol_vector = B.exp() * Cvect
|
| 985 |
+
else:
|
| 986 |
+
sol_vector = B.exp() * (((-B).exp() * b).applyfunc(intx_wrtt) + Cvect)
|
| 987 |
+
|
| 988 |
+
if is_transformed:
|
| 989 |
+
sol_vector = sol_vector.subs(t, tau)
|
| 990 |
+
|
| 991 |
+
gens = sol_vector.atoms(exp)
|
| 992 |
+
|
| 993 |
+
if type != "type1":
|
| 994 |
+
sol_vector = [expand_mul(s) for s in sol_vector]
|
| 995 |
+
|
| 996 |
+
sol_vector = [collect(s, ordered(gens), exact=True) for s in sol_vector]
|
| 997 |
+
|
| 998 |
+
if doit:
|
| 999 |
+
sol_vector = [s.doit() for s in sol_vector]
|
| 1000 |
+
|
| 1001 |
+
return sol_vector
|
| 1002 |
+
|
| 1003 |
+
|
| 1004 |
+
def _matrix_is_constant(M, t):
|
| 1005 |
+
"""Checks if the matrix M is independent of t or not."""
|
| 1006 |
+
return all(coef.as_independent(t, as_Add=True)[1] == 0 for coef in M)
|
| 1007 |
+
|
| 1008 |
+
|
| 1009 |
+
def canonical_odes(eqs, funcs, t):
|
| 1010 |
+
r"""
|
| 1011 |
+
Function that solves for highest order derivatives in a system
|
| 1012 |
+
|
| 1013 |
+
Explanation
|
| 1014 |
+
===========
|
| 1015 |
+
|
| 1016 |
+
This function inputs a system of ODEs and based on the system,
|
| 1017 |
+
the dependent variables and their highest order, returns the system
|
| 1018 |
+
in the following form:
|
| 1019 |
+
|
| 1020 |
+
.. math::
|
| 1021 |
+
X'(t) = A(t) X(t) + b(t)
|
| 1022 |
+
|
| 1023 |
+
Here, $X(t)$ is the vector of dependent variables of lower order, $A(t)$ is
|
| 1024 |
+
the coefficient matrix, $b(t)$ is the non-homogeneous term and $X'(t)$ is the
|
| 1025 |
+
vector of dependent variables in their respective highest order. We use the term
|
| 1026 |
+
canonical form to imply the system of ODEs which is of the above form.
|
| 1027 |
+
|
| 1028 |
+
If the system passed has a non-linear term with multiple solutions, then a list of
|
| 1029 |
+
systems is returned in its canonical form.
|
| 1030 |
+
|
| 1031 |
+
Parameters
|
| 1032 |
+
==========
|
| 1033 |
+
|
| 1034 |
+
eqs : List
|
| 1035 |
+
List of the ODEs
|
| 1036 |
+
funcs : List
|
| 1037 |
+
List of dependent variables
|
| 1038 |
+
t : Symbol
|
| 1039 |
+
Independent variable
|
| 1040 |
+
|
| 1041 |
+
Examples
|
| 1042 |
+
========
|
| 1043 |
+
|
| 1044 |
+
>>> from sympy import symbols, Function, Eq, Derivative
|
| 1045 |
+
>>> from sympy.solvers.ode.systems import canonical_odes
|
| 1046 |
+
>>> f, g = symbols("f g", cls=Function)
|
| 1047 |
+
>>> x, y = symbols("x y")
|
| 1048 |
+
>>> funcs = [f(x), g(x)]
|
| 1049 |
+
>>> eqs = [Eq(f(x).diff(x) - 7*f(x), 12*g(x)), Eq(g(x).diff(x) + g(x), 20*f(x))]
|
| 1050 |
+
|
| 1051 |
+
>>> canonical_eqs = canonical_odes(eqs, funcs, x)
|
| 1052 |
+
>>> canonical_eqs
|
| 1053 |
+
[[Eq(Derivative(f(x), x), 7*f(x) + 12*g(x)), Eq(Derivative(g(x), x), 20*f(x) - g(x))]]
|
| 1054 |
+
|
| 1055 |
+
>>> system = [Eq(Derivative(f(x), x)**2 - 2*Derivative(f(x), x) + 1, 4), Eq(-y*f(x) + Derivative(g(x), x), 0)]
|
| 1056 |
+
|
| 1057 |
+
>>> canonical_system = canonical_odes(system, funcs, x)
|
| 1058 |
+
>>> canonical_system
|
| 1059 |
+
[[Eq(Derivative(f(x), x), -1), Eq(Derivative(g(x), x), y*f(x))], [Eq(Derivative(f(x), x), 3), Eq(Derivative(g(x), x), y*f(x))]]
|
| 1060 |
+
|
| 1061 |
+
Returns
|
| 1062 |
+
=======
|
| 1063 |
+
|
| 1064 |
+
List
|
| 1065 |
+
|
| 1066 |
+
"""
|
| 1067 |
+
from sympy.solvers.solvers import solve
|
| 1068 |
+
|
| 1069 |
+
order = _get_func_order(eqs, funcs)
|
| 1070 |
+
|
| 1071 |
+
canon_eqs = solve(eqs, *[func.diff(t, order[func]) for func in funcs], dict=True)
|
| 1072 |
+
|
| 1073 |
+
systems = []
|
| 1074 |
+
for eq in canon_eqs:
|
| 1075 |
+
system = [Eq(func.diff(t, order[func]), eq[func.diff(t, order[func])]) for func in funcs]
|
| 1076 |
+
systems.append(system)
|
| 1077 |
+
|
| 1078 |
+
return systems
|
| 1079 |
+
|
| 1080 |
+
|
| 1081 |
+
def _is_commutative_anti_derivative(A, t):
|
| 1082 |
+
r"""
|
| 1083 |
+
Helper function for determining if the Matrix passed is commutative with its antiderivative
|
| 1084 |
+
|
| 1085 |
+
Explanation
|
| 1086 |
+
===========
|
| 1087 |
+
|
| 1088 |
+
This function checks if the Matrix $A$ passed is commutative with its antiderivative with respect
|
| 1089 |
+
to the independent variable $t$.
|
| 1090 |
+
|
| 1091 |
+
.. math::
|
| 1092 |
+
B(t) = \int A(t) dt
|
| 1093 |
+
|
| 1094 |
+
The function outputs two values, first one being the antiderivative $B(t)$, second one being a
|
| 1095 |
+
boolean value, if True, then the matrix $A(t)$ passed is commutative with $B(t)$, else the matrix
|
| 1096 |
+
passed isn't commutative with $B(t)$.
|
| 1097 |
+
|
| 1098 |
+
Parameters
|
| 1099 |
+
==========
|
| 1100 |
+
|
| 1101 |
+
A : Matrix
|
| 1102 |
+
The matrix which has to be checked
|
| 1103 |
+
t : Symbol
|
| 1104 |
+
Independent variable
|
| 1105 |
+
|
| 1106 |
+
Examples
|
| 1107 |
+
========
|
| 1108 |
+
|
| 1109 |
+
>>> from sympy import symbols, Matrix
|
| 1110 |
+
>>> from sympy.solvers.ode.systems import _is_commutative_anti_derivative
|
| 1111 |
+
>>> t = symbols("t")
|
| 1112 |
+
>>> A = Matrix([[1, t], [-t, 1]])
|
| 1113 |
+
|
| 1114 |
+
>>> B, is_commuting = _is_commutative_anti_derivative(A, t)
|
| 1115 |
+
>>> is_commuting
|
| 1116 |
+
True
|
| 1117 |
+
|
| 1118 |
+
Returns
|
| 1119 |
+
=======
|
| 1120 |
+
|
| 1121 |
+
Matrix, Boolean
|
| 1122 |
+
|
| 1123 |
+
"""
|
| 1124 |
+
B = integrate(A, t)
|
| 1125 |
+
is_commuting = (B*A - A*B).applyfunc(expand).applyfunc(factor_terms).is_zero_matrix
|
| 1126 |
+
|
| 1127 |
+
is_commuting = False if is_commuting is None else is_commuting
|
| 1128 |
+
|
| 1129 |
+
return B, is_commuting
|
| 1130 |
+
|
| 1131 |
+
|
| 1132 |
+
def _factor_matrix(A, t):
|
| 1133 |
+
term = None
|
| 1134 |
+
for element in A:
|
| 1135 |
+
temp_term = element.as_independent(t)[1]
|
| 1136 |
+
if temp_term.has(t):
|
| 1137 |
+
term = temp_term
|
| 1138 |
+
break
|
| 1139 |
+
|
| 1140 |
+
if term is not None:
|
| 1141 |
+
A_factored = (A/term).applyfunc(ratsimp)
|
| 1142 |
+
can_factor = _matrix_is_constant(A_factored, t)
|
| 1143 |
+
term = (term, A_factored) if can_factor else None
|
| 1144 |
+
|
| 1145 |
+
return term
|
| 1146 |
+
|
| 1147 |
+
|
| 1148 |
+
def _is_second_order_type2(A, t):
|
| 1149 |
+
term = _factor_matrix(A, t)
|
| 1150 |
+
is_type2 = False
|
| 1151 |
+
|
| 1152 |
+
if term is not None:
|
| 1153 |
+
term = 1/term[0]
|
| 1154 |
+
is_type2 = term.is_polynomial()
|
| 1155 |
+
|
| 1156 |
+
if is_type2:
|
| 1157 |
+
poly = Poly(term.expand(), t)
|
| 1158 |
+
monoms = poly.monoms()
|
| 1159 |
+
|
| 1160 |
+
if monoms[0][0] in (2, 4):
|
| 1161 |
+
cs = _get_poly_coeffs(poly, 4)
|
| 1162 |
+
a, b, c, d, e = cs
|
| 1163 |
+
|
| 1164 |
+
a1 = powdenest(sqrt(a), force=True)
|
| 1165 |
+
c1 = powdenest(sqrt(e), force=True)
|
| 1166 |
+
b1 = powdenest(sqrt(c - 2*a1*c1), force=True)
|
| 1167 |
+
|
| 1168 |
+
is_type2 = (b == 2*a1*b1) and (d == 2*b1*c1)
|
| 1169 |
+
term = a1*t**2 + b1*t + c1
|
| 1170 |
+
|
| 1171 |
+
else:
|
| 1172 |
+
is_type2 = False
|
| 1173 |
+
|
| 1174 |
+
return is_type2, term
|
| 1175 |
+
|
| 1176 |
+
|
| 1177 |
+
def _get_poly_coeffs(poly, order):
|
| 1178 |
+
cs = [0 for _ in range(order+1)]
|
| 1179 |
+
for c, m in zip(poly.coeffs(), poly.monoms()):
|
| 1180 |
+
cs[-1-m[0]] = c
|
| 1181 |
+
return cs
|
| 1182 |
+
|
| 1183 |
+
|
| 1184 |
+
def _match_second_order_type(A1, A0, t, b=None):
|
| 1185 |
+
r"""
|
| 1186 |
+
Works only for second order system in its canonical form.
|
| 1187 |
+
|
| 1188 |
+
Type 0: Constant coefficient matrix, can be simply solved by
|
| 1189 |
+
introducing dummy variables.
|
| 1190 |
+
Type 1: When the substitution: $U = t*X' - X$ works for reducing
|
| 1191 |
+
the second order system to first order system.
|
| 1192 |
+
Type 2: When the system is of the form: $poly * X'' = A*X$ where
|
| 1193 |
+
$poly$ is square of a quadratic polynomial with respect to
|
| 1194 |
+
*t* and $A$ is a constant coefficient matrix.
|
| 1195 |
+
|
| 1196 |
+
"""
|
| 1197 |
+
match = {"type_of_equation": "type0"}
|
| 1198 |
+
n = A1.shape[0]
|
| 1199 |
+
|
| 1200 |
+
if _matrix_is_constant(A1, t) and _matrix_is_constant(A0, t):
|
| 1201 |
+
return match
|
| 1202 |
+
|
| 1203 |
+
if (A1 + A0*t).applyfunc(expand_mul).is_zero_matrix:
|
| 1204 |
+
match.update({"type_of_equation": "type1", "A1": A1})
|
| 1205 |
+
|
| 1206 |
+
elif A1.is_zero_matrix and (b is None or b.is_zero_matrix):
|
| 1207 |
+
is_type2, term = _is_second_order_type2(A0, t)
|
| 1208 |
+
if is_type2:
|
| 1209 |
+
a, b, c = _get_poly_coeffs(Poly(term, t), 2)
|
| 1210 |
+
A = (A0*(term**2).expand()).applyfunc(ratsimp) + (b**2/4 - a*c)*eye(n, n)
|
| 1211 |
+
tau = integrate(1/term, t)
|
| 1212 |
+
t_ = Symbol("{}_".format(t))
|
| 1213 |
+
match.update({"type_of_equation": "type2", "A0": A,
|
| 1214 |
+
"g(t)": sqrt(term), "tau": tau, "is_transformed": True,
|
| 1215 |
+
"t_": t_})
|
| 1216 |
+
|
| 1217 |
+
return match
|
| 1218 |
+
|
| 1219 |
+
|
| 1220 |
+
def _second_order_subs_type1(A, b, funcs, t):
|
| 1221 |
+
r"""
|
| 1222 |
+
For a linear, second order system of ODEs, a particular substitution.
|
| 1223 |
+
|
| 1224 |
+
A system of the below form can be reduced to a linear first order system of
|
| 1225 |
+
ODEs:
|
| 1226 |
+
.. math::
|
| 1227 |
+
X'' = A(t) * (t*X' - X) + b(t)
|
| 1228 |
+
|
| 1229 |
+
By substituting:
|
| 1230 |
+
.. math:: U = t*X' - X
|
| 1231 |
+
|
| 1232 |
+
To get the system:
|
| 1233 |
+
.. math:: U' = t*(A(t)*U + b(t))
|
| 1234 |
+
|
| 1235 |
+
Where $U$ is the vector of dependent variables, $X$ is the vector of dependent
|
| 1236 |
+
variables in `funcs` and $X'$ is the first order derivative of $X$ with respect to
|
| 1237 |
+
$t$. It may or may not reduce the system into linear first order system of ODEs.
|
| 1238 |
+
|
| 1239 |
+
Then a check is made to determine if the system passed can be reduced or not, if
|
| 1240 |
+
this substitution works, then the system is reduced and its solved for the new
|
| 1241 |
+
substitution. After we get the solution for $U$:
|
| 1242 |
+
|
| 1243 |
+
.. math:: U = a(t)
|
| 1244 |
+
|
| 1245 |
+
We substitute and return the reduced system:
|
| 1246 |
+
|
| 1247 |
+
.. math::
|
| 1248 |
+
a(t) = t*X' - X
|
| 1249 |
+
|
| 1250 |
+
Parameters
|
| 1251 |
+
==========
|
| 1252 |
+
|
| 1253 |
+
A: Matrix
|
| 1254 |
+
Coefficient matrix($A(t)*t$) of the second order system of this form.
|
| 1255 |
+
b: Matrix
|
| 1256 |
+
Non-homogeneous term($b(t)$) of the system of ODEs.
|
| 1257 |
+
funcs: List
|
| 1258 |
+
List of dependent variables
|
| 1259 |
+
t: Symbol
|
| 1260 |
+
Independent variable of the system of ODEs.
|
| 1261 |
+
|
| 1262 |
+
Returns
|
| 1263 |
+
=======
|
| 1264 |
+
|
| 1265 |
+
List
|
| 1266 |
+
|
| 1267 |
+
"""
|
| 1268 |
+
|
| 1269 |
+
U = Matrix([t*func.diff(t) - func for func in funcs])
|
| 1270 |
+
|
| 1271 |
+
sol = linodesolve(A, t, t*b)
|
| 1272 |
+
reduced_eqs = [Eq(u, s) for s, u in zip(sol, U)]
|
| 1273 |
+
reduced_eqs = canonical_odes(reduced_eqs, funcs, t)[0]
|
| 1274 |
+
|
| 1275 |
+
return reduced_eqs
|
| 1276 |
+
|
| 1277 |
+
|
| 1278 |
+
def _second_order_subs_type2(A, funcs, t_):
|
| 1279 |
+
r"""
|
| 1280 |
+
Returns a second order system based on the coefficient matrix passed.
|
| 1281 |
+
|
| 1282 |
+
Explanation
|
| 1283 |
+
===========
|
| 1284 |
+
|
| 1285 |
+
This function returns a system of second order ODE of the following form:
|
| 1286 |
+
|
| 1287 |
+
.. math::
|
| 1288 |
+
X'' = A * X
|
| 1289 |
+
|
| 1290 |
+
Here, $X$ is the vector of dependent variables, but a bit modified, $A$ is the
|
| 1291 |
+
coefficient matrix passed.
|
| 1292 |
+
|
| 1293 |
+
Along with returning the second order system, this function also returns the new
|
| 1294 |
+
dependent variables with the new independent variable `t_` passed.
|
| 1295 |
+
|
| 1296 |
+
Parameters
|
| 1297 |
+
==========
|
| 1298 |
+
|
| 1299 |
+
A: Matrix
|
| 1300 |
+
Coefficient matrix of the system
|
| 1301 |
+
funcs: List
|
| 1302 |
+
List of old dependent variables
|
| 1303 |
+
t_: Symbol
|
| 1304 |
+
New independent variable
|
| 1305 |
+
|
| 1306 |
+
Returns
|
| 1307 |
+
=======
|
| 1308 |
+
|
| 1309 |
+
List, List
|
| 1310 |
+
|
| 1311 |
+
"""
|
| 1312 |
+
func_names = [func.func.__name__ for func in funcs]
|
| 1313 |
+
new_funcs = [Function(Dummy("{}_".format(name)))(t_) for name in func_names]
|
| 1314 |
+
rhss = A * Matrix(new_funcs)
|
| 1315 |
+
new_eqs = [Eq(func.diff(t_, 2), rhs) for func, rhs in zip(new_funcs, rhss)]
|
| 1316 |
+
|
| 1317 |
+
return new_eqs, new_funcs
|
| 1318 |
+
|
| 1319 |
+
|
| 1320 |
+
def _is_euler_system(As, t):
|
| 1321 |
+
return all(_matrix_is_constant((A*t**i).applyfunc(ratsimp), t) for i, A in enumerate(As))
|
| 1322 |
+
|
| 1323 |
+
|
| 1324 |
+
def _classify_linear_system(eqs, funcs, t, is_canon=False):
|
| 1325 |
+
r"""
|
| 1326 |
+
Returns a dictionary with details of the eqs if the system passed is linear
|
| 1327 |
+
and can be classified by this function else returns None
|
| 1328 |
+
|
| 1329 |
+
Explanation
|
| 1330 |
+
===========
|
| 1331 |
+
|
| 1332 |
+
This function takes the eqs, converts it into a form Ax = b where x is a vector of terms
|
| 1333 |
+
containing dependent variables and their derivatives till their maximum order. If it is
|
| 1334 |
+
possible to convert eqs into Ax = b, then all the equations in eqs are linear otherwise
|
| 1335 |
+
they are non-linear.
|
| 1336 |
+
|
| 1337 |
+
To check if the equations are constant coefficient, we need to check if all the terms in
|
| 1338 |
+
A obtained above are constant or not.
|
| 1339 |
+
|
| 1340 |
+
To check if the equations are homogeneous or not, we need to check if b is a zero matrix
|
| 1341 |
+
or not.
|
| 1342 |
+
|
| 1343 |
+
Parameters
|
| 1344 |
+
==========
|
| 1345 |
+
|
| 1346 |
+
eqs: List
|
| 1347 |
+
List of ODEs
|
| 1348 |
+
funcs: List
|
| 1349 |
+
List of dependent variables
|
| 1350 |
+
t: Symbol
|
| 1351 |
+
Independent variable of the equations in eqs
|
| 1352 |
+
is_canon: Boolean
|
| 1353 |
+
If True, then this function will not try to get the
|
| 1354 |
+
system in canonical form. Default value is False
|
| 1355 |
+
|
| 1356 |
+
Returns
|
| 1357 |
+
=======
|
| 1358 |
+
|
| 1359 |
+
match = {
|
| 1360 |
+
'no_of_equation': len(eqs),
|
| 1361 |
+
'eq': eqs,
|
| 1362 |
+
'func': funcs,
|
| 1363 |
+
'order': order,
|
| 1364 |
+
'is_linear': is_linear,
|
| 1365 |
+
'is_constant': is_constant,
|
| 1366 |
+
'is_homogeneous': is_homogeneous,
|
| 1367 |
+
}
|
| 1368 |
+
|
| 1369 |
+
Dict or list of Dicts or None
|
| 1370 |
+
Dict with values for keys:
|
| 1371 |
+
1. no_of_equation: Number of equations
|
| 1372 |
+
2. eq: The set of equations
|
| 1373 |
+
3. func: List of dependent variables
|
| 1374 |
+
4. order: A dictionary that gives the order of the
|
| 1375 |
+
dependent variable in eqs
|
| 1376 |
+
5. is_linear: Boolean value indicating if the set of
|
| 1377 |
+
equations are linear or not.
|
| 1378 |
+
6. is_constant: Boolean value indicating if the set of
|
| 1379 |
+
equations have constant coefficients or not.
|
| 1380 |
+
7. is_homogeneous: Boolean value indicating if the set of
|
| 1381 |
+
equations are homogeneous or not.
|
| 1382 |
+
8. commutative_antiderivative: Antiderivative of the coefficient
|
| 1383 |
+
matrix if the coefficient matrix is non-constant
|
| 1384 |
+
and commutative with its antiderivative. This key
|
| 1385 |
+
may or may not exist.
|
| 1386 |
+
9. is_general: Boolean value indicating if the system of ODEs is
|
| 1387 |
+
solvable using one of the general case solvers or not.
|
| 1388 |
+
10. rhs: rhs of the non-homogeneous system of ODEs in Matrix form. This
|
| 1389 |
+
key may or may not exist.
|
| 1390 |
+
11. is_higher_order: True if the system passed has an order greater than 1.
|
| 1391 |
+
This key may or may not exist.
|
| 1392 |
+
12. is_second_order: True if the system passed is a second order ODE. This
|
| 1393 |
+
key may or may not exist.
|
| 1394 |
+
This Dict is the answer returned if the eqs are linear and constant
|
| 1395 |
+
coefficient. Otherwise, None is returned.
|
| 1396 |
+
|
| 1397 |
+
"""
|
| 1398 |
+
|
| 1399 |
+
# Error for i == 0 can be added but isn't for now
|
| 1400 |
+
|
| 1401 |
+
# Check for len(funcs) == len(eqs)
|
| 1402 |
+
if len(funcs) != len(eqs):
|
| 1403 |
+
raise ValueError("Number of functions given is not equal to the number of equations %s" % funcs)
|
| 1404 |
+
|
| 1405 |
+
# ValueError when functions have more than one arguments
|
| 1406 |
+
for func in funcs:
|
| 1407 |
+
if len(func.args) != 1:
|
| 1408 |
+
raise ValueError("dsolve() and classify_sysode() work with "
|
| 1409 |
+
"functions of one variable only, not %s" % func)
|
| 1410 |
+
|
| 1411 |
+
# Getting the func_dict and order using the helper
|
| 1412 |
+
# function
|
| 1413 |
+
order = _get_func_order(eqs, funcs)
|
| 1414 |
+
system_order = max(order[func] for func in funcs)
|
| 1415 |
+
is_higher_order = system_order > 1
|
| 1416 |
+
is_second_order = system_order == 2 and all(order[func] == 2 for func in funcs)
|
| 1417 |
+
|
| 1418 |
+
# Not adding the check if the len(func.args) for
|
| 1419 |
+
# every func in funcs is 1
|
| 1420 |
+
|
| 1421 |
+
# Linearity check
|
| 1422 |
+
try:
|
| 1423 |
+
|
| 1424 |
+
canon_eqs = canonical_odes(eqs, funcs, t) if not is_canon else [eqs]
|
| 1425 |
+
if len(canon_eqs) == 1:
|
| 1426 |
+
As, b = linear_ode_to_matrix(canon_eqs[0], funcs, t, system_order)
|
| 1427 |
+
else:
|
| 1428 |
+
|
| 1429 |
+
match = {
|
| 1430 |
+
'is_implicit': True,
|
| 1431 |
+
'canon_eqs': canon_eqs
|
| 1432 |
+
}
|
| 1433 |
+
|
| 1434 |
+
return match
|
| 1435 |
+
|
| 1436 |
+
# When the system of ODEs is non-linear, an ODENonlinearError is raised.
|
| 1437 |
+
# This function catches the error and None is returned.
|
| 1438 |
+
except ODENonlinearError:
|
| 1439 |
+
return None
|
| 1440 |
+
|
| 1441 |
+
is_linear = True
|
| 1442 |
+
|
| 1443 |
+
# Homogeneous check
|
| 1444 |
+
is_homogeneous = True if b.is_zero_matrix else False
|
| 1445 |
+
|
| 1446 |
+
# Is general key is used to identify if the system of ODEs can be solved by
|
| 1447 |
+
# one of the general case solvers or not.
|
| 1448 |
+
match = {
|
| 1449 |
+
'no_of_equation': len(eqs),
|
| 1450 |
+
'eq': eqs,
|
| 1451 |
+
'func': funcs,
|
| 1452 |
+
'order': order,
|
| 1453 |
+
'is_linear': is_linear,
|
| 1454 |
+
'is_homogeneous': is_homogeneous,
|
| 1455 |
+
'is_general': True
|
| 1456 |
+
}
|
| 1457 |
+
|
| 1458 |
+
if not is_homogeneous:
|
| 1459 |
+
match['rhs'] = b
|
| 1460 |
+
|
| 1461 |
+
is_constant = all(_matrix_is_constant(A_, t) for A_ in As)
|
| 1462 |
+
|
| 1463 |
+
# The match['is_linear'] check will be added in the future when this
|
| 1464 |
+
# function becomes ready to deal with non-linear systems of ODEs
|
| 1465 |
+
|
| 1466 |
+
if not is_higher_order:
|
| 1467 |
+
A = As[1]
|
| 1468 |
+
match['func_coeff'] = A
|
| 1469 |
+
|
| 1470 |
+
# Constant coefficient check
|
| 1471 |
+
is_constant = _matrix_is_constant(A, t)
|
| 1472 |
+
match['is_constant'] = is_constant
|
| 1473 |
+
|
| 1474 |
+
try:
|
| 1475 |
+
system_info = linodesolve_type(A, t, b=b)
|
| 1476 |
+
except NotImplementedError:
|
| 1477 |
+
return None
|
| 1478 |
+
|
| 1479 |
+
match.update(system_info)
|
| 1480 |
+
antiderivative = match.pop("antiderivative")
|
| 1481 |
+
|
| 1482 |
+
if not is_constant:
|
| 1483 |
+
match['commutative_antiderivative'] = antiderivative
|
| 1484 |
+
|
| 1485 |
+
return match
|
| 1486 |
+
else:
|
| 1487 |
+
match['type_of_equation'] = "type0"
|
| 1488 |
+
|
| 1489 |
+
if is_second_order:
|
| 1490 |
+
A1, A0 = As[1:]
|
| 1491 |
+
|
| 1492 |
+
match_second_order = _match_second_order_type(A1, A0, t)
|
| 1493 |
+
match.update(match_second_order)
|
| 1494 |
+
|
| 1495 |
+
match['is_second_order'] = True
|
| 1496 |
+
|
| 1497 |
+
# If system is constant, then no need to check if its in euler
|
| 1498 |
+
# form or not. It will be easier and faster to directly proceed
|
| 1499 |
+
# to solve it.
|
| 1500 |
+
if match['type_of_equation'] == "type0" and not is_constant:
|
| 1501 |
+
is_euler = _is_euler_system(As, t)
|
| 1502 |
+
if is_euler:
|
| 1503 |
+
t_ = Symbol('{}_'.format(t))
|
| 1504 |
+
match.update({'is_transformed': True, 'type_of_equation': 'type1',
|
| 1505 |
+
't_': t_})
|
| 1506 |
+
else:
|
| 1507 |
+
is_jordan = lambda M: M == Matrix.jordan_block(M.shape[0], M[0, 0])
|
| 1508 |
+
terms = _factor_matrix(As[-1], t)
|
| 1509 |
+
if all(A.is_zero_matrix for A in As[1:-1]) and terms is not None and not is_jordan(terms[1]):
|
| 1510 |
+
P, J = terms[1].jordan_form()
|
| 1511 |
+
match.update({'type_of_equation': 'type2', 'J': J,
|
| 1512 |
+
'f(t)': terms[0], 'P': P, 'is_transformed': True})
|
| 1513 |
+
|
| 1514 |
+
if match['type_of_equation'] != 'type0' and is_second_order:
|
| 1515 |
+
match.pop('is_second_order', None)
|
| 1516 |
+
|
| 1517 |
+
match['is_higher_order'] = is_higher_order
|
| 1518 |
+
|
| 1519 |
+
return match
|
| 1520 |
+
|
| 1521 |
+
def _preprocess_eqs(eqs):
|
| 1522 |
+
processed_eqs = []
|
| 1523 |
+
for eq in eqs:
|
| 1524 |
+
processed_eqs.append(eq if isinstance(eq, Equality) else Eq(eq, 0))
|
| 1525 |
+
|
| 1526 |
+
return processed_eqs
|
| 1527 |
+
|
| 1528 |
+
|
| 1529 |
+
def _eqs2dict(eqs, funcs):
|
| 1530 |
+
eqsorig = {}
|
| 1531 |
+
eqsmap = {}
|
| 1532 |
+
funcset = set(funcs)
|
| 1533 |
+
for eq in eqs:
|
| 1534 |
+
f1, = eq.lhs.atoms(AppliedUndef)
|
| 1535 |
+
f2s = (eq.rhs.atoms(AppliedUndef) - {f1}) & funcset
|
| 1536 |
+
eqsmap[f1] = f2s
|
| 1537 |
+
eqsorig[f1] = eq
|
| 1538 |
+
return eqsmap, eqsorig
|
| 1539 |
+
|
| 1540 |
+
|
| 1541 |
+
def _dict2graph(d):
|
| 1542 |
+
nodes = list(d)
|
| 1543 |
+
edges = [(f1, f2) for f1, f2s in d.items() for f2 in f2s]
|
| 1544 |
+
G = (nodes, edges)
|
| 1545 |
+
return G
|
| 1546 |
+
|
| 1547 |
+
|
| 1548 |
+
def _is_type1(scc, t):
|
| 1549 |
+
eqs, funcs = scc
|
| 1550 |
+
|
| 1551 |
+
try:
|
| 1552 |
+
(A1, A0), b = linear_ode_to_matrix(eqs, funcs, t, 1)
|
| 1553 |
+
except (ODENonlinearError, ODEOrderError):
|
| 1554 |
+
return False
|
| 1555 |
+
|
| 1556 |
+
if _matrix_is_constant(A0, t) and b.is_zero_matrix:
|
| 1557 |
+
return True
|
| 1558 |
+
|
| 1559 |
+
return False
|
| 1560 |
+
|
| 1561 |
+
|
| 1562 |
+
def _combine_type1_subsystems(subsystem, funcs, t):
|
| 1563 |
+
indices = [i for i, sys in enumerate(zip(subsystem, funcs)) if _is_type1(sys, t)]
|
| 1564 |
+
remove = set()
|
| 1565 |
+
for ip, i in enumerate(indices):
|
| 1566 |
+
for j in indices[ip+1:]:
|
| 1567 |
+
if any(eq2.has(funcs[i]) for eq2 in subsystem[j]):
|
| 1568 |
+
subsystem[j] = subsystem[i] + subsystem[j]
|
| 1569 |
+
remove.add(i)
|
| 1570 |
+
subsystem = [sys for i, sys in enumerate(subsystem) if i not in remove]
|
| 1571 |
+
return subsystem
|
| 1572 |
+
|
| 1573 |
+
|
| 1574 |
+
def _component_division(eqs, funcs, t):
|
| 1575 |
+
|
| 1576 |
+
# Assuming that each eq in eqs is in canonical form,
|
| 1577 |
+
# that is, [f(x).diff(x) = .., g(x).diff(x) = .., etc]
|
| 1578 |
+
# and that the system passed is in its first order
|
| 1579 |
+
eqsmap, eqsorig = _eqs2dict(eqs, funcs)
|
| 1580 |
+
|
| 1581 |
+
subsystems = []
|
| 1582 |
+
for cc in connected_components(_dict2graph(eqsmap)):
|
| 1583 |
+
eqsmap_c = {f: eqsmap[f] for f in cc}
|
| 1584 |
+
sccs = strongly_connected_components(_dict2graph(eqsmap_c))
|
| 1585 |
+
subsystem = [[eqsorig[f] for f in scc] for scc in sccs]
|
| 1586 |
+
subsystem = _combine_type1_subsystems(subsystem, sccs, t)
|
| 1587 |
+
subsystems.append(subsystem)
|
| 1588 |
+
|
| 1589 |
+
return subsystems
|
| 1590 |
+
|
| 1591 |
+
|
| 1592 |
+
# Returns: List of equations
|
| 1593 |
+
def _linear_ode_solver(match):
|
| 1594 |
+
t = match['t']
|
| 1595 |
+
funcs = match['func']
|
| 1596 |
+
|
| 1597 |
+
rhs = match.get('rhs', None)
|
| 1598 |
+
tau = match.get('tau', None)
|
| 1599 |
+
t = match['t_'] if 't_' in match else t
|
| 1600 |
+
A = match['func_coeff']
|
| 1601 |
+
|
| 1602 |
+
# Note: To make B None when the matrix has constant
|
| 1603 |
+
# coefficient
|
| 1604 |
+
B = match.get('commutative_antiderivative', None)
|
| 1605 |
+
type = match['type_of_equation']
|
| 1606 |
+
|
| 1607 |
+
sol_vector = linodesolve(A, t, b=rhs, B=B,
|
| 1608 |
+
type=type, tau=tau)
|
| 1609 |
+
|
| 1610 |
+
sol = [Eq(f, s) for f, s in zip(funcs, sol_vector)]
|
| 1611 |
+
|
| 1612 |
+
return sol
|
| 1613 |
+
|
| 1614 |
+
|
| 1615 |
+
def _select_equations(eqs, funcs, key=lambda x: x):
|
| 1616 |
+
eq_dict = {e.lhs: e.rhs for e in eqs}
|
| 1617 |
+
return [Eq(f, eq_dict[key(f)]) for f in funcs]
|
| 1618 |
+
|
| 1619 |
+
|
| 1620 |
+
def _higher_order_ode_solver(match):
|
| 1621 |
+
eqs = match["eq"]
|
| 1622 |
+
funcs = match["func"]
|
| 1623 |
+
t = match["t"]
|
| 1624 |
+
sysorder = match['order']
|
| 1625 |
+
type = match.get('type_of_equation', "type0")
|
| 1626 |
+
|
| 1627 |
+
is_second_order = match.get('is_second_order', False)
|
| 1628 |
+
is_transformed = match.get('is_transformed', False)
|
| 1629 |
+
is_euler = is_transformed and type == "type1"
|
| 1630 |
+
is_higher_order_type2 = is_transformed and type == "type2" and 'P' in match
|
| 1631 |
+
|
| 1632 |
+
if is_second_order:
|
| 1633 |
+
new_eqs, new_funcs = _second_order_to_first_order(eqs, funcs, t,
|
| 1634 |
+
A1=match.get("A1", None), A0=match.get("A0", None),
|
| 1635 |
+
b=match.get("rhs", None), type=type,
|
| 1636 |
+
t_=match.get("t_", None))
|
| 1637 |
+
else:
|
| 1638 |
+
new_eqs, new_funcs = _higher_order_to_first_order(eqs, sysorder, t, funcs=funcs,
|
| 1639 |
+
type=type, J=match.get('J', None),
|
| 1640 |
+
f_t=match.get('f(t)', None),
|
| 1641 |
+
P=match.get('P', None), b=match.get('rhs', None))
|
| 1642 |
+
|
| 1643 |
+
if is_transformed:
|
| 1644 |
+
t = match.get('t_', t)
|
| 1645 |
+
|
| 1646 |
+
if not is_higher_order_type2:
|
| 1647 |
+
new_eqs = _select_equations(new_eqs, [f.diff(t) for f in new_funcs])
|
| 1648 |
+
|
| 1649 |
+
sol = None
|
| 1650 |
+
|
| 1651 |
+
# NotImplementedError may be raised when the system may be actually
|
| 1652 |
+
# solvable if it can be just divided into sub-systems
|
| 1653 |
+
try:
|
| 1654 |
+
if not is_higher_order_type2:
|
| 1655 |
+
sol = _strong_component_solver(new_eqs, new_funcs, t)
|
| 1656 |
+
except NotImplementedError:
|
| 1657 |
+
sol = None
|
| 1658 |
+
|
| 1659 |
+
# Dividing the system only when it becomes essential
|
| 1660 |
+
if sol is None:
|
| 1661 |
+
try:
|
| 1662 |
+
sol = _component_solver(new_eqs, new_funcs, t)
|
| 1663 |
+
except NotImplementedError:
|
| 1664 |
+
sol = None
|
| 1665 |
+
|
| 1666 |
+
if sol is None:
|
| 1667 |
+
return sol
|
| 1668 |
+
|
| 1669 |
+
is_second_order_type2 = is_second_order and type == "type2"
|
| 1670 |
+
|
| 1671 |
+
underscores = '__' if is_transformed else '_'
|
| 1672 |
+
|
| 1673 |
+
sol = _select_equations(sol, funcs,
|
| 1674 |
+
key=lambda x: Function(Dummy('{}{}0'.format(x.func.__name__, underscores)))(t))
|
| 1675 |
+
|
| 1676 |
+
if match.get("is_transformed", False):
|
| 1677 |
+
if is_second_order_type2:
|
| 1678 |
+
g_t = match["g(t)"]
|
| 1679 |
+
tau = match["tau"]
|
| 1680 |
+
sol = [Eq(s.lhs, s.rhs.subs(t, tau) * g_t) for s in sol]
|
| 1681 |
+
elif is_euler:
|
| 1682 |
+
t = match['t']
|
| 1683 |
+
tau = match['t_']
|
| 1684 |
+
sol = [s.subs(tau, log(t)) for s in sol]
|
| 1685 |
+
elif is_higher_order_type2:
|
| 1686 |
+
P = match['P']
|
| 1687 |
+
sol_vector = P * Matrix([s.rhs for s in sol])
|
| 1688 |
+
sol = [Eq(f, s) for f, s in zip(funcs, sol_vector)]
|
| 1689 |
+
|
| 1690 |
+
return sol
|
| 1691 |
+
|
| 1692 |
+
|
| 1693 |
+
# Returns: List of equations or None
|
| 1694 |
+
# If None is returned by this solver, then the system
|
| 1695 |
+
# of ODEs cannot be solved directly by dsolve_system.
|
| 1696 |
+
def _strong_component_solver(eqs, funcs, t):
|
| 1697 |
+
from sympy.solvers.ode.ode import dsolve, constant_renumber
|
| 1698 |
+
|
| 1699 |
+
match = _classify_linear_system(eqs, funcs, t, is_canon=True)
|
| 1700 |
+
sol = None
|
| 1701 |
+
|
| 1702 |
+
# Assuming that we can't get an implicit system
|
| 1703 |
+
# since we are already canonical equations from
|
| 1704 |
+
# dsolve_system
|
| 1705 |
+
if match:
|
| 1706 |
+
match['t'] = t
|
| 1707 |
+
|
| 1708 |
+
if match.get('is_higher_order', False):
|
| 1709 |
+
sol = _higher_order_ode_solver(match)
|
| 1710 |
+
|
| 1711 |
+
elif match.get('is_linear', False):
|
| 1712 |
+
sol = _linear_ode_solver(match)
|
| 1713 |
+
|
| 1714 |
+
# Note: For now, only linear systems are handled by this function
|
| 1715 |
+
# hence, the match condition is added. This can be removed later.
|
| 1716 |
+
if sol is None and len(eqs) == 1:
|
| 1717 |
+
sol = dsolve(eqs[0], func=funcs[0])
|
| 1718 |
+
variables = Tuple(eqs[0]).free_symbols
|
| 1719 |
+
new_constants = [Dummy() for _ in range(ode_order(eqs[0], funcs[0]))]
|
| 1720 |
+
sol = constant_renumber(sol, variables=variables, newconstants=new_constants)
|
| 1721 |
+
sol = [sol]
|
| 1722 |
+
|
| 1723 |
+
# To add non-linear case here in future
|
| 1724 |
+
|
| 1725 |
+
return sol
|
| 1726 |
+
|
| 1727 |
+
|
| 1728 |
+
def _get_funcs_from_canon(eqs):
|
| 1729 |
+
return [eq.lhs.args[0] for eq in eqs]
|
| 1730 |
+
|
| 1731 |
+
|
| 1732 |
+
# Returns: List of Equations(a solution)
|
| 1733 |
+
def _weak_component_solver(wcc, t):
|
| 1734 |
+
|
| 1735 |
+
# We will divide the systems into sccs
|
| 1736 |
+
# only when the wcc cannot be solved as
|
| 1737 |
+
# a whole
|
| 1738 |
+
eqs = []
|
| 1739 |
+
for scc in wcc:
|
| 1740 |
+
eqs += scc
|
| 1741 |
+
funcs = _get_funcs_from_canon(eqs)
|
| 1742 |
+
|
| 1743 |
+
sol = _strong_component_solver(eqs, funcs, t)
|
| 1744 |
+
if sol:
|
| 1745 |
+
return sol
|
| 1746 |
+
|
| 1747 |
+
sol = []
|
| 1748 |
+
|
| 1749 |
+
for scc in wcc:
|
| 1750 |
+
eqs = scc
|
| 1751 |
+
funcs = _get_funcs_from_canon(eqs)
|
| 1752 |
+
|
| 1753 |
+
# Substituting solutions for the dependent
|
| 1754 |
+
# variables solved in previous SCC, if any solved.
|
| 1755 |
+
comp_eqs = [eq.subs({s.lhs: s.rhs for s in sol}) for eq in eqs]
|
| 1756 |
+
scc_sol = _strong_component_solver(comp_eqs, funcs, t)
|
| 1757 |
+
|
| 1758 |
+
if scc_sol is None:
|
| 1759 |
+
raise NotImplementedError(filldedent('''
|
| 1760 |
+
The system of ODEs passed cannot be solved by dsolve_system.
|
| 1761 |
+
'''))
|
| 1762 |
+
|
| 1763 |
+
# scc_sol: List of equations
|
| 1764 |
+
# scc_sol is a solution
|
| 1765 |
+
sol += scc_sol
|
| 1766 |
+
|
| 1767 |
+
return sol
|
| 1768 |
+
|
| 1769 |
+
|
| 1770 |
+
# Returns: List of Equations(a solution)
|
| 1771 |
+
def _component_solver(eqs, funcs, t):
|
| 1772 |
+
components = _component_division(eqs, funcs, t)
|
| 1773 |
+
sol = []
|
| 1774 |
+
|
| 1775 |
+
for wcc in components:
|
| 1776 |
+
|
| 1777 |
+
# wcc_sol: List of Equations
|
| 1778 |
+
sol += _weak_component_solver(wcc, t)
|
| 1779 |
+
|
| 1780 |
+
# sol: List of Equations
|
| 1781 |
+
return sol
|
| 1782 |
+
|
| 1783 |
+
|
| 1784 |
+
def _second_order_to_first_order(eqs, funcs, t, type="auto", A1=None,
|
| 1785 |
+
A0=None, b=None, t_=None):
|
| 1786 |
+
r"""
|
| 1787 |
+
Expects the system to be in second order and in canonical form
|
| 1788 |
+
|
| 1789 |
+
Explanation
|
| 1790 |
+
===========
|
| 1791 |
+
|
| 1792 |
+
Reduces a second order system into a first order one depending on the type of second
|
| 1793 |
+
order system.
|
| 1794 |
+
1. "type0": If this is passed, then the system will be reduced to first order by
|
| 1795 |
+
introducing dummy variables.
|
| 1796 |
+
2. "type1": If this is passed, then a particular substitution will be used to reduce the
|
| 1797 |
+
the system into first order.
|
| 1798 |
+
3. "type2": If this is passed, then the system will be transformed with new dependent
|
| 1799 |
+
variables and independent variables. This transformation is a part of solving
|
| 1800 |
+
the corresponding system of ODEs.
|
| 1801 |
+
|
| 1802 |
+
`A1` and `A0` are the coefficient matrices from the system and it is assumed that the
|
| 1803 |
+
second order system has the form given below:
|
| 1804 |
+
|
| 1805 |
+
.. math::
|
| 1806 |
+
A2 * X'' = A1 * X' + A0 * X + b
|
| 1807 |
+
|
| 1808 |
+
Here, $A2$ is the coefficient matrix for the vector $X''$ and $b$ is the non-homogeneous
|
| 1809 |
+
term.
|
| 1810 |
+
|
| 1811 |
+
Default value for `b` is None but if `A1` and `A0` are passed and `b` is not passed, then the
|
| 1812 |
+
system will be assumed homogeneous.
|
| 1813 |
+
|
| 1814 |
+
"""
|
| 1815 |
+
is_a1 = A1 is None
|
| 1816 |
+
is_a0 = A0 is None
|
| 1817 |
+
|
| 1818 |
+
if (type == "type1" and is_a1) or (type == "type2" and is_a0)\
|
| 1819 |
+
or (type == "auto" and (is_a1 or is_a0)):
|
| 1820 |
+
(A2, A1, A0), b = linear_ode_to_matrix(eqs, funcs, t, 2)
|
| 1821 |
+
|
| 1822 |
+
if not A2.is_Identity:
|
| 1823 |
+
raise ValueError(filldedent('''
|
| 1824 |
+
The system must be in its canonical form.
|
| 1825 |
+
'''))
|
| 1826 |
+
|
| 1827 |
+
if type == "auto":
|
| 1828 |
+
match = _match_second_order_type(A1, A0, t)
|
| 1829 |
+
type = match["type_of_equation"]
|
| 1830 |
+
A1 = match.get("A1", None)
|
| 1831 |
+
A0 = match.get("A0", None)
|
| 1832 |
+
|
| 1833 |
+
sys_order = dict.fromkeys(funcs, 2)
|
| 1834 |
+
|
| 1835 |
+
if type == "type1":
|
| 1836 |
+
if b is None:
|
| 1837 |
+
b = zeros(len(eqs))
|
| 1838 |
+
eqs = _second_order_subs_type1(A1, b, funcs, t)
|
| 1839 |
+
sys_order = dict.fromkeys(funcs, 1)
|
| 1840 |
+
|
| 1841 |
+
if type == "type2":
|
| 1842 |
+
if t_ is None:
|
| 1843 |
+
t_ = Symbol("{}_".format(t))
|
| 1844 |
+
t = t_
|
| 1845 |
+
eqs, funcs = _second_order_subs_type2(A0, funcs, t_)
|
| 1846 |
+
sys_order = dict.fromkeys(funcs, 2)
|
| 1847 |
+
|
| 1848 |
+
return _higher_order_to_first_order(eqs, sys_order, t, funcs=funcs)
|
| 1849 |
+
|
| 1850 |
+
|
| 1851 |
+
def _higher_order_type2_to_sub_systems(J, f_t, funcs, t, max_order, b=None, P=None):
|
| 1852 |
+
|
| 1853 |
+
# Note: To add a test for this ValueError
|
| 1854 |
+
if J is None or f_t is None or not _matrix_is_constant(J, t):
|
| 1855 |
+
raise ValueError(filldedent('''
|
| 1856 |
+
Correctly input for args 'A' and 'f_t' for Linear, Higher Order,
|
| 1857 |
+
Type 2
|
| 1858 |
+
'''))
|
| 1859 |
+
|
| 1860 |
+
if P is None and b is not None and not b.is_zero_matrix:
|
| 1861 |
+
raise ValueError(filldedent('''
|
| 1862 |
+
Provide the keyword 'P' for matrix P in A = P * J * P-1.
|
| 1863 |
+
'''))
|
| 1864 |
+
|
| 1865 |
+
new_funcs = Matrix([Function(Dummy('{}__0'.format(f.func.__name__)))(t) for f in funcs])
|
| 1866 |
+
new_eqs = new_funcs.diff(t, max_order) - f_t * J * new_funcs
|
| 1867 |
+
|
| 1868 |
+
if b is not None and not b.is_zero_matrix:
|
| 1869 |
+
new_eqs -= P.inv() * b
|
| 1870 |
+
|
| 1871 |
+
new_eqs = canonical_odes(new_eqs, new_funcs, t)[0]
|
| 1872 |
+
|
| 1873 |
+
return new_eqs, new_funcs
|
| 1874 |
+
|
| 1875 |
+
|
| 1876 |
+
def _higher_order_to_first_order(eqs, sys_order, t, funcs=None, type="type0", **kwargs):
|
| 1877 |
+
if funcs is None:
|
| 1878 |
+
funcs = sys_order.keys()
|
| 1879 |
+
|
| 1880 |
+
# Standard Cauchy Euler system
|
| 1881 |
+
if type == "type1":
|
| 1882 |
+
t_ = Symbol('{}_'.format(t))
|
| 1883 |
+
new_funcs = [Function(Dummy('{}_'.format(f.func.__name__)))(t_) for f in funcs]
|
| 1884 |
+
max_order = max(sys_order[func] for func in funcs)
|
| 1885 |
+
subs_dict = dict(zip(funcs, new_funcs))
|
| 1886 |
+
subs_dict[t] = exp(t_)
|
| 1887 |
+
|
| 1888 |
+
free_function = Function(Dummy())
|
| 1889 |
+
|
| 1890 |
+
def _get_coeffs_from_subs_expression(expr):
|
| 1891 |
+
if isinstance(expr, Subs):
|
| 1892 |
+
free_symbol = expr.args[1][0]
|
| 1893 |
+
term = expr.args[0]
|
| 1894 |
+
return {ode_order(term, free_symbol): 1}
|
| 1895 |
+
|
| 1896 |
+
if isinstance(expr, Mul):
|
| 1897 |
+
coeff = expr.args[0]
|
| 1898 |
+
order = list(_get_coeffs_from_subs_expression(expr.args[1]).keys())[0]
|
| 1899 |
+
return {order: coeff}
|
| 1900 |
+
|
| 1901 |
+
if isinstance(expr, Add):
|
| 1902 |
+
coeffs = {}
|
| 1903 |
+
for arg in expr.args:
|
| 1904 |
+
|
| 1905 |
+
if isinstance(arg, Mul):
|
| 1906 |
+
coeffs.update(_get_coeffs_from_subs_expression(arg))
|
| 1907 |
+
|
| 1908 |
+
else:
|
| 1909 |
+
order = list(_get_coeffs_from_subs_expression(arg).keys())[0]
|
| 1910 |
+
coeffs[order] = 1
|
| 1911 |
+
|
| 1912 |
+
return coeffs
|
| 1913 |
+
|
| 1914 |
+
for o in range(1, max_order + 1):
|
| 1915 |
+
expr = free_function(log(t_)).diff(t_, o)*t_**o
|
| 1916 |
+
coeff_dict = _get_coeffs_from_subs_expression(expr)
|
| 1917 |
+
coeffs = [coeff_dict[order] if order in coeff_dict else 0 for order in range(o + 1)]
|
| 1918 |
+
expr_to_subs = sum(free_function(t_).diff(t_, i) * c for i, c in
|
| 1919 |
+
enumerate(coeffs)) / t**o
|
| 1920 |
+
subs_dict.update({f.diff(t, o): expr_to_subs.subs(free_function(t_), nf)
|
| 1921 |
+
for f, nf in zip(funcs, new_funcs)})
|
| 1922 |
+
|
| 1923 |
+
new_eqs = [eq.subs(subs_dict) for eq in eqs]
|
| 1924 |
+
new_sys_order = {nf: sys_order[f] for f, nf in zip(funcs, new_funcs)}
|
| 1925 |
+
|
| 1926 |
+
new_eqs = canonical_odes(new_eqs, new_funcs, t_)[0]
|
| 1927 |
+
|
| 1928 |
+
return _higher_order_to_first_order(new_eqs, new_sys_order, t_, funcs=new_funcs)
|
| 1929 |
+
|
| 1930 |
+
# Systems of the form: X(n)(t) = f(t)*A*X + b
|
| 1931 |
+
# where X(n)(t) is the nth derivative of the vector of dependent variables
|
| 1932 |
+
# with respect to the independent variable and A is a constant matrix.
|
| 1933 |
+
if type == "type2":
|
| 1934 |
+
J = kwargs.get('J', None)
|
| 1935 |
+
f_t = kwargs.get('f_t', None)
|
| 1936 |
+
b = kwargs.get('b', None)
|
| 1937 |
+
P = kwargs.get('P', None)
|
| 1938 |
+
max_order = max(sys_order[func] for func in funcs)
|
| 1939 |
+
|
| 1940 |
+
return _higher_order_type2_to_sub_systems(J, f_t, funcs, t, max_order, P=P, b=b)
|
| 1941 |
+
|
| 1942 |
+
# Note: To be changed to this after doit option is disabled for default cases
|
| 1943 |
+
# new_sysorder = _get_func_order(new_eqs, new_funcs)
|
| 1944 |
+
#
|
| 1945 |
+
# return _higher_order_to_first_order(new_eqs, new_sysorder, t, funcs=new_funcs)
|
| 1946 |
+
|
| 1947 |
+
new_funcs = []
|
| 1948 |
+
|
| 1949 |
+
for prev_func in funcs:
|
| 1950 |
+
func_name = prev_func.func.__name__
|
| 1951 |
+
func = Function(Dummy('{}_0'.format(func_name)))(t)
|
| 1952 |
+
new_funcs.append(func)
|
| 1953 |
+
subs_dict = {prev_func: func}
|
| 1954 |
+
new_eqs = []
|
| 1955 |
+
|
| 1956 |
+
for i in range(1, sys_order[prev_func]):
|
| 1957 |
+
new_func = Function(Dummy('{}_{}'.format(func_name, i)))(t)
|
| 1958 |
+
subs_dict[prev_func.diff(t, i)] = new_func
|
| 1959 |
+
new_funcs.append(new_func)
|
| 1960 |
+
|
| 1961 |
+
prev_f = subs_dict[prev_func.diff(t, i-1)]
|
| 1962 |
+
new_eq = Eq(prev_f.diff(t), new_func)
|
| 1963 |
+
new_eqs.append(new_eq)
|
| 1964 |
+
|
| 1965 |
+
eqs = [eq.subs(subs_dict) for eq in eqs] + new_eqs
|
| 1966 |
+
|
| 1967 |
+
return eqs, new_funcs
|
| 1968 |
+
|
| 1969 |
+
|
| 1970 |
+
def dsolve_system(eqs, funcs=None, t=None, ics=None, doit=False, simplify=True):
|
| 1971 |
+
r"""
|
| 1972 |
+
Solves any(supported) system of Ordinary Differential Equations
|
| 1973 |
+
|
| 1974 |
+
Explanation
|
| 1975 |
+
===========
|
| 1976 |
+
|
| 1977 |
+
This function takes a system of ODEs as an input, determines if the
|
| 1978 |
+
it is solvable by this function, and returns the solution if found any.
|
| 1979 |
+
|
| 1980 |
+
This function can handle:
|
| 1981 |
+
1. Linear, First Order, Constant coefficient homogeneous system of ODEs
|
| 1982 |
+
2. Linear, First Order, Constant coefficient non-homogeneous system of ODEs
|
| 1983 |
+
3. Linear, First Order, non-constant coefficient homogeneous system of ODEs
|
| 1984 |
+
4. Linear, First Order, non-constant coefficient non-homogeneous system of ODEs
|
| 1985 |
+
5. Any implicit system which can be divided into system of ODEs which is of the above 4 forms
|
| 1986 |
+
6. Any higher order linear system of ODEs that can be reduced to one of the 5 forms of systems described above.
|
| 1987 |
+
|
| 1988 |
+
The types of systems described above are not limited by the number of equations, i.e. this
|
| 1989 |
+
function can solve the above types irrespective of the number of equations in the system passed.
|
| 1990 |
+
But, the bigger the system, the more time it will take to solve the system.
|
| 1991 |
+
|
| 1992 |
+
This function returns a list of solutions. Each solution is a list of equations where LHS is
|
| 1993 |
+
the dependent variable and RHS is an expression in terms of the independent variable.
|
| 1994 |
+
|
| 1995 |
+
Among the non constant coefficient types, not all the systems are solvable by this function. Only
|
| 1996 |
+
those which have either a coefficient matrix with a commutative antiderivative or those systems which
|
| 1997 |
+
may be divided further so that the divided systems may have coefficient matrix with commutative antiderivative.
|
| 1998 |
+
|
| 1999 |
+
Parameters
|
| 2000 |
+
==========
|
| 2001 |
+
|
| 2002 |
+
eqs : List
|
| 2003 |
+
system of ODEs to be solved
|
| 2004 |
+
funcs : List or None
|
| 2005 |
+
List of dependent variables that make up the system of ODEs
|
| 2006 |
+
t : Symbol or None
|
| 2007 |
+
Independent variable in the system of ODEs
|
| 2008 |
+
ics : Dict or None
|
| 2009 |
+
Set of initial boundary/conditions for the system of ODEs
|
| 2010 |
+
doit : Boolean
|
| 2011 |
+
Evaluate the solutions if True. Default value is True. Can be
|
| 2012 |
+
set to false if the integral evaluation takes too much time and/or
|
| 2013 |
+
is not required.
|
| 2014 |
+
simplify: Boolean
|
| 2015 |
+
Simplify the solutions for the systems. Default value is True.
|
| 2016 |
+
Can be set to false if simplification takes too much time and/or
|
| 2017 |
+
is not required.
|
| 2018 |
+
|
| 2019 |
+
Examples
|
| 2020 |
+
========
|
| 2021 |
+
|
| 2022 |
+
>>> from sympy import symbols, Eq, Function
|
| 2023 |
+
>>> from sympy.solvers.ode.systems import dsolve_system
|
| 2024 |
+
>>> f, g = symbols("f g", cls=Function)
|
| 2025 |
+
>>> x = symbols("x")
|
| 2026 |
+
|
| 2027 |
+
>>> eqs = [Eq(f(x).diff(x), g(x)), Eq(g(x).diff(x), f(x))]
|
| 2028 |
+
>>> dsolve_system(eqs)
|
| 2029 |
+
[[Eq(f(x), -C1*exp(-x) + C2*exp(x)), Eq(g(x), C1*exp(-x) + C2*exp(x))]]
|
| 2030 |
+
|
| 2031 |
+
You can also pass the initial conditions for the system of ODEs:
|
| 2032 |
+
|
| 2033 |
+
>>> dsolve_system(eqs, ics={f(0): 1, g(0): 0})
|
| 2034 |
+
[[Eq(f(x), exp(x)/2 + exp(-x)/2), Eq(g(x), exp(x)/2 - exp(-x)/2)]]
|
| 2035 |
+
|
| 2036 |
+
Optionally, you can pass the dependent variables and the independent
|
| 2037 |
+
variable for which the system is to be solved:
|
| 2038 |
+
|
| 2039 |
+
>>> funcs = [f(x), g(x)]
|
| 2040 |
+
>>> dsolve_system(eqs, funcs=funcs, t=x)
|
| 2041 |
+
[[Eq(f(x), -C1*exp(-x) + C2*exp(x)), Eq(g(x), C1*exp(-x) + C2*exp(x))]]
|
| 2042 |
+
|
| 2043 |
+
Lets look at an implicit system of ODEs:
|
| 2044 |
+
|
| 2045 |
+
>>> eqs = [Eq(f(x).diff(x)**2, g(x)**2), Eq(g(x).diff(x), g(x))]
|
| 2046 |
+
>>> dsolve_system(eqs)
|
| 2047 |
+
[[Eq(f(x), C1 - C2*exp(x)), Eq(g(x), C2*exp(x))], [Eq(f(x), C1 + C2*exp(x)), Eq(g(x), C2*exp(x))]]
|
| 2048 |
+
|
| 2049 |
+
Returns
|
| 2050 |
+
=======
|
| 2051 |
+
|
| 2052 |
+
List of List of Equations
|
| 2053 |
+
|
| 2054 |
+
Raises
|
| 2055 |
+
======
|
| 2056 |
+
|
| 2057 |
+
NotImplementedError
|
| 2058 |
+
When the system of ODEs is not solvable by this function.
|
| 2059 |
+
ValueError
|
| 2060 |
+
When the parameters passed are not in the required form.
|
| 2061 |
+
|
| 2062 |
+
"""
|
| 2063 |
+
from sympy.solvers.ode.ode import solve_ics, _extract_funcs, constant_renumber
|
| 2064 |
+
|
| 2065 |
+
if not iterable(eqs):
|
| 2066 |
+
raise ValueError(filldedent('''
|
| 2067 |
+
List of equations should be passed. The input is not valid.
|
| 2068 |
+
'''))
|
| 2069 |
+
|
| 2070 |
+
eqs = _preprocess_eqs(eqs)
|
| 2071 |
+
|
| 2072 |
+
if funcs is not None and not isinstance(funcs, list):
|
| 2073 |
+
raise ValueError(filldedent('''
|
| 2074 |
+
Input to the funcs should be a list of functions.
|
| 2075 |
+
'''))
|
| 2076 |
+
|
| 2077 |
+
if funcs is None:
|
| 2078 |
+
funcs = _extract_funcs(eqs)
|
| 2079 |
+
|
| 2080 |
+
if any(len(func.args) != 1 for func in funcs):
|
| 2081 |
+
raise ValueError(filldedent('''
|
| 2082 |
+
dsolve_system can solve a system of ODEs with only one independent
|
| 2083 |
+
variable.
|
| 2084 |
+
'''))
|
| 2085 |
+
|
| 2086 |
+
if len(eqs) != len(funcs):
|
| 2087 |
+
raise ValueError(filldedent('''
|
| 2088 |
+
Number of equations and number of functions do not match
|
| 2089 |
+
'''))
|
| 2090 |
+
|
| 2091 |
+
if t is not None and not isinstance(t, Symbol):
|
| 2092 |
+
raise ValueError(filldedent('''
|
| 2093 |
+
The independent variable must be of type Symbol
|
| 2094 |
+
'''))
|
| 2095 |
+
|
| 2096 |
+
if t is None:
|
| 2097 |
+
t = list(list(eqs[0].atoms(Derivative))[0].atoms(Symbol))[0]
|
| 2098 |
+
|
| 2099 |
+
sols = []
|
| 2100 |
+
canon_eqs = canonical_odes(eqs, funcs, t)
|
| 2101 |
+
|
| 2102 |
+
for canon_eq in canon_eqs:
|
| 2103 |
+
try:
|
| 2104 |
+
sol = _strong_component_solver(canon_eq, funcs, t)
|
| 2105 |
+
except NotImplementedError:
|
| 2106 |
+
sol = None
|
| 2107 |
+
|
| 2108 |
+
if sol is None:
|
| 2109 |
+
sol = _component_solver(canon_eq, funcs, t)
|
| 2110 |
+
|
| 2111 |
+
sols.append(sol)
|
| 2112 |
+
|
| 2113 |
+
if sols:
|
| 2114 |
+
final_sols = []
|
| 2115 |
+
variables = Tuple(*eqs).free_symbols
|
| 2116 |
+
|
| 2117 |
+
for sol in sols:
|
| 2118 |
+
|
| 2119 |
+
sol = _select_equations(sol, funcs)
|
| 2120 |
+
sol = constant_renumber(sol, variables=variables)
|
| 2121 |
+
|
| 2122 |
+
if ics:
|
| 2123 |
+
constants = Tuple(*sol).free_symbols - variables
|
| 2124 |
+
solved_constants = solve_ics(sol, funcs, constants, ics)
|
| 2125 |
+
sol = [s.subs(solved_constants) for s in sol]
|
| 2126 |
+
|
| 2127 |
+
if simplify:
|
| 2128 |
+
constants = Tuple(*sol).free_symbols - variables
|
| 2129 |
+
sol = simpsol(sol, [t], constants, doit=doit)
|
| 2130 |
+
|
| 2131 |
+
final_sols.append(sol)
|
| 2132 |
+
|
| 2133 |
+
sols = final_sols
|
| 2134 |
+
|
| 2135 |
+
return sols
|
pllava/lib/python3.10/site-packages/sympy/solvers/ode/tests/__init__.py
ADDED
|
File without changes
|
pllava/lib/python3.10/site-packages/sympy/solvers/ode/tests/__pycache__/test_lie_group.cpython-310.pyc
ADDED
|
Binary file (5.93 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/solvers/ode/tests/__pycache__/test_ode.cpython-310.pyc
ADDED
|
Binary file (37.7 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/solvers/ode/tests/__pycache__/test_single.cpython-310.pyc
ADDED
|
Binary file (81.7 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/solvers/ode/tests/__pycache__/test_subscheck.cpython-310.pyc
ADDED
|
Binary file (11.8 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/solvers/pde.py
ADDED
|
@@ -0,0 +1,971 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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]
|
pllava/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)
|
pllava/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
|
pllava/lib/python3.10/site-packages/sympy/solvers/solvers.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
pllava/lib/python3.10/site-packages/sympy/solvers/solveset.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
pllava/lib/python3.10/site-packages/sympy/solvers/tests/__init__.py
ADDED
|
File without changes
|
pllava/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/test_constantsimp.cpython-310.pyc
ADDED
|
Binary file (7.43 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/test_decompogen.cpython-310.pyc
ADDED
|
Binary file (3.53 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/test_inequalities.cpython-310.pyc
ADDED
|
Binary file (19.6 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/test_numeric.cpython-310.pyc
ADDED
|
Binary file (5.73 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/test_pde.cpython-310.pyc
ADDED
|
Binary file (9.7 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/test_polysys.cpython-310.pyc
ADDED
|
Binary file (7.49 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/test_recurr.cpython-310.pyc
ADDED
|
Binary file (13.2 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/test_simplex.cpython-310.pyc
ADDED
|
Binary file (10.1 kB). View file
|
|
|
pllava/lib/python3.10/site-packages/sympy/solvers/tests/test_constantsimp.py
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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)
|