applied-ai-018 commited on
Commit
b38c997
·
verified ·
1 Parent(s): e3fac8c

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py33_np18.pkl_01.npy +3 -0
  3. env-llmeval/lib/python3.10/site-packages/scipy.libs/libgfortran-040039e1.so.5.0.0 +3 -0
  4. env-llmeval/lib/python3.10/site-packages/sympy/codegen/__pycache__/__init__.cpython-310.pyc +0 -0
  5. env-llmeval/lib/python3.10/site-packages/sympy/codegen/__pycache__/algorithms.cpython-310.pyc +0 -0
  6. env-llmeval/lib/python3.10/site-packages/sympy/codegen/__pycache__/approximations.cpython-310.pyc +0 -0
  7. env-llmeval/lib/python3.10/site-packages/sympy/codegen/__pycache__/cnodes.cpython-310.pyc +0 -0
  8. env-llmeval/lib/python3.10/site-packages/sympy/codegen/__pycache__/cutils.cpython-310.pyc +0 -0
  9. env-llmeval/lib/python3.10/site-packages/sympy/codegen/__pycache__/fnodes.cpython-310.pyc +0 -0
  10. env-llmeval/lib/python3.10/site-packages/sympy/codegen/__pycache__/futils.cpython-310.pyc +0 -0
  11. env-llmeval/lib/python3.10/site-packages/sympy/codegen/__pycache__/pynodes.cpython-310.pyc +0 -0
  12. env-llmeval/lib/python3.10/site-packages/sympy/codegen/__pycache__/rewriting.cpython-310.pyc +0 -0
  13. env-llmeval/lib/python3.10/site-packages/sympy/solvers/__init__.py +71 -0
  14. env-llmeval/lib/python3.10/site-packages/sympy/solvers/__pycache__/bivariate.cpython-310.pyc +0 -0
  15. env-llmeval/lib/python3.10/site-packages/sympy/solvers/__pycache__/deutils.cpython-310.pyc +0 -0
  16. env-llmeval/lib/python3.10/site-packages/sympy/solvers/__pycache__/solvers.cpython-310.pyc +0 -0
  17. env-llmeval/lib/python3.10/site-packages/sympy/solvers/benchmarks/__init__.py +0 -0
  18. env-llmeval/lib/python3.10/site-packages/sympy/solvers/bivariate.py +509 -0
  19. env-llmeval/lib/python3.10/site-packages/sympy/solvers/decompogen.py +126 -0
  20. env-llmeval/lib/python3.10/site-packages/sympy/solvers/diophantine/__init__.py +5 -0
  21. env-llmeval/lib/python3.10/site-packages/sympy/solvers/diophantine/__pycache__/__init__.cpython-310.pyc +0 -0
  22. env-llmeval/lib/python3.10/site-packages/sympy/solvers/diophantine/__pycache__/diophantine.cpython-310.pyc +0 -0
  23. env-llmeval/lib/python3.10/site-packages/sympy/solvers/diophantine/diophantine.py +0 -0
  24. env-llmeval/lib/python3.10/site-packages/sympy/solvers/diophantine/tests/__init__.py +0 -0
  25. env-llmeval/lib/python3.10/site-packages/sympy/solvers/diophantine/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  26. env-llmeval/lib/python3.10/site-packages/sympy/solvers/diophantine/tests/__pycache__/test_diophantine.cpython-310.pyc +0 -0
  27. env-llmeval/lib/python3.10/site-packages/sympy/solvers/diophantine/tests/test_diophantine.py +1037 -0
  28. env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/__init__.py +16 -0
  29. env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/__init__.cpython-310.pyc +0 -0
  30. env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/hypergeometric.cpython-310.pyc +0 -0
  31. env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/lie_group.cpython-310.pyc +0 -0
  32. env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/nonhomogeneous.cpython-310.pyc +0 -0
  33. env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/ode.cpython-310.pyc +0 -0
  34. env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/riccati.cpython-310.pyc +0 -0
  35. env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/single.cpython-310.pyc +0 -0
  36. env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/subscheck.cpython-310.pyc +0 -0
  37. env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/systems.cpython-310.pyc +0 -0
  38. env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/hypergeometric.py +272 -0
  39. env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/lie_group.py +1101 -0
  40. env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/nonhomogeneous.py +499 -0
  41. env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/ode.py +0 -0
  42. env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/riccati.py +893 -0
  43. env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/single.py +0 -0
  44. env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/subscheck.py +392 -0
  45. env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/systems.py +2135 -0
  46. env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/tests/__init__.py +0 -0
  47. env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  48. env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/tests/__pycache__/test_lie_group.cpython-310.pyc +0 -0
  49. env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/tests/__pycache__/test_ode.cpython-310.pyc +0 -0
  50. env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/tests/__pycache__/test_riccati.cpython-310.pyc +0 -0
.gitattributes CHANGED
@@ -127,3 +127,4 @@ env-llmeval/lib/python3.10/site-packages/lxml/objectify.cpython-310-x86_64-linux
127
  env-llmeval/lib/python3.10/site-packages/triton/third_party/cuda/bin/ptxas filter=lfs diff=lfs merge=lfs -text
128
  env-llmeval/lib/python3.10/site-packages/lxml/etree.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
129
  env-llmeval/lib/python3.10/site-packages/scipy.libs/libopenblasp-r0-24bff013.3.26.dev.so filter=lfs diff=lfs merge=lfs -text
 
 
127
  env-llmeval/lib/python3.10/site-packages/triton/third_party/cuda/bin/ptxas filter=lfs diff=lfs merge=lfs -text
128
  env-llmeval/lib/python3.10/site-packages/lxml/etree.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
129
  env-llmeval/lib/python3.10/site-packages/scipy.libs/libopenblasp-r0-24bff013.3.26.dev.so filter=lfs diff=lfs merge=lfs -text
130
+ env-llmeval/lib/python3.10/site-packages/scipy.libs/libgfortran-040039e1.so.5.0.0 filter=lfs diff=lfs merge=lfs -text
env-llmeval/lib/python3.10/site-packages/joblib/test/data/joblib_0.9.2_pickle_py33_np18.pkl_01.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0efbd7d9ce7eec3a6e0a0db41e795e0396cca3d6b037dad6c61b464843d28809
3
+ size 120
env-llmeval/lib/python3.10/site-packages/scipy.libs/libgfortran-040039e1.so.5.0.0 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:14afb3129b1a8b50bc40a3b0820c7f1152ea9bc10121aab152943f7057472886
3
+ size 2686065
env-llmeval/lib/python3.10/site-packages/sympy/codegen/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.09 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/codegen/__pycache__/algorithms.cpython-310.pyc ADDED
Binary file (5.42 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/codegen/__pycache__/approximations.cpython-310.pyc ADDED
Binary file (6.33 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/codegen/__pycache__/cnodes.cpython-310.pyc ADDED
Binary file (4.31 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/codegen/__pycache__/cutils.cpython-310.pyc ADDED
Binary file (717 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/codegen/__pycache__/fnodes.cpython-310.pyc ADDED
Binary file (21.2 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/codegen/__pycache__/futils.cpython-310.pyc ADDED
Binary file (2.02 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/codegen/__pycache__/pynodes.cpython-310.pyc ADDED
Binary file (669 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/codegen/__pycache__/rewriting.cpython-310.pyc ADDED
Binary file (13.5 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/solvers/__init__.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """A module for solving all kinds of equations.
2
+
3
+ Examples
4
+ ========
5
+
6
+ >>> from sympy.solvers import solve
7
+ >>> from sympy.abc import x
8
+ >>> solve(x**5+5*x**4+10*x**3+10*x**2+5*x+1,x)
9
+ [-1]
10
+ """
11
+ from sympy.core.assumptions import check_assumptions, failing_assumptions
12
+
13
+ from .solvers import solve, solve_linear_system, solve_linear_system_LU, \
14
+ solve_undetermined_coeffs, nsolve, solve_linear, checksol, \
15
+ det_quick, inv_quick
16
+
17
+ from .diophantine import diophantine
18
+
19
+ from .recurr import rsolve, rsolve_poly, rsolve_ratio, rsolve_hyper
20
+
21
+ from .ode import checkodesol, classify_ode, dsolve, \
22
+ homogeneous_order
23
+
24
+ from .polysys import solve_poly_system, solve_triangulated
25
+
26
+ from .pde import pde_separate, pde_separate_add, pde_separate_mul, \
27
+ pdsolve, classify_pde, checkpdesol
28
+
29
+ from .deutils import ode_order
30
+
31
+ from .inequalities import reduce_inequalities, reduce_abs_inequality, \
32
+ reduce_abs_inequalities, solve_poly_inequality, solve_rational_inequalities, solve_univariate_inequality
33
+
34
+ from .decompogen import decompogen
35
+
36
+ from .solveset import solveset, linsolve, linear_eq_to_matrix, nonlinsolve, substitution
37
+
38
+ # This is here instead of sympy/sets/__init__.py to avoid circular import issues
39
+ from ..core.singleton import S
40
+ Complexes = S.Complexes
41
+
42
+ __all__ = [
43
+ 'solve', 'solve_linear_system', 'solve_linear_system_LU',
44
+ 'solve_undetermined_coeffs', 'nsolve', 'solve_linear', 'checksol',
45
+ 'det_quick', 'inv_quick', 'check_assumptions', 'failing_assumptions',
46
+
47
+ 'diophantine',
48
+
49
+ 'rsolve', 'rsolve_poly', 'rsolve_ratio', 'rsolve_hyper',
50
+
51
+ 'checkodesol', 'classify_ode', 'dsolve', 'homogeneous_order',
52
+
53
+ 'solve_poly_system', 'solve_triangulated',
54
+
55
+ 'pde_separate', 'pde_separate_add', 'pde_separate_mul', 'pdsolve',
56
+ 'classify_pde', 'checkpdesol',
57
+
58
+ 'ode_order',
59
+
60
+ 'reduce_inequalities', 'reduce_abs_inequality', 'reduce_abs_inequalities',
61
+ 'solve_poly_inequality', 'solve_rational_inequalities',
62
+ 'solve_univariate_inequality',
63
+
64
+ 'decompogen',
65
+
66
+ 'solveset', 'linsolve', 'linear_eq_to_matrix', 'nonlinsolve',
67
+ 'substitution',
68
+
69
+ # This is here instead of sympy/sets/__init__.py to avoid circular import issues
70
+ 'Complexes',
71
+ ]
env-llmeval/lib/python3.10/site-packages/sympy/solvers/__pycache__/bivariate.cpython-310.pyc ADDED
Binary file (13.8 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/solvers/__pycache__/deutils.cpython-310.pyc ADDED
Binary file (8.05 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/solvers/__pycache__/solvers.cpython-310.pyc ADDED
Binary file (98.6 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/solvers/benchmarks/__init__.py ADDED
File without changes
env-llmeval/lib/python3.10/site-packages/sympy/solvers/bivariate.py ADDED
@@ -0,0 +1,509 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sympy.core.add import Add
2
+ from sympy.core.exprtools import factor_terms
3
+ from sympy.core.function import expand_log, _mexpand
4
+ from sympy.core.power import Pow
5
+ from sympy.core.singleton import S
6
+ from sympy.core.sorting import ordered
7
+ from sympy.core.symbol import Dummy
8
+ from sympy.functions.elementary.exponential import (LambertW, exp, log)
9
+ from sympy.functions.elementary.miscellaneous import root
10
+ from sympy.polys.polyroots import roots
11
+ from sympy.polys.polytools import Poly, factor
12
+ from sympy.simplify.simplify import separatevars
13
+ from sympy.simplify.radsimp import collect
14
+ from sympy.simplify.simplify import powsimp
15
+ from sympy.solvers.solvers import solve, _invert
16
+ from sympy.utilities.iterables import uniq
17
+
18
+
19
+ def _filtered_gens(poly, symbol):
20
+ """process the generators of ``poly``, returning the set of generators that
21
+ have ``symbol``. If there are two generators that are inverses of each other,
22
+ prefer the one that has no denominator.
23
+
24
+ Examples
25
+ ========
26
+
27
+ >>> from sympy.solvers.bivariate import _filtered_gens
28
+ >>> from sympy import Poly, exp
29
+ >>> from sympy.abc import x
30
+ >>> _filtered_gens(Poly(x + 1/x + exp(x)), x)
31
+ {x, exp(x)}
32
+
33
+ """
34
+ # TODO it would be good to pick the smallest divisible power
35
+ # instead of the base for something like x**4 + x**2 -->
36
+ # return x**2 not x
37
+ gens = {g for g in poly.gens if symbol in g.free_symbols}
38
+ for g in list(gens):
39
+ ag = 1/g
40
+ if g in gens and ag in gens:
41
+ if ag.as_numer_denom()[1] is not S.One:
42
+ g = ag
43
+ gens.remove(g)
44
+ return gens
45
+
46
+
47
+ def _mostfunc(lhs, func, X=None):
48
+ """Returns the term in lhs which contains the most of the
49
+ func-type things e.g. log(log(x)) wins over log(x) if both terms appear.
50
+
51
+ ``func`` can be a function (exp, log, etc...) or any other SymPy object,
52
+ like Pow.
53
+
54
+ If ``X`` is not ``None``, then the function returns the term composed with the
55
+ most ``func`` having the specified variable.
56
+
57
+ Examples
58
+ ========
59
+
60
+ >>> from sympy.solvers.bivariate import _mostfunc
61
+ >>> from sympy import exp
62
+ >>> from sympy.abc import x, y
63
+ >>> _mostfunc(exp(x) + exp(exp(x) + 2), exp)
64
+ exp(exp(x) + 2)
65
+ >>> _mostfunc(exp(x) + exp(exp(y) + 2), exp)
66
+ exp(exp(y) + 2)
67
+ >>> _mostfunc(exp(x) + exp(exp(y) + 2), exp, x)
68
+ exp(x)
69
+ >>> _mostfunc(x, exp, x) is None
70
+ True
71
+ >>> _mostfunc(exp(x) + exp(x*y), exp, x)
72
+ exp(x)
73
+ """
74
+ fterms = [tmp for tmp in lhs.atoms(func) if (not X or
75
+ X.is_Symbol and X in tmp.free_symbols or
76
+ not X.is_Symbol and tmp.has(X))]
77
+ if len(fterms) == 1:
78
+ return fterms[0]
79
+ elif fterms:
80
+ return max(list(ordered(fterms)), key=lambda x: x.count(func))
81
+ return None
82
+
83
+
84
+ def _linab(arg, symbol):
85
+ """Return ``a, b, X`` assuming ``arg`` can be written as ``a*X + b``
86
+ where ``X`` is a symbol-dependent factor and ``a`` and ``b`` are
87
+ independent of ``symbol``.
88
+
89
+ Examples
90
+ ========
91
+
92
+ >>> from sympy.solvers.bivariate import _linab
93
+ >>> from sympy.abc import x, y
94
+ >>> from sympy import exp, S
95
+ >>> _linab(S(2), x)
96
+ (2, 0, 1)
97
+ >>> _linab(2*x, x)
98
+ (2, 0, x)
99
+ >>> _linab(y + y*x + 2*x, x)
100
+ (y + 2, y, x)
101
+ >>> _linab(3 + 2*exp(x), x)
102
+ (2, 3, exp(x))
103
+ """
104
+ arg = factor_terms(arg.expand())
105
+ ind, dep = arg.as_independent(symbol)
106
+ if arg.is_Mul and dep.is_Add:
107
+ a, b, x = _linab(dep, symbol)
108
+ return ind*a, ind*b, x
109
+ if not arg.is_Add:
110
+ b = 0
111
+ a, x = ind, dep
112
+ else:
113
+ b = ind
114
+ a, x = separatevars(dep).as_independent(symbol, as_Add=False)
115
+ if x.could_extract_minus_sign():
116
+ a = -a
117
+ x = -x
118
+ return a, b, x
119
+
120
+
121
+ def _lambert(eq, x):
122
+ """
123
+ Given an expression assumed to be in the form
124
+ ``F(X, a..f) = a*log(b*X + c) + d*X + f = 0``
125
+ where X = g(x) and x = g^-1(X), return the Lambert solution,
126
+ ``x = g^-1(-c/b + (a/d)*W(d/(a*b)*exp(c*d/a/b)*exp(-f/a)))``.
127
+ """
128
+ eq = _mexpand(expand_log(eq))
129
+ mainlog = _mostfunc(eq, log, x)
130
+ if not mainlog:
131
+ return [] # violated assumptions
132
+ other = eq.subs(mainlog, 0)
133
+ if isinstance(-other, log):
134
+ eq = (eq - other).subs(mainlog, mainlog.args[0])
135
+ mainlog = mainlog.args[0]
136
+ if not isinstance(mainlog, log):
137
+ return [] # violated assumptions
138
+ other = -(-other).args[0]
139
+ eq += other
140
+ if x not in other.free_symbols:
141
+ return [] # violated assumptions
142
+ d, f, X2 = _linab(other, x)
143
+ logterm = collect(eq - other, mainlog)
144
+ a = logterm.as_coefficient(mainlog)
145
+ if a is None or x in a.free_symbols:
146
+ return [] # violated assumptions
147
+ logarg = mainlog.args[0]
148
+ b, c, X1 = _linab(logarg, x)
149
+ if X1 != X2:
150
+ return [] # violated assumptions
151
+
152
+ # invert the generator X1 so we have x(u)
153
+ u = Dummy('rhs')
154
+ xusolns = solve(X1 - u, x)
155
+
156
+ # There are infinitely many branches for LambertW
157
+ # but only branches for k = -1 and 0 might be real. The k = 0
158
+ # branch is real and the k = -1 branch is real if the LambertW argumen
159
+ # in in range [-1/e, 0]. Since `solve` does not return infinite
160
+ # solutions we will only include the -1 branch if it tests as real.
161
+ # Otherwise, inclusion of any LambertW in the solution indicates to
162
+ # the user that there are imaginary solutions corresponding to
163
+ # different k values.
164
+ lambert_real_branches = [-1, 0]
165
+ sol = []
166
+
167
+ # solution of the given Lambert equation is like
168
+ # sol = -c/b + (a/d)*LambertW(arg, k),
169
+ # where arg = d/(a*b)*exp((c*d-b*f)/a/b) and k in lambert_real_branches.
170
+ # Instead of considering the single arg, `d/(a*b)*exp((c*d-b*f)/a/b)`,
171
+ # the individual `p` roots obtained when writing `exp((c*d-b*f)/a/b)`
172
+ # as `exp(A/p) = exp(A)**(1/p)`, where `p` is an Integer, are used.
173
+
174
+ # calculating args for LambertW
175
+ num, den = ((c*d-b*f)/a/b).as_numer_denom()
176
+ p, den = den.as_coeff_Mul()
177
+ e = exp(num/den)
178
+ t = Dummy('t')
179
+ args = [d/(a*b)*t for t in roots(t**p - e, t).keys()]
180
+
181
+ # calculating solutions from args
182
+ for arg in args:
183
+ for k in lambert_real_branches:
184
+ w = LambertW(arg, k)
185
+ if k and not w.is_real:
186
+ continue
187
+ rhs = -c/b + (a/d)*w
188
+
189
+ sol.extend(xu.subs(u, rhs) for xu in xusolns)
190
+ return sol
191
+
192
+
193
+ def _solve_lambert(f, symbol, gens):
194
+ """Return solution to ``f`` if it is a Lambert-type expression
195
+ else raise NotImplementedError.
196
+
197
+ For ``f(X, a..f) = a*log(b*X + c) + d*X - f = 0`` the solution
198
+ for ``X`` is ``X = -c/b + (a/d)*W(d/(a*b)*exp(c*d/a/b)*exp(f/a))``.
199
+ There are a variety of forms for `f(X, a..f)` as enumerated below:
200
+
201
+ 1a1)
202
+ if B**B = R for R not in [0, 1] (since those cases would already
203
+ be solved before getting here) then log of both sides gives
204
+ log(B) + log(log(B)) = log(log(R)) and
205
+ X = log(B), a = 1, b = 1, c = 0, d = 1, f = log(log(R))
206
+ 1a2)
207
+ if B*(b*log(B) + c)**a = R then log of both sides gives
208
+ log(B) + a*log(b*log(B) + c) = log(R) and
209
+ X = log(B), d=1, f=log(R)
210
+ 1b)
211
+ if a*log(b*B + c) + d*B = R and
212
+ X = B, f = R
213
+ 2a)
214
+ if (b*B + c)*exp(d*B + g) = R then log of both sides gives
215
+ log(b*B + c) + d*B + g = log(R) and
216
+ X = B, a = 1, f = log(R) - g
217
+ 2b)
218
+ if g*exp(d*B + h) - b*B = c then the log form is
219
+ log(g) + d*B + h - log(b*B + c) = 0 and
220
+ X = B, a = -1, f = -h - log(g)
221
+ 3)
222
+ if d*p**(a*B + g) - b*B = c then the log form is
223
+ log(d) + (a*B + g)*log(p) - log(b*B + c) = 0 and
224
+ X = B, a = -1, d = a*log(p), f = -log(d) - g*log(p)
225
+ """
226
+
227
+ def _solve_even_degree_expr(expr, t, symbol):
228
+ """Return the unique solutions of equations derived from
229
+ ``expr`` by replacing ``t`` with ``+/- symbol``.
230
+
231
+ Parameters
232
+ ==========
233
+
234
+ expr : Expr
235
+ The expression which includes a dummy variable t to be
236
+ replaced with +symbol and -symbol.
237
+
238
+ symbol : Symbol
239
+ The symbol for which a solution is being sought.
240
+
241
+ Returns
242
+ =======
243
+
244
+ List of unique solution of the two equations generated by
245
+ replacing ``t`` with positive and negative ``symbol``.
246
+
247
+ Notes
248
+ =====
249
+
250
+ If ``expr = 2*log(t) + x/2` then solutions for
251
+ ``2*log(x) + x/2 = 0`` and ``2*log(-x) + x/2 = 0`` are
252
+ returned by this function. Though this may seem
253
+ counter-intuitive, one must note that the ``expr`` being
254
+ solved here has been derived from a different expression. For
255
+ an expression like ``eq = x**2*g(x) = 1``, if we take the
256
+ log of both sides we obtain ``log(x**2) + log(g(x)) = 0``. If
257
+ x is positive then this simplifies to
258
+ ``2*log(x) + log(g(x)) = 0``; the Lambert-solving routines will
259
+ return solutions for this, but we must also consider the
260
+ solutions for ``2*log(-x) + log(g(x))`` since those must also
261
+ be a solution of ``eq`` which has the same value when the ``x``
262
+ in ``x**2`` is negated. If `g(x)` does not have even powers of
263
+ symbol then we do not want to replace the ``x`` there with
264
+ ``-x``. So the role of the ``t`` in the expression received by
265
+ this function is to mark where ``+/-x`` should be inserted
266
+ before obtaining the Lambert solutions.
267
+
268
+ """
269
+ nlhs, plhs = [
270
+ expr.xreplace({t: sgn*symbol}) for sgn in (-1, 1)]
271
+ sols = _solve_lambert(nlhs, symbol, gens)
272
+ if plhs != nlhs:
273
+ sols.extend(_solve_lambert(plhs, symbol, gens))
274
+ # uniq is needed for a case like
275
+ # 2*log(t) - log(-z**2) + log(z + log(x) + log(z))
276
+ # where substituting t with +/-x gives all the same solution;
277
+ # uniq, rather than list(set()), is used to maintain canonical
278
+ # order
279
+ return list(uniq(sols))
280
+
281
+ nrhs, lhs = f.as_independent(symbol, as_Add=True)
282
+ rhs = -nrhs
283
+
284
+ lamcheck = [tmp for tmp in gens
285
+ if (tmp.func in [exp, log] or
286
+ (tmp.is_Pow and symbol in tmp.exp.free_symbols))]
287
+ if not lamcheck:
288
+ raise NotImplementedError()
289
+
290
+ if lhs.is_Add or lhs.is_Mul:
291
+ # replacing all even_degrees of symbol with dummy variable t
292
+ # since these will need special handling; non-Add/Mul do not
293
+ # need this handling
294
+ t = Dummy('t', **symbol.assumptions0)
295
+ lhs = lhs.replace(
296
+ lambda i: # find symbol**even
297
+ i.is_Pow and i.base == symbol and i.exp.is_even,
298
+ lambda i: # replace t**even
299
+ t**i.exp)
300
+
301
+ if lhs.is_Add and lhs.has(t):
302
+ t_indep = lhs.subs(t, 0)
303
+ t_term = lhs - t_indep
304
+ _rhs = rhs - t_indep
305
+ if not t_term.is_Add and _rhs and not (
306
+ t_term.has(S.ComplexInfinity, S.NaN)):
307
+ eq = expand_log(log(t_term) - log(_rhs))
308
+ return _solve_even_degree_expr(eq, t, symbol)
309
+ elif lhs.is_Mul and rhs:
310
+ # this needs to happen whether t is present or not
311
+ lhs = expand_log(log(lhs), force=True)
312
+ rhs = log(rhs)
313
+ if lhs.has(t) and lhs.is_Add:
314
+ # it expanded from Mul to Add
315
+ eq = lhs - rhs
316
+ return _solve_even_degree_expr(eq, t, symbol)
317
+
318
+ # restore symbol in lhs
319
+ lhs = lhs.xreplace({t: symbol})
320
+
321
+ lhs = powsimp(factor(lhs, deep=True))
322
+
323
+ # make sure we have inverted as completely as possible
324
+ r = Dummy()
325
+ i, lhs = _invert(lhs - r, symbol)
326
+ rhs = i.xreplace({r: rhs})
327
+
328
+ # For the first forms:
329
+ #
330
+ # 1a1) B**B = R will arrive here as B*log(B) = log(R)
331
+ # lhs is Mul so take log of both sides:
332
+ # log(B) + log(log(B)) = log(log(R))
333
+ # 1a2) B*(b*log(B) + c)**a = R will arrive unchanged so
334
+ # lhs is Mul, so take log of both sides:
335
+ # log(B) + a*log(b*log(B) + c) = log(R)
336
+ # 1b) d*log(a*B + b) + c*B = R will arrive unchanged so
337
+ # lhs is Add, so isolate c*B and expand log of both sides:
338
+ # log(c) + log(B) = log(R - d*log(a*B + b))
339
+
340
+ soln = []
341
+ if not soln:
342
+ mainlog = _mostfunc(lhs, log, symbol)
343
+ if mainlog:
344
+ if lhs.is_Mul and rhs != 0:
345
+ soln = _lambert(log(lhs) - log(rhs), symbol)
346
+ elif lhs.is_Add:
347
+ other = lhs.subs(mainlog, 0)
348
+ if other and not other.is_Add and [
349
+ tmp for tmp in other.atoms(Pow)
350
+ if symbol in tmp.free_symbols]:
351
+ if not rhs:
352
+ diff = log(other) - log(other - lhs)
353
+ else:
354
+ diff = log(lhs - other) - log(rhs - other)
355
+ soln = _lambert(expand_log(diff), symbol)
356
+ else:
357
+ #it's ready to go
358
+ soln = _lambert(lhs - rhs, symbol)
359
+
360
+ # For the next forms,
361
+ #
362
+ # collect on main exp
363
+ # 2a) (b*B + c)*exp(d*B + g) = R
364
+ # lhs is mul, so take log of both sides:
365
+ # log(b*B + c) + d*B = log(R) - g
366
+ # 2b) g*exp(d*B + h) - b*B = R
367
+ # lhs is add, so add b*B to both sides,
368
+ # take the log of both sides and rearrange to give
369
+ # log(R + b*B) - d*B = log(g) + h
370
+
371
+ if not soln:
372
+ mainexp = _mostfunc(lhs, exp, symbol)
373
+ if mainexp:
374
+ lhs = collect(lhs, mainexp)
375
+ if lhs.is_Mul and rhs != 0:
376
+ soln = _lambert(expand_log(log(lhs) - log(rhs)), symbol)
377
+ elif lhs.is_Add:
378
+ # move all but mainexp-containing term to rhs
379
+ other = lhs.subs(mainexp, 0)
380
+ mainterm = lhs - other
381
+ rhs = rhs - other
382
+ if (mainterm.could_extract_minus_sign() and
383
+ rhs.could_extract_minus_sign()):
384
+ mainterm *= -1
385
+ rhs *= -1
386
+ diff = log(mainterm) - log(rhs)
387
+ soln = _lambert(expand_log(diff), symbol)
388
+
389
+ # For the last form:
390
+ #
391
+ # 3) d*p**(a*B + g) - b*B = c
392
+ # collect on main pow, add b*B to both sides,
393
+ # take log of both sides and rearrange to give
394
+ # a*B*log(p) - log(b*B + c) = -log(d) - g*log(p)
395
+ if not soln:
396
+ mainpow = _mostfunc(lhs, Pow, symbol)
397
+ if mainpow and symbol in mainpow.exp.free_symbols:
398
+ lhs = collect(lhs, mainpow)
399
+ if lhs.is_Mul and rhs != 0:
400
+ # b*B = 0
401
+ soln = _lambert(expand_log(log(lhs) - log(rhs)), symbol)
402
+ elif lhs.is_Add:
403
+ # move all but mainpow-containing term to rhs
404
+ other = lhs.subs(mainpow, 0)
405
+ mainterm = lhs - other
406
+ rhs = rhs - other
407
+ diff = log(mainterm) - log(rhs)
408
+ soln = _lambert(expand_log(diff), symbol)
409
+
410
+ if not soln:
411
+ raise NotImplementedError('%s does not appear to have a solution in '
412
+ 'terms of LambertW' % f)
413
+
414
+ return list(ordered(soln))
415
+
416
+
417
+ def bivariate_type(f, x, y, *, first=True):
418
+ """Given an expression, f, 3 tests will be done to see what type
419
+ of composite bivariate it might be, options for u(x, y) are::
420
+
421
+ x*y
422
+ x+y
423
+ x*y+x
424
+ x*y+y
425
+
426
+ If it matches one of these types, ``u(x, y)``, ``P(u)`` and dummy
427
+ variable ``u`` will be returned. Solving ``P(u)`` for ``u`` and
428
+ equating the solutions to ``u(x, y)`` and then solving for ``x`` or
429
+ ``y`` is equivalent to solving the original expression for ``x`` or
430
+ ``y``. If ``x`` and ``y`` represent two functions in the same
431
+ variable, e.g. ``x = g(t)`` and ``y = h(t)``, then if ``u(x, y) - p``
432
+ can be solved for ``t`` then these represent the solutions to
433
+ ``P(u) = 0`` when ``p`` are the solutions of ``P(u) = 0``.
434
+
435
+ Only positive values of ``u`` are considered.
436
+
437
+ Examples
438
+ ========
439
+
440
+ >>> from sympy import solve
441
+ >>> from sympy.solvers.bivariate import bivariate_type
442
+ >>> from sympy.abc import x, y
443
+ >>> eq = (x**2 - 3).subs(x, x + y)
444
+ >>> bivariate_type(eq, x, y)
445
+ (x + y, _u**2 - 3, _u)
446
+ >>> uxy, pu, u = _
447
+ >>> usol = solve(pu, u); usol
448
+ [sqrt(3)]
449
+ >>> [solve(uxy - s) for s in solve(pu, u)]
450
+ [[{x: -y + sqrt(3)}]]
451
+ >>> all(eq.subs(s).equals(0) for sol in _ for s in sol)
452
+ True
453
+
454
+ """
455
+
456
+ u = Dummy('u', positive=True)
457
+
458
+ if first:
459
+ p = Poly(f, x, y)
460
+ f = p.as_expr()
461
+ _x = Dummy()
462
+ _y = Dummy()
463
+ rv = bivariate_type(Poly(f.subs({x: _x, y: _y}), _x, _y), _x, _y, first=False)
464
+ if rv:
465
+ reps = {_x: x, _y: y}
466
+ return rv[0].xreplace(reps), rv[1].xreplace(reps), rv[2]
467
+ return
468
+
469
+ p = f
470
+ f = p.as_expr()
471
+
472
+ # f(x*y)
473
+ args = Add.make_args(p.as_expr())
474
+ new = []
475
+ for a in args:
476
+ a = _mexpand(a.subs(x, u/y))
477
+ free = a.free_symbols
478
+ if x in free or y in free:
479
+ break
480
+ new.append(a)
481
+ else:
482
+ return x*y, Add(*new), u
483
+
484
+ def ok(f, v, c):
485
+ new = _mexpand(f.subs(v, c))
486
+ free = new.free_symbols
487
+ return None if (x in free or y in free) else new
488
+
489
+ # f(a*x + b*y)
490
+ new = []
491
+ d = p.degree(x)
492
+ if p.degree(y) == d:
493
+ a = root(p.coeff_monomial(x**d), d)
494
+ b = root(p.coeff_monomial(y**d), d)
495
+ new = ok(f, x, (u - b*y)/a)
496
+ if new is not None:
497
+ return a*x + b*y, new, u
498
+
499
+ # f(a*x*y + b*y)
500
+ new = []
501
+ d = p.degree(x)
502
+ if p.degree(y) == d:
503
+ for itry in range(2):
504
+ a = root(p.coeff_monomial(x**d*y**d), d)
505
+ b = root(p.coeff_monomial(y**d), d)
506
+ new = ok(f, x, (u - b*y)/a/y)
507
+ if new is not None:
508
+ return a*x*y + b*y, new, u
509
+ x, y = y, x
env-llmeval/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)
env-llmeval/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
+ ]
env-llmeval/lib/python3.10/site-packages/sympy/solvers/diophantine/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (288 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/solvers/diophantine/__pycache__/diophantine.cpython-310.pyc ADDED
Binary file (103 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/solvers/diophantine/diophantine.py ADDED
The diff for this file is too large to render. See raw diff
 
env-llmeval/lib/python3.10/site-packages/sympy/solvers/diophantine/tests/__init__.py ADDED
File without changes
env-llmeval/lib/python3.10/site-packages/sympy/solvers/diophantine/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (196 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/solvers/diophantine/tests/__pycache__/test_diophantine.cpython-310.pyc ADDED
Binary file (46 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/solvers/diophantine/tests/test_diophantine.py ADDED
@@ -0,0 +1,1037 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
360
+
361
+ def test_diop_ternary_quadratic_normal():
362
+ assert check_solutions(234*x**2 - 65601*y**2 - z**2)
363
+ assert check_solutions(23*x**2 + 616*y**2 - z**2)
364
+ assert check_solutions(5*x**2 + 4*y**2 - z**2)
365
+ assert check_solutions(3*x**2 + 6*y**2 - 3*z**2)
366
+ assert check_solutions(x**2 + 3*y**2 - z**2)
367
+ assert check_solutions(4*x**2 + 5*y**2 - z**2)
368
+ assert check_solutions(x**2 + y**2 - z**2)
369
+ assert check_solutions(16*x**2 + y**2 - 25*z**2)
370
+ assert check_solutions(6*x**2 - y**2 + 10*z**2)
371
+ assert check_solutions(213*x**2 + 12*y**2 - 9*z**2)
372
+ assert check_solutions(34*x**2 - 3*y**2 - 301*z**2)
373
+ assert check_solutions(124*x**2 - 30*y**2 - 7729*z**2)
374
+
375
+
376
+ def is_normal_transformation_ok(eq):
377
+ A = transformation_to_normal(eq)
378
+ X, Y, Z = A*Matrix([x, y, z])
379
+ simplified = diop_simplify(eq.subs(zip((x, y, z), (X, Y, Z))))
380
+
381
+ coeff = dict([reversed(t.as_independent(*[X, Y, Z])) for t in simplified.args])
382
+ for term in [X*Y, Y*Z, X*Z]:
383
+ if term in coeff.keys():
384
+ return False
385
+
386
+ return True
387
+
388
+
389
+ def test_transformation_to_normal():
390
+ assert is_normal_transformation_ok(x**2 + 3*y**2 + z**2 - 13*x*y - 16*y*z + 12*x*z)
391
+ assert is_normal_transformation_ok(x**2 + 3*y**2 - 100*z**2)
392
+ assert is_normal_transformation_ok(x**2 + 23*y*z)
393
+ assert is_normal_transformation_ok(3*y**2 - 100*z**2 - 12*x*y)
394
+ assert is_normal_transformation_ok(x**2 + 23*x*y - 34*y*z + 12*x*z)
395
+ assert is_normal_transformation_ok(z**2 + 34*x*y - 23*y*z + x*z)
396
+ assert is_normal_transformation_ok(x**2 + y**2 + z**2 - x*y - y*z - x*z)
397
+ assert is_normal_transformation_ok(x**2 + 2*y*z + 3*z**2)
398
+ assert is_normal_transformation_ok(x*y + 2*x*z + 3*y*z)
399
+ assert is_normal_transformation_ok(2*x*z + 3*y*z)
400
+
401
+
402
+ def test_diop_ternary_quadratic():
403
+ assert check_solutions(2*x**2 + z**2 + y**2 - 4*x*y)
404
+ assert check_solutions(x**2 - y**2 - z**2 - x*y - y*z)
405
+ assert check_solutions(3*x**2 - x*y - y*z - x*z)
406
+ assert check_solutions(x**2 - y*z - x*z)
407
+ assert check_solutions(5*x**2 - 3*x*y - x*z)
408
+ assert check_solutions(4*x**2 - 5*y**2 - x*z)
409
+ assert check_solutions(3*x**2 + 2*y**2 - z**2 - 2*x*y + 5*y*z - 7*y*z)
410
+ assert check_solutions(8*x**2 - 12*y*z)
411
+ assert check_solutions(45*x**2 - 7*y**2 - 8*x*y - z**2)
412
+ assert check_solutions(x**2 - 49*y**2 - z**2 + 13*z*y -8*x*y)
413
+ assert check_solutions(90*x**2 + 3*y**2 + 5*x*y + 2*z*y + 5*x*z)
414
+ assert check_solutions(x**2 + 3*y**2 + z**2 - x*y - 17*y*z)
415
+ assert check_solutions(x**2 + 3*y**2 + z**2 - x*y - 16*y*z + 12*x*z)
416
+ assert check_solutions(x**2 + 3*y**2 + z**2 - 13*x*y - 16*y*z + 12*x*z)
417
+ assert check_solutions(x*y - 7*y*z + 13*x*z)
418
+
419
+ assert diop_ternary_quadratic_normal(x**2 + y**2 + z**2) == (None, None, None)
420
+ assert diop_ternary_quadratic_normal(x**2 + y**2) is None
421
+ raises(ValueError, lambda:
422
+ _diop_ternary_quadratic_normal((x, y, z),
423
+ {x*y: 1, x**2: 2, y**2: 3, z**2: 0}))
424
+ eq = -2*x*y - 6*x*z + 7*y**2 - 3*y*z + 4*z**2
425
+ assert diop_ternary_quadratic(eq) == (7, 2, 0)
426
+ assert diop_ternary_quadratic_normal(4*x**2 + 5*y**2 - z**2) == \
427
+ (1, 0, 2)
428
+ assert diop_ternary_quadratic(x*y + 2*y*z) == \
429
+ (-2, 0, n1)
430
+ eq = -5*x*y - 8*x*z - 3*y*z + 8*z**2
431
+ assert parametrize_ternary_quadratic(eq) == \
432
+ (8*p**2 - 3*p*q, -8*p*q + 8*q**2, 5*p*q)
433
+ # this cannot be tested with diophantine because it will
434
+ # factor into a product
435
+ assert diop_solve(x*y + 2*y*z) == (-2*p*q, -n1*p**2 + p**2, p*q)
436
+
437
+
438
+ def test_square_factor():
439
+ assert square_factor(1) == square_factor(-1) == 1
440
+ assert square_factor(0) == 1
441
+ assert square_factor(5) == square_factor(-5) == 1
442
+ assert square_factor(4) == square_factor(-4) == 2
443
+ assert square_factor(12) == square_factor(-12) == 2
444
+ assert square_factor(6) == 1
445
+ assert square_factor(18) == 3
446
+ assert square_factor(52) == 2
447
+ assert square_factor(49) == 7
448
+ assert square_factor(392) == 14
449
+ assert square_factor(factorint(-12)) == 2
450
+
451
+
452
+ def test_parametrize_ternary_quadratic():
453
+ assert check_solutions(x**2 + y**2 - z**2)
454
+ assert check_solutions(x**2 + 2*x*y + z**2)
455
+ assert check_solutions(234*x**2 - 65601*y**2 - z**2)
456
+ assert check_solutions(3*x**2 + 2*y**2 - z**2 - 2*x*y + 5*y*z - 7*y*z)
457
+ assert check_solutions(x**2 - y**2 - z**2)
458
+ assert check_solutions(x**2 - 49*y**2 - z**2 + 13*z*y - 8*x*y)
459
+ assert check_solutions(8*x*y + z**2)
460
+ assert check_solutions(124*x**2 - 30*y**2 - 7729*z**2)
461
+ assert check_solutions(236*x**2 - 225*y**2 - 11*x*y - 13*y*z - 17*x*z)
462
+ assert check_solutions(90*x**2 + 3*y**2 + 5*x*y + 2*z*y + 5*x*z)
463
+ assert check_solutions(124*x**2 - 30*y**2 - 7729*z**2)
464
+
465
+
466
+ def test_no_square_ternary_quadratic():
467
+ assert check_solutions(2*x*y + y*z - 3*x*z)
468
+ assert check_solutions(189*x*y - 345*y*z - 12*x*z)
469
+ assert check_solutions(23*x*y + 34*y*z)
470
+ assert check_solutions(x*y + y*z + z*x)
471
+ assert check_solutions(23*x*y + 23*y*z + 23*x*z)
472
+
473
+
474
+ def test_descent():
475
+
476
+ u = ([(13, 23), (3, -11), (41, -113), (91, -3), (1, 1), (1, -1), (17, 13), (123689, 1), (19, -570)])
477
+ for a, b in u:
478
+ w, x, y = descent(a, b)
479
+ assert a*x**2 + b*y**2 == w**2
480
+ # the docstring warns against bad input, so these are expected results
481
+ # - can't both be negative
482
+ raises(TypeError, lambda: descent(-1, -3))
483
+ # A can't be zero unless B != 1
484
+ raises(ZeroDivisionError, lambda: descent(0, 3))
485
+ # supposed to be square-free
486
+ raises(TypeError, lambda: descent(4, 3))
487
+
488
+
489
+ def test_diophantine():
490
+ assert check_solutions((x - y)*(y - z)*(z - x))
491
+ assert check_solutions((x - y)*(x**2 + y**2 - z**2))
492
+ assert check_solutions((x - 3*y + 7*z)*(x**2 + y**2 - z**2))
493
+ assert check_solutions(x**2 - 3*y**2 - 1)
494
+ assert check_solutions(y**2 + 7*x*y)
495
+ assert check_solutions(x**2 - 3*x*y + y**2)
496
+ assert check_solutions(z*(x**2 - y**2 - 15))
497
+ assert check_solutions(x*(2*y - 2*z + 5))
498
+ assert check_solutions((x**2 - 3*y**2 - 1)*(x**2 - y**2 - 15))
499
+ assert check_solutions((x**2 - 3*y**2 - 1)*(y - 7*z))
500
+ assert check_solutions((x**2 + y**2 - z**2)*(x - 7*y - 3*z + 4*w))
501
+ # Following test case caused problems in parametric representation
502
+ # But this can be solved by factoring out y.
503
+ # No need to use methods for ternary quadratic equations.
504
+ assert check_solutions(y**2 - 7*x*y + 4*y*z)
505
+ assert check_solutions(x**2 - 2*x + 1)
506
+
507
+ assert diophantine(x - y) == diophantine(Eq(x, y))
508
+ # 18196
509
+ eq = x**4 + y**4 - 97
510
+ assert diophantine(eq, permute=True) == diophantine(-eq, permute=True)
511
+ assert diophantine(3*x*pi - 2*y*pi) == {(2*t_0, 3*t_0)}
512
+ eq = x**2 + y**2 + z**2 - 14
513
+ base_sol = {(1, 2, 3)}
514
+ assert diophantine(eq) == base_sol
515
+ complete_soln = set(signed_permutations(base_sol.pop()))
516
+ assert diophantine(eq, permute=True) == complete_soln
517
+
518
+ assert diophantine(x**2 + x*Rational(15, 14) - 3) == set()
519
+ # test issue 11049
520
+ eq = 92*x**2 - 99*y**2 - z**2
521
+ coeff = eq.as_coefficients_dict()
522
+ assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \
523
+ {(9, 7, 51)}
524
+ assert diophantine(eq) == {(
525
+ 891*p**2 + 9*q**2, -693*p**2 - 102*p*q + 7*q**2,
526
+ 5049*p**2 - 1386*p*q - 51*q**2)}
527
+ eq = 2*x**2 + 2*y**2 - z**2
528
+ coeff = eq.as_coefficients_dict()
529
+ assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \
530
+ {(1, 1, 2)}
531
+ assert diophantine(eq) == {(
532
+ 2*p**2 - q**2, -2*p**2 + 4*p*q - q**2,
533
+ 4*p**2 - 4*p*q + 2*q**2)}
534
+ eq = 411*x**2+57*y**2-221*z**2
535
+ coeff = eq.as_coefficients_dict()
536
+ assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \
537
+ {(2021, 2645, 3066)}
538
+ assert diophantine(eq) == \
539
+ {(115197*p**2 - 446641*q**2, -150765*p**2 + 1355172*p*q -
540
+ 584545*q**2, 174762*p**2 - 301530*p*q + 677586*q**2)}
541
+ eq = 573*x**2+267*y**2-984*z**2
542
+ coeff = eq.as_coefficients_dict()
543
+ assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \
544
+ {(49, 233, 127)}
545
+ assert diophantine(eq) == \
546
+ {(4361*p**2 - 16072*q**2, -20737*p**2 + 83312*p*q - 76424*q**2,
547
+ 11303*p**2 - 41474*p*q + 41656*q**2)}
548
+ # this produces factors during reconstruction
549
+ eq = x**2 + 3*y**2 - 12*z**2
550
+ coeff = eq.as_coefficients_dict()
551
+ assert _diop_ternary_quadratic_normal((x, y, z), coeff) == \
552
+ {(0, 2, 1)}
553
+ assert diophantine(eq) == \
554
+ {(24*p*q, 2*p**2 - 24*q**2, p**2 + 12*q**2)}
555
+ # solvers have not been written for every type
556
+ raises(NotImplementedError, lambda: diophantine(x*y**2 + 1))
557
+
558
+ # rational expressions
559
+ assert diophantine(1/x) == set()
560
+ assert diophantine(1/x + 1/y - S.Half) == {(6, 3), (-2, 1), (4, 4), (1, -2), (3, 6)}
561
+ assert diophantine(x**2 + y**2 +3*x- 5, permute=True) == \
562
+ {(-1, 1), (-4, -1), (1, -1), (1, 1), (-4, 1), (-1, -1), (4, 1), (4, -1)}
563
+
564
+
565
+ #test issue 18186
566
+ assert diophantine(y**4 + x**4 - 2**4 - 3**4, syms=(x, y), permute=True) == \
567
+ {(-3, -2), (-3, 2), (-2, -3), (-2, 3), (2, -3), (2, 3), (3, -2), (3, 2)}
568
+ assert diophantine(y**4 + x**4 - 2**4 - 3**4, syms=(y, x), permute=True) == \
569
+ {(-3, -2), (-3, 2), (-2, -3), (-2, 3), (2, -3), (2, 3), (3, -2), (3, 2)}
570
+
571
+ # issue 18122
572
+ assert check_solutions(x**2-y)
573
+ assert check_solutions(y**2-x)
574
+ assert diophantine((x**2-y), t) == {(t, t**2)}
575
+ assert diophantine((y**2-x), t) == {(t**2, -t)}
576
+
577
+
578
+ def test_general_pythagorean():
579
+ from sympy.abc import a, b, c, d, e
580
+
581
+ assert check_solutions(a**2 + b**2 + c**2 - d**2)
582
+ assert check_solutions(a**2 + 4*b**2 + 4*c**2 - d**2)
583
+ assert check_solutions(9*a**2 + 4*b**2 + 4*c**2 - d**2)
584
+ assert check_solutions(9*a**2 + 4*b**2 - 25*d**2 + 4*c**2 )
585
+ assert check_solutions(9*a**2 - 16*d**2 + 4*b**2 + 4*c**2)
586
+ assert check_solutions(-e**2 + 9*a**2 + 4*b**2 + 4*c**2 + 25*d**2)
587
+ assert check_solutions(16*a**2 - b**2 + 9*c**2 + d**2 + 25*e**2)
588
+
589
+ assert GeneralPythagorean(a**2 + b**2 + c**2 - d**2).solve(parameters=[x, y, z]) == \
590
+ {(x**2 + y**2 - z**2, 2*x*z, 2*y*z, x**2 + y**2 + z**2)}
591
+
592
+
593
+ def test_diop_general_sum_of_squares_quick():
594
+ for i in range(3, 10):
595
+ assert check_solutions(sum(i**2 for i in symbols(':%i' % i)) - i)
596
+
597
+ assert diop_general_sum_of_squares(x**2 + y**2 - 2) is None
598
+ assert diop_general_sum_of_squares(x**2 + y**2 + z**2 + 2) == set()
599
+ eq = x**2 + y**2 + z**2 - (1 + 4 + 9)
600
+ assert diop_general_sum_of_squares(eq) == \
601
+ {(1, 2, 3)}
602
+ eq = u**2 + v**2 + x**2 + y**2 + z**2 - 1313
603
+ assert len(diop_general_sum_of_squares(eq, 3)) == 3
604
+ # issue 11016
605
+ var = symbols(':5') + (symbols('6', negative=True),)
606
+ eq = Add(*[i**2 for i in var]) - 112
607
+
608
+ 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),
609
+ (0, 0, 4, 4, 4, -8), (1, 2, 3, 3, 5, -8), (0, 1, 2, 3, 7, -7), (2, 2, 4, 4, 6, -6),
610
+ (1, 1, 3, 4, 6, -7), (0, 2, 3, 3, 3, -9), (0, 0, 2, 2, 2, -10), (1, 1, 2, 3, 4, -9),
611
+ (0, 1, 1, 2, 5, -9), (0, 0, 2, 6, 6, -6), (1, 3, 4, 5, 5, -6), (0, 2, 2, 2, 6, -8),
612
+ (0, 3, 3, 3, 6, -7), (0, 2, 3, 5, 5, -7), (0, 1, 5, 5, 5, -6)}
613
+ assert diophantine(eq) == base_soln
614
+ assert len(diophantine(eq, permute=True)) == 196800
615
+
616
+ # handle negated squares with signsimp
617
+ assert diophantine(12 - x**2 - y**2 - z**2) == {(2, 2, 2)}
618
+ # diophantine handles simplification, so classify_diop should
619
+ # not have to look for additional patterns that are removed
620
+ # by diophantine
621
+ eq = a**2 + b**2 + c**2 + d**2 - 4
622
+ raises(NotImplementedError, lambda: classify_diop(-eq))
623
+
624
+
625
+ def test_issue_23807():
626
+ # fixes recursion error
627
+ eq = x**2 + y**2 + z**2 - 1000000
628
+ base_soln = {(0, 0, 1000), (0, 352, 936), (480, 600, 640), (24, 640, 768), (192, 640, 744),
629
+ (192, 480, 856), (168, 224, 960), (0, 600, 800), (280, 576, 768), (152, 480, 864),
630
+ (0, 280, 960), (352, 360, 864), (424, 480, 768), (360, 480, 800), (224, 600, 768),
631
+ (96, 360, 928), (168, 576, 800), (96, 480, 872)}
632
+
633
+ assert diophantine(eq) == base_soln
634
+
635
+
636
+ def test_diop_partition():
637
+ for n in [8, 10]:
638
+ for k in range(1, 8):
639
+ for p in partition(n, k):
640
+ assert len(p) == k
641
+ assert list(partition(3, 5)) == []
642
+ assert [list(p) for p in partition(3, 5, 1)] == [
643
+ [0, 0, 0, 0, 3], [0, 0, 0, 1, 2], [0, 0, 1, 1, 1]]
644
+ assert list(partition(0)) == [()]
645
+ assert list(partition(1, 0)) == [()]
646
+ assert [list(i) for i in partition(3)] == [[1, 1, 1], [1, 2], [3]]
647
+
648
+
649
+ def test_prime_as_sum_of_two_squares():
650
+ for i in [5, 13, 17, 29, 37, 41, 2341, 3557, 34841, 64601]:
651
+ a, b = prime_as_sum_of_two_squares(i)
652
+ assert a**2 + b**2 == i
653
+ assert prime_as_sum_of_two_squares(7) is None
654
+ ans = prime_as_sum_of_two_squares(800029)
655
+ assert ans == (450, 773) and type(ans[0]) is int
656
+
657
+
658
+ def test_sum_of_three_squares():
659
+ for i in [0, 1, 2, 34, 123, 34304595905, 34304595905394941, 343045959052344,
660
+ 800, 801, 802, 803, 804, 805, 806]:
661
+ a, b, c = sum_of_three_squares(i)
662
+ assert a**2 + b**2 + c**2 == i
663
+
664
+ assert sum_of_three_squares(7) is None
665
+ assert sum_of_three_squares((4**5)*15) is None
666
+ assert sum_of_three_squares(25) == (5, 0, 0)
667
+ assert sum_of_three_squares(4) == (0, 0, 2)
668
+
669
+
670
+ def test_sum_of_four_squares():
671
+ from sympy.core.random import randint
672
+
673
+ # this should never fail
674
+ n = randint(1, 100000000000000)
675
+ assert sum(i**2 for i in sum_of_four_squares(n)) == n
676
+
677
+ assert sum_of_four_squares(0) == (0, 0, 0, 0)
678
+ assert sum_of_four_squares(14) == (0, 1, 2, 3)
679
+ assert sum_of_four_squares(15) == (1, 1, 2, 3)
680
+ assert sum_of_four_squares(18) == (1, 2, 2, 3)
681
+ assert sum_of_four_squares(19) == (0, 1, 3, 3)
682
+ assert sum_of_four_squares(48) == (0, 4, 4, 4)
683
+
684
+
685
+ def test_power_representation():
686
+ tests = [(1729, 3, 2), (234, 2, 4), (2, 1, 2), (3, 1, 3), (5, 2, 2), (12352, 2, 4),
687
+ (32760, 2, 3)]
688
+
689
+ for test in tests:
690
+ n, p, k = test
691
+ f = power_representation(n, p, k)
692
+
693
+ while True:
694
+ try:
695
+ l = next(f)
696
+ assert len(l) == k
697
+
698
+ chk_sum = 0
699
+ for l_i in l:
700
+ chk_sum = chk_sum + l_i**p
701
+ assert chk_sum == n
702
+
703
+ except StopIteration:
704
+ break
705
+
706
+ assert list(power_representation(20, 2, 4, True)) == \
707
+ [(1, 1, 3, 3), (0, 0, 2, 4)]
708
+ raises(ValueError, lambda: list(power_representation(1.2, 2, 2)))
709
+ raises(ValueError, lambda: list(power_representation(2, 0, 2)))
710
+ raises(ValueError, lambda: list(power_representation(2, 2, 0)))
711
+ assert list(power_representation(-1, 2, 2)) == []
712
+ assert list(power_representation(1, 1, 1)) == [(1,)]
713
+ assert list(power_representation(3, 2, 1)) == []
714
+ assert list(power_representation(4, 2, 1)) == [(2,)]
715
+ assert list(power_representation(3**4, 4, 6, zeros=True)) == \
716
+ [(1, 2, 2, 2, 2, 2), (0, 0, 0, 0, 0, 3)]
717
+ assert list(power_representation(3**4, 4, 5, zeros=False)) == []
718
+ assert list(power_representation(-2, 3, 2)) == [(-1, -1)]
719
+ assert list(power_representation(-2, 4, 2)) == []
720
+ assert list(power_representation(0, 3, 2, True)) == [(0, 0)]
721
+ assert list(power_representation(0, 3, 2, False)) == []
722
+ # when we are dealing with squares, do feasibility checks
723
+ assert len(list(power_representation(4**10*(8*10 + 7), 2, 3))) == 0
724
+ # there will be a recursion error if these aren't recognized
725
+ big = 2**30
726
+ for i in [13, 10, 7, 5, 4, 2, 1]:
727
+ assert list(sum_of_powers(big, 2, big - i)) == []
728
+
729
+
730
+ def test_assumptions():
731
+ """
732
+ Test whether diophantine respects the assumptions.
733
+ """
734
+ #Test case taken from the below so question regarding assumptions in diophantine module
735
+ #https://stackoverflow.com/questions/23301941/how-can-i-declare-natural-symbols-with-sympy
736
+ m, n = symbols('m n', integer=True, positive=True)
737
+ diof = diophantine(n**2 + m*n - 500)
738
+ assert diof == {(5, 20), (40, 10), (95, 5), (121, 4), (248, 2), (499, 1)}
739
+
740
+ a, b = symbols('a b', integer=True, positive=False)
741
+ diof = diophantine(a*b + 2*a + 3*b - 6)
742
+ assert diof == {(-15, -3), (-9, -4), (-7, -5), (-6, -6), (-5, -8), (-4, -14)}
743
+
744
+
745
+ def check_solutions(eq):
746
+ """
747
+ Determines whether solutions returned by diophantine() satisfy the original
748
+ equation. Hope to generalize this so we can remove functions like check_ternay_quadratic,
749
+ check_solutions_normal, check_solutions()
750
+ """
751
+ s = diophantine(eq)
752
+
753
+ factors = Mul.make_args(eq)
754
+
755
+ var = list(eq.free_symbols)
756
+ var.sort(key=default_sort_key)
757
+
758
+ while s:
759
+ solution = s.pop()
760
+ for f in factors:
761
+ if diop_simplify(f.subs(zip(var, solution))) == 0:
762
+ break
763
+ else:
764
+ return False
765
+ return True
766
+
767
+
768
+ def test_diopcoverage():
769
+ eq = (2*x + y + 1)**2
770
+ assert diop_solve(eq) == {(t_0, -2*t_0 - 1)}
771
+ eq = 2*x**2 + 6*x*y + 12*x + 4*y**2 + 18*y + 18
772
+ assert diop_solve(eq) == {(t, -t - 3), (2*t - 3, -t)}
773
+ assert diop_quadratic(x + y**2 - 3) == {(-t**2 + 3, -t)}
774
+
775
+ assert diop_linear(x + y - 3) == (t_0, 3 - t_0)
776
+
777
+ assert base_solution_linear(0, 1, 2, t=None) == (0, 0)
778
+ ans = (3*t - 1, -2*t + 1)
779
+ assert base_solution_linear(4, 8, 12, t) == ans
780
+ assert base_solution_linear(4, 8, 12, t=None) == tuple(_.subs(t, 0) for _ in ans)
781
+
782
+ assert cornacchia(1, 1, 20) is None
783
+ assert cornacchia(1, 1, 5) == {(2, 1)}
784
+ assert cornacchia(1, 2, 17) == {(3, 2)}
785
+
786
+ raises(ValueError, lambda: reconstruct(4, 20, 1))
787
+
788
+ assert gaussian_reduce(4, 1, 3) == (1, 1)
789
+ eq = -w**2 - x**2 - y**2 + z**2
790
+
791
+ assert diop_general_pythagorean(eq) == \
792
+ diop_general_pythagorean(-eq) == \
793
+ (m1**2 + m2**2 - m3**2, 2*m1*m3,
794
+ 2*m2*m3, m1**2 + m2**2 + m3**2)
795
+
796
+ assert len(check_param(S(3) + x/3, S(4) + x/2, S(2), [x])) == 0
797
+ assert len(check_param(Rational(3, 2), S(4) + x, S(2), [x])) == 0
798
+ assert len(check_param(S(4) + x, Rational(3, 2), S(2), [x])) == 0
799
+
800
+ assert _nint_or_floor(16, 10) == 2
801
+ assert _odd(1) == (not _even(1)) == True
802
+ assert _odd(0) == (not _even(0)) == False
803
+ assert _remove_gcd(2, 4, 6) == (1, 2, 3)
804
+ raises(TypeError, lambda: _remove_gcd((2, 4, 6)))
805
+ assert sqf_normal(2*3**2*5, 2*5*11, 2*7**2*11) == \
806
+ (11, 1, 5)
807
+
808
+ # it's ok if these pass some day when the solvers are implemented
809
+ raises(NotImplementedError, lambda: diophantine(x**2 + y**2 + x*y + 2*y*z - 12))
810
+ raises(NotImplementedError, lambda: diophantine(x**3 + y**2))
811
+ assert diop_quadratic(x**2 + y**2 - 1**2 - 3**4) == \
812
+ {(-9, -1), (-9, 1), (-1, -9), (-1, 9), (1, -9), (1, 9), (9, -1), (9, 1)}
813
+
814
+
815
+ def test_holzer():
816
+ # if the input is good, don't let it diverge in holzer()
817
+ # (but see test_fail_holzer below)
818
+ assert holzer(2, 7, 13, 4, 79, 23) == (2, 7, 13)
819
+
820
+ # None in uv condition met; solution is not Holzer reduced
821
+ # so this will hopefully change but is here for coverage
822
+ assert holzer(2, 6, 2, 1, 1, 10) == (2, 6, 2)
823
+
824
+ raises(ValueError, lambda: holzer(2, 7, 14, 4, 79, 23))
825
+
826
+
827
+ @XFAIL
828
+ def test_fail_holzer():
829
+ eq = lambda x, y, z: a*x**2 + b*y**2 - c*z**2
830
+ a, b, c = 4, 79, 23
831
+ x, y, z = xyz = 26, 1, 11
832
+ X, Y, Z = ans = 2, 7, 13
833
+ assert eq(*xyz) == 0
834
+ assert eq(*ans) == 0
835
+ assert max(a*x**2, b*y**2, c*z**2) <= a*b*c
836
+ assert max(a*X**2, b*Y**2, c*Z**2) <= a*b*c
837
+ h = holzer(x, y, z, a, b, c)
838
+ assert h == ans # it would be nice to get the smaller soln
839
+
840
+
841
+ def test_issue_9539():
842
+ assert diophantine(6*w + 9*y + 20*x - z) == \
843
+ {(t_0, t_1, t_1 + t_2, 6*t_0 + 29*t_1 + 9*t_2)}
844
+
845
+
846
+ def test_issue_8943():
847
+ assert diophantine(
848
+ 3*(x**2 + y**2 + z**2) - 14*(x*y + y*z + z*x)) == \
849
+ {(0, 0, 0)}
850
+
851
+
852
+ def test_diop_sum_of_even_powers():
853
+ eq = x**4 + y**4 + z**4 - 2673
854
+ assert diop_solve(eq) == {(3, 6, 6), (2, 4, 7)}
855
+ assert diop_general_sum_of_even_powers(eq, 2) == {(3, 6, 6), (2, 4, 7)}
856
+ raises(NotImplementedError, lambda: diop_general_sum_of_even_powers(-eq, 2))
857
+ neg = symbols('neg', negative=True)
858
+ eq = x**4 + y**4 + neg**4 - 2673
859
+ assert diop_general_sum_of_even_powers(eq) == {(-3, 6, 6)}
860
+ assert diophantine(x**4 + y**4 + 2) == set()
861
+ assert diop_general_sum_of_even_powers(x**4 + y**4 - 2, limit=0) == set()
862
+
863
+
864
+ def test_sum_of_squares_powers():
865
+ 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),
866
+ (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),
867
+ (2, 3, 5, 6, 7), (3, 3, 4, 5, 8)}
868
+ eq = u**2 + v**2 + x**2 + y**2 + z**2 - 123
869
+ ans = diop_general_sum_of_squares(eq, oo) # allow oo to be used
870
+ assert len(ans) == 14
871
+ assert ans == tru
872
+
873
+ raises(ValueError, lambda: list(sum_of_squares(10, -1)))
874
+ assert list(sum_of_squares(-10, 2)) == []
875
+ assert list(sum_of_squares(2, 3)) == []
876
+ assert list(sum_of_squares(0, 3, True)) == [(0, 0, 0)]
877
+ assert list(sum_of_squares(0, 3)) == []
878
+ assert list(sum_of_squares(4, 1)) == [(2,)]
879
+ assert list(sum_of_squares(5, 1)) == []
880
+ assert list(sum_of_squares(50, 2)) == [(5, 5), (1, 7)]
881
+ assert list(sum_of_squares(11, 5, True)) == [
882
+ (1, 1, 1, 2, 2), (0, 0, 1, 1, 3)]
883
+ assert list(sum_of_squares(8, 8)) == [(1, 1, 1, 1, 1, 1, 1, 1)]
884
+
885
+ assert [len(list(sum_of_squares(i, 5, True))) for i in range(30)] == [
886
+ 1, 1, 1, 1, 2,
887
+ 2, 1, 1, 2, 2,
888
+ 2, 2, 2, 3, 2,
889
+ 1, 3, 3, 3, 3,
890
+ 4, 3, 3, 2, 2,
891
+ 4, 4, 4, 4, 5]
892
+ assert [len(list(sum_of_squares(i, 5))) for i in range(30)] == [
893
+ 0, 0, 0, 0, 0,
894
+ 1, 0, 0, 1, 0,
895
+ 0, 1, 0, 1, 1,
896
+ 0, 1, 1, 0, 1,
897
+ 2, 1, 1, 1, 1,
898
+ 1, 1, 1, 1, 3]
899
+ for i in range(30):
900
+ s1 = set(sum_of_squares(i, 5, True))
901
+ assert not s1 or all(sum(j**2 for j in t) == i for t in s1)
902
+ s2 = set(sum_of_squares(i, 5))
903
+ assert all(sum(j**2 for j in t) == i for t in s2)
904
+
905
+ raises(ValueError, lambda: list(sum_of_powers(2, -1, 1)))
906
+ raises(ValueError, lambda: list(sum_of_powers(2, 1, -1)))
907
+ assert list(sum_of_powers(-2, 3, 2)) == [(-1, -1)]
908
+ assert list(sum_of_powers(-2, 4, 2)) == []
909
+ assert list(sum_of_powers(2, 1, 1)) == [(2,)]
910
+ assert list(sum_of_powers(2, 1, 3, True)) == [(0, 0, 2), (0, 1, 1)]
911
+ assert list(sum_of_powers(5, 1, 2, True)) == [(0, 5), (1, 4), (2, 3)]
912
+ assert list(sum_of_powers(6, 2, 2)) == []
913
+ assert list(sum_of_powers(3**5, 3, 1)) == []
914
+ assert list(sum_of_powers(3**6, 3, 1)) == [(9,)] and (9**3 == 3**6)
915
+ assert list(sum_of_powers(2**1000, 5, 2)) == []
916
+
917
+
918
+ def test__can_do_sum_of_squares():
919
+ assert _can_do_sum_of_squares(3, -1) is False
920
+ assert _can_do_sum_of_squares(-3, 1) is False
921
+ assert _can_do_sum_of_squares(0, 1)
922
+ assert _can_do_sum_of_squares(4, 1)
923
+ assert _can_do_sum_of_squares(1, 2)
924
+ assert _can_do_sum_of_squares(2, 2)
925
+ assert _can_do_sum_of_squares(3, 2) is False
926
+
927
+
928
+ def test_diophantine_permute_sign():
929
+ from sympy.abc import a, b, c, d, e
930
+ eq = a**4 + b**4 - (2**4 + 3**4)
931
+ base_sol = {(2, 3)}
932
+ assert diophantine(eq) == base_sol
933
+ complete_soln = set(signed_permutations(base_sol.pop()))
934
+ assert diophantine(eq, permute=True) == complete_soln
935
+
936
+ eq = a**2 + b**2 + c**2 + d**2 + e**2 - 234
937
+ assert len(diophantine(eq)) == 35
938
+ assert len(diophantine(eq, permute=True)) == 62000
939
+ soln = {(-1, -1), (-1, 2), (1, -2), (1, 1)}
940
+ assert diophantine(10*x**2 + 12*x*y + 12*y**2 - 34, permute=True) == soln
941
+
942
+
943
+ @XFAIL
944
+ def test_not_implemented():
945
+ eq = x**2 + y**4 - 1**2 - 3**4
946
+ assert diophantine(eq, syms=[x, y]) == {(9, 1), (1, 3)}
947
+
948
+
949
+ def test_issue_9538():
950
+ eq = x - 3*y + 2
951
+ assert diophantine(eq, syms=[y,x]) == {(t_0, 3*t_0 - 2)}
952
+ raises(TypeError, lambda: diophantine(eq, syms={y, x}))
953
+
954
+
955
+ def test_ternary_quadratic():
956
+ # solution with 3 parameters
957
+ s = diophantine(2*x**2 + y**2 - 2*z**2)
958
+ p, q, r = ordered(S(s).free_symbols)
959
+ assert s == {(
960
+ p**2 - 2*q**2,
961
+ -2*p**2 + 4*p*q - 4*p*r - 4*q**2,
962
+ p**2 - 4*p*q + 2*q**2 - 4*q*r)}
963
+ # solution with Mul in solution
964
+ s = diophantine(x**2 + 2*y**2 - 2*z**2)
965
+ assert s == {(4*p*q, p**2 - 2*q**2, p**2 + 2*q**2)}
966
+ # solution with no Mul in solution
967
+ s = diophantine(2*x**2 + 2*y**2 - z**2)
968
+ assert s == {(2*p**2 - q**2, -2*p**2 + 4*p*q - q**2,
969
+ 4*p**2 - 4*p*q + 2*q**2)}
970
+ # reduced form when parametrized
971
+ s = diophantine(3*x**2 + 72*y**2 - 27*z**2)
972
+ assert s == {(24*p**2 - 9*q**2, 6*p*q, 8*p**2 + 3*q**2)}
973
+ assert parametrize_ternary_quadratic(
974
+ 3*x**2 + 2*y**2 - z**2 - 2*x*y + 5*y*z - 7*y*z) == (
975
+ 2*p**2 - 2*p*q - q**2, 2*p**2 + 2*p*q - q**2, 2*p**2 -
976
+ 2*p*q + 3*q**2)
977
+ assert parametrize_ternary_quadratic(
978
+ 124*x**2 - 30*y**2 - 7729*z**2) == (
979
+ -1410*p**2 - 363263*q**2, 2700*p**2 + 30916*p*q -
980
+ 695610*q**2, -60*p**2 + 5400*p*q + 15458*q**2)
981
+
982
+
983
+ def test_diophantine_solution_set():
984
+ s1 = DiophantineSolutionSet([], [])
985
+ assert set(s1) == set()
986
+ assert s1.symbols == ()
987
+ assert s1.parameters == ()
988
+ raises(ValueError, lambda: s1.add((x,)))
989
+ assert list(s1.dict_iterator()) == []
990
+
991
+ s2 = DiophantineSolutionSet([x, y], [t, u])
992
+ assert s2.symbols == (x, y)
993
+ assert s2.parameters == (t, u)
994
+ raises(ValueError, lambda: s2.add((1,)))
995
+ s2.add((3, 4))
996
+ assert set(s2) == {(3, 4)}
997
+ s2.update((3, 4), (-1, u))
998
+ assert set(s2) == {(3, 4), (-1, u)}
999
+ raises(ValueError, lambda: s1.update(s2))
1000
+ assert list(s2.dict_iterator()) == [{x: -1, y: u}, {x: 3, y: 4}]
1001
+
1002
+ s3 = DiophantineSolutionSet([x, y, z], [t, u])
1003
+ assert len(s3.parameters) == 2
1004
+ s3.add((t**2 + u, t - u, 1))
1005
+ assert set(s3) == {(t**2 + u, t - u, 1)}
1006
+ assert s3.subs(t, 2) == {(u + 4, 2 - u, 1)}
1007
+ assert s3(2) == {(u + 4, 2 - u, 1)}
1008
+ assert s3.subs({t: 7, u: 8}) == {(57, -1, 1)}
1009
+ assert s3(7, 8) == {(57, -1, 1)}
1010
+ assert s3.subs({t: 5}) == {(u + 25, 5 - u, 1)}
1011
+ assert s3(5) == {(u + 25, 5 - u, 1)}
1012
+ assert s3.subs(u, -3) == {(t**2 - 3, t + 3, 1)}
1013
+ assert s3(None, -3) == {(t**2 - 3, t + 3, 1)}
1014
+ assert s3.subs({t: 2, u: 8}) == {(12, -6, 1)}
1015
+ assert s3(2, 8) == {(12, -6, 1)}
1016
+ assert s3.subs({t: 5, u: -3}) == {(22, 8, 1)}
1017
+ assert s3(5, -3) == {(22, 8, 1)}
1018
+ raises(ValueError, lambda: s3.subs(x=1))
1019
+ raises(ValueError, lambda: s3.subs(1, 2, 3))
1020
+ raises(ValueError, lambda: s3.add(()))
1021
+ raises(ValueError, lambda: s3.add((1, 2, 3, 4)))
1022
+ raises(ValueError, lambda: s3.add((1, 2)))
1023
+ raises(ValueError, lambda: s3(1, 2, 3))
1024
+ raises(TypeError, lambda: s3(t=1))
1025
+
1026
+ s4 = DiophantineSolutionSet([x, y], [t, u])
1027
+ s4.add((t, 11*t))
1028
+ s4.add((-t, 22*t))
1029
+ assert s4(0, 0) == {(0, 0)}
1030
+
1031
+
1032
+ def test_quadratic_parameter_passing():
1033
+ eq = -33*x*y + 3*y**2
1034
+ solution = BinaryQuadratic(eq).solve(parameters=[t, u])
1035
+ # test that parameters are passed all the way to the final solution
1036
+ assert solution == {(t, 11*t), (-t, 22*t)}
1037
+ assert solution(0, 0) == {(0, 0)}
env-llmeval/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
+ ]
env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (599 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/hypergeometric.cpython-310.pyc ADDED
Binary file (7.07 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/lie_group.cpython-310.pyc ADDED
Binary file (30.8 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/nonhomogeneous.cpython-310.pyc ADDED
Binary file (14.8 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/ode.cpython-310.pyc ADDED
Binary file (121 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/riccati.cpython-310.pyc ADDED
Binary file (24.4 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/single.cpython-310.pyc ADDED
Binary file (105 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/subscheck.cpython-310.pyc ADDED
Binary file (12.2 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/systems.cpython-310.pyc ADDED
Binary file (66.9 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/hypergeometric.py ADDED
@@ -0,0 +1,272 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r'''
2
+ This module contains the implementation of the 2nd_hypergeometric hint for
3
+ dsolve. This is an incomplete implementation of the algorithm described in [1].
4
+ The algorithm solves 2nd order linear ODEs of the form
5
+
6
+ .. math:: y'' + A(x) y' + B(x) y = 0\text{,}
7
+
8
+ where `A` and `B` are rational functions. The algorithm should find any
9
+ solution of the form
10
+
11
+ .. math:: y = P(x) _pF_q(..; ..;\frac{\alpha x^k + \beta}{\gamma x^k + \delta})\text{,}
12
+
13
+ where pFq is any of 2F1, 1F1 or 0F1 and `P` is an "arbitrary function".
14
+ Currently only the 2F1 case is implemented in SymPy but the other cases are
15
+ described in the paper and could be implemented in future (contributions
16
+ welcome!).
17
+
18
+ References
19
+ ==========
20
+
21
+ .. [1] L. Chan, E.S. Cheb-Terrab, Non-Liouvillian solutions for second order
22
+ linear ODEs, (2004).
23
+ https://arxiv.org/abs/math-ph/0402063
24
+ '''
25
+
26
+ from sympy.core import S, Pow
27
+ from sympy.core.function import expand
28
+ from sympy.core.relational import Eq
29
+ from sympy.core.symbol import Symbol, Wild
30
+ from sympy.functions import exp, sqrt, hyper
31
+ from sympy.integrals import Integral
32
+ from sympy.polys import roots, gcd
33
+ from sympy.polys.polytools import cancel, factor
34
+ from sympy.simplify import collect, simplify, logcombine # type: ignore
35
+ from sympy.simplify.powsimp import powdenest
36
+ from sympy.solvers.ode.ode import get_numbered_constants
37
+
38
+
39
+ def match_2nd_hypergeometric(eq, func):
40
+ x = func.args[0]
41
+ df = func.diff(x)
42
+ a3 = Wild('a3', exclude=[func, func.diff(x), func.diff(x, 2)])
43
+ b3 = Wild('b3', exclude=[func, func.diff(x), func.diff(x, 2)])
44
+ c3 = Wild('c3', exclude=[func, func.diff(x), func.diff(x, 2)])
45
+ deq = a3*(func.diff(x, 2)) + b3*df + c3*func
46
+ r = collect(eq,
47
+ [func.diff(x, 2), func.diff(x), func]).match(deq)
48
+ if r:
49
+ if not all(val.is_polynomial() for val in r.values()):
50
+ n, d = eq.as_numer_denom()
51
+ eq = expand(n)
52
+ r = collect(eq, [func.diff(x, 2), func.diff(x), func]).match(deq)
53
+
54
+ if r and r[a3]!=0:
55
+ A = cancel(r[b3]/r[a3])
56
+ B = cancel(r[c3]/r[a3])
57
+ return [A, B]
58
+ else:
59
+ return []
60
+
61
+
62
+ def equivalence_hypergeometric(A, B, func):
63
+ # This method for finding the equivalence is only for 2F1 type.
64
+ # We can extend it for 1F1 and 0F1 type also.
65
+ x = func.args[0]
66
+
67
+ # making given equation in normal form
68
+ I1 = factor(cancel(A.diff(x)/2 + A**2/4 - B))
69
+
70
+ # computing shifted invariant(J1) of the equation
71
+ J1 = factor(cancel(x**2*I1 + S(1)/4))
72
+ num, dem = J1.as_numer_denom()
73
+ num = powdenest(expand(num))
74
+ dem = powdenest(expand(dem))
75
+ # this function will compute the different powers of variable(x) in J1.
76
+ # then it will help in finding value of k. k is power of x such that we can express
77
+ # J1 = x**k * J0(x**k) then all the powers in J0 become integers.
78
+ def _power_counting(num):
79
+ _pow = {0}
80
+ for val in num:
81
+ if val.has(x):
82
+ if isinstance(val, Pow) and val.as_base_exp()[0] == x:
83
+ _pow.add(val.as_base_exp()[1])
84
+ elif val == x:
85
+ _pow.add(val.as_base_exp()[1])
86
+ else:
87
+ _pow.update(_power_counting(val.args))
88
+ return _pow
89
+
90
+ pow_num = _power_counting((num, ))
91
+ pow_dem = _power_counting((dem, ))
92
+ pow_dem.update(pow_num)
93
+
94
+ _pow = pow_dem
95
+ k = gcd(_pow)
96
+
97
+ # computing I0 of the given equation
98
+ I0 = powdenest(simplify(factor(((J1/k**2) - S(1)/4)/((x**k)**2))), force=True)
99
+ I0 = factor(cancel(powdenest(I0.subs(x, x**(S(1)/k)), force=True)))
100
+
101
+ # Before this point I0, J1 might be functions of e.g. sqrt(x) but replacing
102
+ # x with x**(1/k) should result in I0 being a rational function of x or
103
+ # otherwise the hypergeometric solver cannot be used. Note that k can be a
104
+ # non-integer rational such as 2/7.
105
+ if not I0.is_rational_function(x):
106
+ return None
107
+
108
+ num, dem = I0.as_numer_denom()
109
+
110
+ max_num_pow = max(_power_counting((num, )))
111
+ dem_args = dem.args
112
+ sing_point = []
113
+ dem_pow = []
114
+ # calculating singular point of I0.
115
+ for arg in dem_args:
116
+ if arg.has(x):
117
+ if isinstance(arg, Pow):
118
+ # (x-a)**n
119
+ dem_pow.append(arg.as_base_exp()[1])
120
+ sing_point.append(list(roots(arg.as_base_exp()[0], x).keys())[0])
121
+ else:
122
+ # (x-a) type
123
+ dem_pow.append(arg.as_base_exp()[1])
124
+ sing_point.append(list(roots(arg, x).keys())[0])
125
+
126
+ dem_pow.sort()
127
+ # checking if equivalence is exists or not.
128
+
129
+ if equivalence(max_num_pow, dem_pow) == "2F1":
130
+ return {'I0':I0, 'k':k, 'sing_point':sing_point, 'type':"2F1"}
131
+ else:
132
+ return None
133
+
134
+
135
+ def match_2nd_2F1_hypergeometric(I, k, sing_point, func):
136
+ x = func.args[0]
137
+ a = Wild("a")
138
+ b = Wild("b")
139
+ c = Wild("c")
140
+ t = Wild("t")
141
+ s = Wild("s")
142
+ r = Wild("r")
143
+ alpha = Wild("alpha")
144
+ beta = Wild("beta")
145
+ gamma = Wild("gamma")
146
+ delta = Wild("delta")
147
+ # I0 of the standerd 2F1 equation.
148
+ I0 = ((a-b+1)*(a-b-1)*x**2 + 2*((1-a-b)*c + 2*a*b)*x + c*(c-2))/(4*x**2*(x-1)**2)
149
+ if sing_point != [0, 1]:
150
+ # If singular point is [0, 1] then we have standerd equation.
151
+ eqs = []
152
+ sing_eqs = [-beta/alpha, -delta/gamma, (delta-beta)/(alpha-gamma)]
153
+ # making equations for the finding the mobius transformation
154
+ for i in range(3):
155
+ if i<len(sing_point):
156
+ eqs.append(Eq(sing_eqs[i], sing_point[i]))
157
+ else:
158
+ eqs.append(Eq(1/sing_eqs[i], 0))
159
+ # solving above equations for the mobius transformation
160
+ _beta = -alpha*sing_point[0]
161
+ _delta = -gamma*sing_point[1]
162
+ _gamma = alpha
163
+ if len(sing_point) == 3:
164
+ _gamma = (_beta + sing_point[2]*alpha)/(sing_point[2] - sing_point[1])
165
+ mob = (alpha*x + beta)/(gamma*x + delta)
166
+ mob = mob.subs(beta, _beta)
167
+ mob = mob.subs(delta, _delta)
168
+ mob = mob.subs(gamma, _gamma)
169
+ mob = cancel(mob)
170
+ t = (beta - delta*x)/(gamma*x - alpha)
171
+ t = cancel(((t.subs(beta, _beta)).subs(delta, _delta)).subs(gamma, _gamma))
172
+ else:
173
+ mob = x
174
+ t = x
175
+
176
+ # applying mobius transformation in I to make it into I0.
177
+ I = I.subs(x, t)
178
+ I = I*(t.diff(x))**2
179
+ I = factor(I)
180
+ dict_I = {x**2:0, x:0, 1:0}
181
+ I0_num, I0_dem = I0.as_numer_denom()
182
+ # collecting coeff of (x**2, x), of the standerd equation.
183
+ # substituting (a-b) = s, (a+b) = r
184
+ dict_I0 = {x**2:s**2 - 1, x:(2*(1-r)*c + (r+s)*(r-s)), 1:c*(c-2)}
185
+ # collecting coeff of (x**2, x) from I0 of the given equation.
186
+ dict_I.update(collect(expand(cancel(I*I0_dem)), [x**2, x], evaluate=False))
187
+ eqs = []
188
+ # We are comparing the coeff of powers of different x, for finding the values of
189
+ # parameters of standerd equation.
190
+ for key in [x**2, x, 1]:
191
+ eqs.append(Eq(dict_I[key], dict_I0[key]))
192
+
193
+ # We can have many possible roots for the equation.
194
+ # I am selecting the root on the basis that when we have
195
+ # standard equation eq = x*(x-1)*f(x).diff(x, 2) + ((a+b+1)*x-c)*f(x).diff(x) + a*b*f(x)
196
+ # then root should be a, b, c.
197
+
198
+ _c = 1 - factor(sqrt(1+eqs[2].lhs))
199
+ if not _c.has(Symbol):
200
+ _c = min(list(roots(eqs[2], c)))
201
+ _s = factor(sqrt(eqs[0].lhs + 1))
202
+ _r = _c - factor(sqrt(_c**2 + _s**2 + eqs[1].lhs - 2*_c))
203
+ _a = (_r + _s)/2
204
+ _b = (_r - _s)/2
205
+
206
+ rn = {'a':simplify(_a), 'b':simplify(_b), 'c':simplify(_c), 'k':k, 'mobius':mob, 'type':"2F1"}
207
+ return rn
208
+
209
+
210
+ def equivalence(max_num_pow, dem_pow):
211
+ # this function is made for checking the equivalence with 2F1 type of equation.
212
+ # max_num_pow is the value of maximum power of x in numerator
213
+ # and dem_pow is list of powers of different factor of form (a*x b).
214
+ # reference from table 1 in paper - "Non-Liouvillian solutions for second order
215
+ # linear ODEs" by L. Chan, E.S. Cheb-Terrab.
216
+ # We can extend it for 1F1 and 0F1 type also.
217
+
218
+ if max_num_pow == 2:
219
+ if dem_pow in [[2, 2], [2, 2, 2]]:
220
+ return "2F1"
221
+ elif max_num_pow == 1:
222
+ if dem_pow in [[1, 2, 2], [2, 2, 2], [1, 2], [2, 2]]:
223
+ return "2F1"
224
+ elif max_num_pow == 0:
225
+ if dem_pow in [[1, 1, 2], [2, 2], [1, 2, 2], [1, 1], [2], [1, 2], [2, 2]]:
226
+ return "2F1"
227
+
228
+ return None
229
+
230
+
231
+ def get_sol_2F1_hypergeometric(eq, func, match_object):
232
+ x = func.args[0]
233
+ from sympy.simplify.hyperexpand import hyperexpand
234
+ from sympy.polys.polytools import factor
235
+ C0, C1 = get_numbered_constants(eq, num=2)
236
+ a = match_object['a']
237
+ b = match_object['b']
238
+ c = match_object['c']
239
+ A = match_object['A']
240
+
241
+ sol = None
242
+
243
+ if c.is_integer == False:
244
+ sol = C0*hyper([a, b], [c], x) + C1*hyper([a-c+1, b-c+1], [2-c], x)*x**(1-c)
245
+ elif c == 1:
246
+ y2 = Integral(exp(Integral((-(a+b+1)*x + c)/(x**2-x), x))/(hyperexpand(hyper([a, b], [c], x))**2), x)*hyper([a, b], [c], x)
247
+ sol = C0*hyper([a, b], [c], x) + C1*y2
248
+ elif (c-a-b).is_integer == False:
249
+ sol = C0*hyper([a, b], [1+a+b-c], 1-x) + C1*hyper([c-a, c-b], [1+c-a-b], 1-x)*(1-x)**(c-a-b)
250
+
251
+ if sol:
252
+ # applying transformation in the solution
253
+ subs = match_object['mobius']
254
+ dtdx = simplify(1/(subs.diff(x)))
255
+ _B = ((a + b + 1)*x - c).subs(x, subs)*dtdx
256
+ _B = factor(_B + ((x**2 -x).subs(x, subs))*(dtdx.diff(x)*dtdx))
257
+ _A = factor((x**2 - x).subs(x, subs)*(dtdx**2))
258
+ e = exp(logcombine(Integral(cancel(_B/(2*_A)), x), force=True))
259
+ sol = sol.subs(x, match_object['mobius'])
260
+ sol = sol.subs(x, x**match_object['k'])
261
+ e = e.subs(x, x**match_object['k'])
262
+
263
+ if not A.is_zero:
264
+ e1 = Integral(A/2, x)
265
+ e1 = exp(logcombine(e1, force=True))
266
+ sol = cancel((e/e1)*x**((-match_object['k']+1)/2))*sol
267
+ sol = Eq(func, sol)
268
+ return sol
269
+
270
+ sol = cancel((e)*x**((-match_object['k']+1)/2))*sol
271
+ sol = Eq(func, sol)
272
+ return sol
env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/lie_group.py ADDED
@@ -0,0 +1,1101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""
2
+ This module contains the implementation of the internal helper functions for the lie_group hint for
3
+ dsolve. These helper functions apply different heuristics on the given equation
4
+ and return the solution. These functions are used by :py:meth:`sympy.solvers.ode.single.LieGroup`
5
+
6
+ References
7
+ =========
8
+
9
+ - `abaco1_simple`, `function_sum` and `chi` are referenced from E.S Cheb-Terrab, L.G.S Duarte
10
+ and L.A,C.P da Mota, Computer Algebra Solving of First Order ODEs Using
11
+ Symmetry Methods, pp. 7 - pp. 8
12
+
13
+ - `abaco1_product`, `abaco2_similar`, `abaco2_unique_unknown`, `linear` and `abaco2_unique_general`
14
+ are referenced from E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
15
+ ODE Patterns, pp. 7 - pp. 12
16
+
17
+ - `bivariate` from Lie Groups and Differential Equations pp. 327 - pp. 329
18
+
19
+ """
20
+ from itertools import islice
21
+
22
+ from sympy.core import Add, S, Mul, Pow
23
+ from sympy.core.exprtools import factor_terms
24
+ from sympy.core.function import Function, AppliedUndef, expand
25
+ from sympy.core.relational import Equality, Eq
26
+ from sympy.core.symbol import Symbol, Wild, Dummy, symbols
27
+ from sympy.functions import exp, log
28
+ from sympy.integrals.integrals import integrate
29
+ from sympy.polys import Poly
30
+ from sympy.polys.polytools import cancel, div
31
+ from sympy.simplify import (collect, powsimp, # type: ignore
32
+ separatevars, simplify)
33
+ from sympy.solvers import solve
34
+ from sympy.solvers.pde import pdsolve
35
+
36
+ from sympy.utilities import numbered_symbols
37
+ from sympy.solvers.deutils import _preprocess, ode_order
38
+ from .ode import checkinfsol
39
+
40
+
41
+ lie_heuristics = (
42
+ "abaco1_simple",
43
+ "abaco1_product",
44
+ "abaco2_similar",
45
+ "abaco2_unique_unknown",
46
+ "abaco2_unique_general",
47
+ "linear",
48
+ "function_sum",
49
+ "bivariate",
50
+ "chi"
51
+ )
52
+
53
+
54
+ def _ode_lie_group_try_heuristic(eq, heuristic, func, match, inf):
55
+
56
+ xi = Function("xi")
57
+ eta = Function("eta")
58
+ f = func.func
59
+ x = func.args[0]
60
+ y = match['y']
61
+ h = match['h']
62
+ tempsol = []
63
+ if not inf:
64
+ try:
65
+ inf = infinitesimals(eq, hint=heuristic, func=func, order=1, match=match)
66
+ except ValueError:
67
+ return None
68
+ for infsim in inf:
69
+ xiinf = (infsim[xi(x, func)]).subs(func, y)
70
+ etainf = (infsim[eta(x, func)]).subs(func, y)
71
+ # This condition creates recursion while using pdsolve.
72
+ # Since the first step while solving a PDE of form
73
+ # a*(f(x, y).diff(x)) + b*(f(x, y).diff(y)) + c = 0
74
+ # is to solve the ODE dy/dx = b/a
75
+ if simplify(etainf/xiinf) == h:
76
+ continue
77
+ rpde = f(x, y).diff(x)*xiinf + f(x, y).diff(y)*etainf
78
+ r = pdsolve(rpde, func=f(x, y)).rhs
79
+ s = pdsolve(rpde - 1, func=f(x, y)).rhs
80
+ newcoord = [_lie_group_remove(coord) for coord in [r, s]]
81
+ r = Dummy("r")
82
+ s = Dummy("s")
83
+ C1 = Symbol("C1")
84
+ rcoord = newcoord[0]
85
+ scoord = newcoord[-1]
86
+ try:
87
+ sol = solve([r - rcoord, s - scoord], x, y, dict=True)
88
+ if sol == []:
89
+ continue
90
+ except NotImplementedError:
91
+ continue
92
+ else:
93
+ sol = sol[0]
94
+ xsub = sol[x]
95
+ ysub = sol[y]
96
+ num = simplify(scoord.diff(x) + scoord.diff(y)*h)
97
+ denom = simplify(rcoord.diff(x) + rcoord.diff(y)*h)
98
+ if num and denom:
99
+ diffeq = simplify((num/denom).subs([(x, xsub), (y, ysub)]))
100
+ sep = separatevars(diffeq, symbols=[r, s], dict=True)
101
+ if sep:
102
+ # Trying to separate, r and s coordinates
103
+ deq = integrate((1/sep[s]), s) + C1 - integrate(sep['coeff']*sep[r], r)
104
+ # Substituting and reverting back to original coordinates
105
+ deq = deq.subs([(r, rcoord), (s, scoord)])
106
+ try:
107
+ sdeq = solve(deq, y)
108
+ except NotImplementedError:
109
+ tempsol.append(deq)
110
+ else:
111
+ return [Eq(f(x), sol) for sol in sdeq]
112
+
113
+
114
+ elif denom: # (ds/dr) is zero which means s is constant
115
+ return [Eq(f(x), solve(scoord - C1, y)[0])]
116
+
117
+ elif num: # (dr/ds) is zero which means r is constant
118
+ return [Eq(f(x), solve(rcoord - C1, y)[0])]
119
+
120
+ # If nothing works, return solution as it is, without solving for y
121
+ if tempsol:
122
+ return [Eq(sol.subs(y, f(x)), 0) for sol in tempsol]
123
+ return None
124
+
125
+
126
+ def _ode_lie_group( s, func, order, match):
127
+
128
+ heuristics = lie_heuristics
129
+ inf = {}
130
+ f = func.func
131
+ x = func.args[0]
132
+ df = func.diff(x)
133
+ xi = Function("xi")
134
+ eta = Function("eta")
135
+ xis = match['xi']
136
+ etas = match['eta']
137
+ y = match.pop('y', None)
138
+ if y:
139
+ h = -simplify(match[match['d']]/match[match['e']])
140
+ y = y
141
+ else:
142
+ y = Dummy("y")
143
+ h = s.subs(func, y)
144
+
145
+ if xis is not None and etas is not None:
146
+ inf = [{xi(x, f(x)): S(xis), eta(x, f(x)): S(etas)}]
147
+
148
+ if checkinfsol(Eq(df, s), inf, func=f(x), order=1)[0][0]:
149
+ heuristics = ["user_defined"] + list(heuristics)
150
+
151
+ match = {'h': h, 'y': y}
152
+
153
+ # This is done so that if any heuristic raises a ValueError
154
+ # another heuristic can be used.
155
+ sol = None
156
+ for heuristic in heuristics:
157
+ sol = _ode_lie_group_try_heuristic(Eq(df, s), heuristic, func, match, inf)
158
+ if sol:
159
+ return sol
160
+ return sol
161
+
162
+
163
+ def infinitesimals(eq, func=None, order=None, hint='default', match=None):
164
+ r"""
165
+ The infinitesimal functions of an ordinary differential equation, `\xi(x,y)`
166
+ and `\eta(x,y)`, are the infinitesimals of the Lie group of point transformations
167
+ for which the differential equation is invariant. So, the ODE `y'=f(x,y)`
168
+ would admit a Lie group `x^*=X(x,y;\varepsilon)=x+\varepsilon\xi(x,y)`,
169
+ `y^*=Y(x,y;\varepsilon)=y+\varepsilon\eta(x,y)` such that `(y^*)'=f(x^*, y^*)`.
170
+ A change of coordinates, to `r(x,y)` and `s(x,y)`, can be performed so this Lie group
171
+ becomes the translation group, `r^*=r` and `s^*=s+\varepsilon`.
172
+ They are tangents to the coordinate curves of the new system.
173
+
174
+ Consider the transformation `(x, y) \to (X, Y)` such that the
175
+ differential equation remains invariant. `\xi` and `\eta` are the tangents to
176
+ the transformed coordinates `X` and `Y`, at `\varepsilon=0`.
177
+
178
+ .. math:: \left(\frac{\partial X(x,y;\varepsilon)}{\partial\varepsilon
179
+ }\right)|_{\varepsilon=0} = \xi,
180
+ \left(\frac{\partial Y(x,y;\varepsilon)}{\partial\varepsilon
181
+ }\right)|_{\varepsilon=0} = \eta,
182
+
183
+ The infinitesimals can be found by solving the following PDE:
184
+
185
+ >>> from sympy import Function, Eq, pprint
186
+ >>> from sympy.abc import x, y
187
+ >>> xi, eta, h = map(Function, ['xi', 'eta', 'h'])
188
+ >>> h = h(x, y) # dy/dx = h
189
+ >>> eta = eta(x, y)
190
+ >>> xi = xi(x, y)
191
+ >>> genform = Eq(eta.diff(x) + (eta.diff(y) - xi.diff(x))*h
192
+ ... - (xi.diff(y))*h**2 - xi*(h.diff(x)) - eta*(h.diff(y)), 0)
193
+ >>> pprint(genform)
194
+ /d d \ d 2 d
195
+ |--(eta(x, y)) - --(xi(x, y))|*h(x, y) - eta(x, y)*--(h(x, y)) - h (x, y)*--(x
196
+ \dy dx / dy dy
197
+ <BLANKLINE>
198
+ d d
199
+ i(x, y)) - xi(x, y)*--(h(x, y)) + --(eta(x, y)) = 0
200
+ dx dx
201
+
202
+ Solving the above mentioned PDE is not trivial, and can be solved only by
203
+ making intelligent assumptions for `\xi` and `\eta` (heuristics). Once an
204
+ infinitesimal is found, the attempt to find more heuristics stops. This is done to
205
+ optimise the speed of solving the differential equation. If a list of all the
206
+ infinitesimals is needed, ``hint`` should be flagged as ``all``, which gives
207
+ the complete list of infinitesimals. If the infinitesimals for a particular
208
+ heuristic needs to be found, it can be passed as a flag to ``hint``.
209
+
210
+ Examples
211
+ ========
212
+
213
+ >>> from sympy import Function
214
+ >>> from sympy.solvers.ode.lie_group import infinitesimals
215
+ >>> from sympy.abc import x
216
+ >>> f = Function('f')
217
+ >>> eq = f(x).diff(x) - x**2*f(x)
218
+ >>> infinitesimals(eq)
219
+ [{eta(x, f(x)): exp(x**3/3), xi(x, f(x)): 0}]
220
+
221
+ References
222
+ ==========
223
+
224
+ - Solving differential equations by Symmetry Groups,
225
+ John Starrett, pp. 1 - pp. 14
226
+
227
+ """
228
+
229
+ if isinstance(eq, Equality):
230
+ eq = eq.lhs - eq.rhs
231
+ if not func:
232
+ eq, func = _preprocess(eq)
233
+ variables = func.args
234
+ if len(variables) != 1:
235
+ raise ValueError("ODE's have only one independent variable")
236
+ else:
237
+ x = variables[0]
238
+ if not order:
239
+ order = ode_order(eq, func)
240
+ if order != 1:
241
+ raise NotImplementedError("Infinitesimals for only "
242
+ "first order ODE's have been implemented")
243
+ else:
244
+ df = func.diff(x)
245
+ # Matching differential equation of the form a*df + b
246
+ a = Wild('a', exclude = [df])
247
+ b = Wild('b', exclude = [df])
248
+ if match: # Used by lie_group hint
249
+ h = match['h']
250
+ y = match['y']
251
+ else:
252
+ match = collect(expand(eq), df).match(a*df + b)
253
+ if match:
254
+ h = -simplify(match[b]/match[a])
255
+ else:
256
+ try:
257
+ sol = solve(eq, df)
258
+ except NotImplementedError:
259
+ raise NotImplementedError("Infinitesimals for the "
260
+ "first order ODE could not be found")
261
+ else:
262
+ h = sol[0] # Find infinitesimals for one solution
263
+ y = Dummy("y")
264
+ h = h.subs(func, y)
265
+
266
+ u = Dummy("u")
267
+ hx = h.diff(x)
268
+ hy = h.diff(y)
269
+ hinv = ((1/h).subs([(x, u), (y, x)])).subs(u, y) # Inverse ODE
270
+ match = {'h': h, 'func': func, 'hx': hx, 'hy': hy, 'y': y, 'hinv': hinv}
271
+ if hint == 'all':
272
+ xieta = []
273
+ for heuristic in lie_heuristics:
274
+ function = globals()['lie_heuristic_' + heuristic]
275
+ inflist = function(match, comp=True)
276
+ if inflist:
277
+ xieta.extend([inf for inf in inflist if inf not in xieta])
278
+ if xieta:
279
+ return xieta
280
+ else:
281
+ raise NotImplementedError("Infinitesimals could not be found for "
282
+ "the given ODE")
283
+
284
+ elif hint == 'default':
285
+ for heuristic in lie_heuristics:
286
+ function = globals()['lie_heuristic_' + heuristic]
287
+ xieta = function(match, comp=False)
288
+ if xieta:
289
+ return xieta
290
+
291
+ raise NotImplementedError("Infinitesimals could not be found for"
292
+ " the given ODE")
293
+
294
+ elif hint not in lie_heuristics:
295
+ raise ValueError("Heuristic not recognized: " + hint)
296
+
297
+ else:
298
+ function = globals()['lie_heuristic_' + hint]
299
+ xieta = function(match, comp=True)
300
+ if xieta:
301
+ return xieta
302
+ else:
303
+ raise ValueError("Infinitesimals could not be found using the"
304
+ " given heuristic")
305
+
306
+
307
+ def lie_heuristic_abaco1_simple(match, comp=False):
308
+ r"""
309
+ The first heuristic uses the following four sets of
310
+ assumptions on `\xi` and `\eta`
311
+
312
+ .. math:: \xi = 0, \eta = f(x)
313
+
314
+ .. math:: \xi = 0, \eta = f(y)
315
+
316
+ .. math:: \xi = f(x), \eta = 0
317
+
318
+ .. math:: \xi = f(y), \eta = 0
319
+
320
+ The success of this heuristic is determined by algebraic factorisation.
321
+ For the first assumption `\xi = 0` and `\eta` to be a function of `x`, the PDE
322
+
323
+ .. math:: \frac{\partial \eta}{\partial x} + (\frac{\partial \eta}{\partial y}
324
+ - \frac{\partial \xi}{\partial x})*h
325
+ - \frac{\partial \xi}{\partial y}*h^{2}
326
+ - \xi*\frac{\partial h}{\partial x} - \eta*\frac{\partial h}{\partial y} = 0
327
+
328
+ reduces to `f'(x) - f\frac{\partial h}{\partial y} = 0`
329
+ If `\frac{\partial h}{\partial y}` is a function of `x`, then this can usually
330
+ be integrated easily. A similar idea is applied to the other 3 assumptions as well.
331
+
332
+
333
+ References
334
+ ==========
335
+
336
+ - E.S Cheb-Terrab, L.G.S Duarte and L.A,C.P da Mota, Computer Algebra
337
+ Solving of First Order ODEs Using Symmetry Methods, pp. 8
338
+
339
+
340
+ """
341
+
342
+ xieta = []
343
+ y = match['y']
344
+ h = match['h']
345
+ func = match['func']
346
+ x = func.args[0]
347
+ hx = match['hx']
348
+ hy = match['hy']
349
+ xi = Function('xi')(x, func)
350
+ eta = Function('eta')(x, func)
351
+
352
+ hysym = hy.free_symbols
353
+ if y not in hysym:
354
+ try:
355
+ fx = exp(integrate(hy, x))
356
+ except NotImplementedError:
357
+ pass
358
+ else:
359
+ inf = {xi: S.Zero, eta: fx}
360
+ if not comp:
361
+ return [inf]
362
+ if comp and inf not in xieta:
363
+ xieta.append(inf)
364
+
365
+ factor = hy/h
366
+ facsym = factor.free_symbols
367
+ if x not in facsym:
368
+ try:
369
+ fy = exp(integrate(factor, y))
370
+ except NotImplementedError:
371
+ pass
372
+ else:
373
+ inf = {xi: S.Zero, eta: fy.subs(y, func)}
374
+ if not comp:
375
+ return [inf]
376
+ if comp and inf not in xieta:
377
+ xieta.append(inf)
378
+
379
+ factor = -hx/h
380
+ facsym = factor.free_symbols
381
+ if y not in facsym:
382
+ try:
383
+ fx = exp(integrate(factor, x))
384
+ except NotImplementedError:
385
+ pass
386
+ else:
387
+ inf = {xi: fx, eta: S.Zero}
388
+ if not comp:
389
+ return [inf]
390
+ if comp and inf not in xieta:
391
+ xieta.append(inf)
392
+
393
+ factor = -hx/(h**2)
394
+ facsym = factor.free_symbols
395
+ if x not in facsym:
396
+ try:
397
+ fy = exp(integrate(factor, y))
398
+ except NotImplementedError:
399
+ pass
400
+ else:
401
+ inf = {xi: fy.subs(y, func), eta: S.Zero}
402
+ if not comp:
403
+ return [inf]
404
+ if comp and inf not in xieta:
405
+ xieta.append(inf)
406
+
407
+ if xieta:
408
+ return xieta
409
+
410
+ def lie_heuristic_abaco1_product(match, comp=False):
411
+ r"""
412
+ The second heuristic uses the following two assumptions on `\xi` and `\eta`
413
+
414
+ .. math:: \eta = 0, \xi = f(x)*g(y)
415
+
416
+ .. math:: \eta = f(x)*g(y), \xi = 0
417
+
418
+ The first assumption of this heuristic holds good if
419
+ `\frac{1}{h^{2}}\frac{\partial^2}{\partial x \partial y}\log(h)` is
420
+ separable in `x` and `y`, then the separated factors containing `x`
421
+ is `f(x)`, and `g(y)` is obtained by
422
+
423
+ .. math:: e^{\int f\frac{\partial}{\partial x}\left(\frac{1}{f*h}\right)\,dy}
424
+
425
+ provided `f\frac{\partial}{\partial x}\left(\frac{1}{f*h}\right)` is a function
426
+ of `y` only.
427
+
428
+ The second assumption holds good if `\frac{dy}{dx} = h(x, y)` is rewritten as
429
+ `\frac{dy}{dx} = \frac{1}{h(y, x)}` and the same properties of the first assumption
430
+ satisfies. After obtaining `f(x)` and `g(y)`, the coordinates are again
431
+ interchanged, to get `\eta` as `f(x)*g(y)`
432
+
433
+
434
+ References
435
+ ==========
436
+ - E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
437
+ ODE Patterns, pp. 7 - pp. 8
438
+
439
+ """
440
+
441
+ xieta = []
442
+ y = match['y']
443
+ h = match['h']
444
+ hinv = match['hinv']
445
+ func = match['func']
446
+ x = func.args[0]
447
+ xi = Function('xi')(x, func)
448
+ eta = Function('eta')(x, func)
449
+
450
+
451
+ inf = separatevars(((log(h).diff(y)).diff(x))/h**2, dict=True, symbols=[x, y])
452
+ if inf and inf['coeff']:
453
+ fx = inf[x]
454
+ gy = simplify(fx*((1/(fx*h)).diff(x)))
455
+ gysyms = gy.free_symbols
456
+ if x not in gysyms:
457
+ gy = exp(integrate(gy, y))
458
+ inf = {eta: S.Zero, xi: (fx*gy).subs(y, func)}
459
+ if not comp:
460
+ return [inf]
461
+ if comp and inf not in xieta:
462
+ xieta.append(inf)
463
+
464
+ u1 = Dummy("u1")
465
+ inf = separatevars(((log(hinv).diff(y)).diff(x))/hinv**2, dict=True, symbols=[x, y])
466
+ if inf and inf['coeff']:
467
+ fx = inf[x]
468
+ gy = simplify(fx*((1/(fx*hinv)).diff(x)))
469
+ gysyms = gy.free_symbols
470
+ if x not in gysyms:
471
+ gy = exp(integrate(gy, y))
472
+ etaval = fx*gy
473
+ etaval = (etaval.subs([(x, u1), (y, x)])).subs(u1, y)
474
+ inf = {eta: etaval.subs(y, func), xi: S.Zero}
475
+ if not comp:
476
+ return [inf]
477
+ if comp and inf not in xieta:
478
+ xieta.append(inf)
479
+
480
+ if xieta:
481
+ return xieta
482
+
483
+ def lie_heuristic_bivariate(match, comp=False):
484
+ r"""
485
+ The third heuristic assumes the infinitesimals `\xi` and `\eta`
486
+ to be bi-variate polynomials in `x` and `y`. The assumption made here
487
+ for the logic below is that `h` is a rational function in `x` and `y`
488
+ though that may not be necessary for the infinitesimals to be
489
+ bivariate polynomials. The coefficients of the infinitesimals
490
+ are found out by substituting them in the PDE and grouping similar terms
491
+ that are polynomials and since they form a linear system, solve and check
492
+ for non trivial solutions. The degree of the assumed bivariates
493
+ are increased till a certain maximum value.
494
+
495
+ References
496
+ ==========
497
+ - Lie Groups and Differential Equations
498
+ pp. 327 - pp. 329
499
+
500
+ """
501
+
502
+ h = match['h']
503
+ hx = match['hx']
504
+ hy = match['hy']
505
+ func = match['func']
506
+ x = func.args[0]
507
+ y = match['y']
508
+ xi = Function('xi')(x, func)
509
+ eta = Function('eta')(x, func)
510
+
511
+ if h.is_rational_function():
512
+ # The maximum degree that the infinitesimals can take is
513
+ # calculated by this technique.
514
+ etax, etay, etad, xix, xiy, xid = symbols("etax etay etad xix xiy xid")
515
+ ipde = etax + (etay - xix)*h - xiy*h**2 - xid*hx - etad*hy
516
+ num, denom = cancel(ipde).as_numer_denom()
517
+ deg = Poly(num, x, y).total_degree()
518
+ deta = Function('deta')(x, y)
519
+ dxi = Function('dxi')(x, y)
520
+ ipde = (deta.diff(x) + (deta.diff(y) - dxi.diff(x))*h - (dxi.diff(y))*h**2
521
+ - dxi*hx - deta*hy)
522
+ xieq = Symbol("xi0")
523
+ etaeq = Symbol("eta0")
524
+
525
+ for i in range(deg + 1):
526
+ if i:
527
+ xieq += Add(*[
528
+ Symbol("xi_" + str(power) + "_" + str(i - power))*x**power*y**(i - power)
529
+ for power in range(i + 1)])
530
+ etaeq += Add(*[
531
+ Symbol("eta_" + str(power) + "_" + str(i - power))*x**power*y**(i - power)
532
+ for power in range(i + 1)])
533
+ pden, denom = (ipde.subs({dxi: xieq, deta: etaeq}).doit()).as_numer_denom()
534
+ pden = expand(pden)
535
+
536
+ # If the individual terms are monomials, the coefficients
537
+ # are grouped
538
+ if pden.is_polynomial(x, y) and pden.is_Add:
539
+ polyy = Poly(pden, x, y).as_dict()
540
+ if polyy:
541
+ symset = xieq.free_symbols.union(etaeq.free_symbols) - {x, y}
542
+ soldict = solve(polyy.values(), *symset)
543
+ if isinstance(soldict, list):
544
+ soldict = soldict[0]
545
+ if any(soldict.values()):
546
+ xired = xieq.subs(soldict)
547
+ etared = etaeq.subs(soldict)
548
+ # Scaling is done by substituting one for the parameters
549
+ # This can be any number except zero.
550
+ dict_ = {sym: 1 for sym in symset}
551
+ inf = {eta: etared.subs(dict_).subs(y, func),
552
+ xi: xired.subs(dict_).subs(y, func)}
553
+ return [inf]
554
+
555
+ def lie_heuristic_chi(match, comp=False):
556
+ r"""
557
+ The aim of the fourth heuristic is to find the function `\chi(x, y)`
558
+ that satisfies the PDE `\frac{d\chi}{dx} + h\frac{d\chi}{dx}
559
+ - \frac{\partial h}{\partial y}\chi = 0`.
560
+
561
+ This assumes `\chi` to be a bivariate polynomial in `x` and `y`. By intuition,
562
+ `h` should be a rational function in `x` and `y`. The method used here is
563
+ to substitute a general binomial for `\chi` up to a certain maximum degree
564
+ is reached. The coefficients of the polynomials, are calculated by by collecting
565
+ terms of the same order in `x` and `y`.
566
+
567
+ After finding `\chi`, the next step is to use `\eta = \xi*h + \chi`, to
568
+ determine `\xi` and `\eta`. This can be done by dividing `\chi` by `h`
569
+ which would give `-\xi` as the quotient and `\eta` as the remainder.
570
+
571
+
572
+ References
573
+ ==========
574
+ - E.S Cheb-Terrab, L.G.S Duarte and L.A,C.P da Mota, Computer Algebra
575
+ Solving of First Order ODEs Using Symmetry Methods, pp. 8
576
+
577
+ """
578
+
579
+ h = match['h']
580
+ hy = match['hy']
581
+ func = match['func']
582
+ x = func.args[0]
583
+ y = match['y']
584
+ xi = Function('xi')(x, func)
585
+ eta = Function('eta')(x, func)
586
+
587
+ if h.is_rational_function():
588
+ schi, schix, schiy = symbols("schi, schix, schiy")
589
+ cpde = schix + h*schiy - hy*schi
590
+ num, denom = cancel(cpde).as_numer_denom()
591
+ deg = Poly(num, x, y).total_degree()
592
+
593
+ chi = Function('chi')(x, y)
594
+ chix = chi.diff(x)
595
+ chiy = chi.diff(y)
596
+ cpde = chix + h*chiy - hy*chi
597
+ chieq = Symbol("chi")
598
+ for i in range(1, deg + 1):
599
+ chieq += Add(*[
600
+ Symbol("chi_" + str(power) + "_" + str(i - power))*x**power*y**(i - power)
601
+ for power in range(i + 1)])
602
+ cnum, cden = cancel(cpde.subs({chi : chieq}).doit()).as_numer_denom()
603
+ cnum = expand(cnum)
604
+ if cnum.is_polynomial(x, y) and cnum.is_Add:
605
+ cpoly = Poly(cnum, x, y).as_dict()
606
+ if cpoly:
607
+ solsyms = chieq.free_symbols - {x, y}
608
+ soldict = solve(cpoly.values(), *solsyms)
609
+ if isinstance(soldict, list):
610
+ soldict = soldict[0]
611
+ if any(soldict.values()):
612
+ chieq = chieq.subs(soldict)
613
+ dict_ = {sym: 1 for sym in solsyms}
614
+ chieq = chieq.subs(dict_)
615
+ # After finding chi, the main aim is to find out
616
+ # eta, xi by the equation eta = xi*h + chi
617
+ # One method to set xi, would be rearranging it to
618
+ # (eta/h) - xi = (chi/h). This would mean dividing
619
+ # chi by h would give -xi as the quotient and eta
620
+ # as the remainder. Thanks to Sean Vig for suggesting
621
+ # this method.
622
+ xic, etac = div(chieq, h)
623
+ inf = {eta: etac.subs(y, func), xi: -xic.subs(y, func)}
624
+ return [inf]
625
+
626
+ def lie_heuristic_function_sum(match, comp=False):
627
+ r"""
628
+ This heuristic uses the following two assumptions on `\xi` and `\eta`
629
+
630
+ .. math:: \eta = 0, \xi = f(x) + g(y)
631
+
632
+ .. math:: \eta = f(x) + g(y), \xi = 0
633
+
634
+ The first assumption of this heuristic holds good if
635
+
636
+ .. math:: \frac{\partial}{\partial y}[(h\frac{\partial^{2}}{
637
+ \partial x^{2}}(h^{-1}))^{-1}]
638
+
639
+ is separable in `x` and `y`,
640
+
641
+ 1. The separated factors containing `y` is `\frac{\partial g}{\partial y}`.
642
+ From this `g(y)` can be determined.
643
+ 2. The separated factors containing `x` is `f''(x)`.
644
+ 3. `h\frac{\partial^{2}}{\partial x^{2}}(h^{-1})` equals
645
+ `\frac{f''(x)}{f(x) + g(y)}`. From this `f(x)` can be determined.
646
+
647
+ The second assumption holds good if `\frac{dy}{dx} = h(x, y)` is rewritten as
648
+ `\frac{dy}{dx} = \frac{1}{h(y, x)}` and the same properties of the first
649
+ assumption satisfies. After obtaining `f(x)` and `g(y)`, the coordinates
650
+ are again interchanged, to get `\eta` as `f(x) + g(y)`.
651
+
652
+ For both assumptions, the constant factors are separated among `g(y)`
653
+ and `f''(x)`, such that `f''(x)` obtained from 3] is the same as that
654
+ obtained from 2]. If not possible, then this heuristic fails.
655
+
656
+
657
+ References
658
+ ==========
659
+ - E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
660
+ ODE Patterns, pp. 7 - pp. 8
661
+
662
+ """
663
+
664
+ xieta = []
665
+ h = match['h']
666
+ func = match['func']
667
+ hinv = match['hinv']
668
+ x = func.args[0]
669
+ y = match['y']
670
+ xi = Function('xi')(x, func)
671
+ eta = Function('eta')(x, func)
672
+
673
+ for odefac in [h, hinv]:
674
+ factor = odefac*((1/odefac).diff(x, 2))
675
+ sep = separatevars((1/factor).diff(y), dict=True, symbols=[x, y])
676
+ if sep and sep['coeff'] and sep[x].has(x) and sep[y].has(y):
677
+ k = Dummy("k")
678
+ try:
679
+ gy = k*integrate(sep[y], y)
680
+ except NotImplementedError:
681
+ pass
682
+ else:
683
+ fdd = 1/(k*sep[x]*sep['coeff'])
684
+ fx = simplify(fdd/factor - gy)
685
+ check = simplify(fx.diff(x, 2) - fdd)
686
+ if fx:
687
+ if not check:
688
+ fx = fx.subs(k, 1)
689
+ gy = (gy/k)
690
+ else:
691
+ sol = solve(check, k)
692
+ if sol:
693
+ sol = sol[0]
694
+ fx = fx.subs(k, sol)
695
+ gy = (gy/k)*sol
696
+ else:
697
+ continue
698
+ if odefac == hinv: # Inverse ODE
699
+ fx = fx.subs(x, y)
700
+ gy = gy.subs(y, x)
701
+ etaval = factor_terms(fx + gy)
702
+ if etaval.is_Mul:
703
+ etaval = Mul(*[arg for arg in etaval.args if arg.has(x, y)])
704
+ if odefac == hinv: # Inverse ODE
705
+ inf = {eta: etaval.subs(y, func), xi : S.Zero}
706
+ else:
707
+ inf = {xi: etaval.subs(y, func), eta : S.Zero}
708
+ if not comp:
709
+ return [inf]
710
+ else:
711
+ xieta.append(inf)
712
+
713
+ if xieta:
714
+ return xieta
715
+
716
+ def lie_heuristic_abaco2_similar(match, comp=False):
717
+ r"""
718
+ This heuristic uses the following two assumptions on `\xi` and `\eta`
719
+
720
+ .. math:: \eta = g(x), \xi = f(x)
721
+
722
+ .. math:: \eta = f(y), \xi = g(y)
723
+
724
+ For the first assumption,
725
+
726
+ 1. First `\frac{\frac{\partial h}{\partial y}}{\frac{\partial^{2} h}{
727
+ \partial yy}}` is calculated. Let us say this value is A
728
+
729
+ 2. If this is constant, then `h` is matched to the form `A(x) + B(x)e^{
730
+ \frac{y}{C}}` then, `\frac{e^{\int \frac{A(x)}{C} \,dx}}{B(x)}` gives `f(x)`
731
+ and `A(x)*f(x)` gives `g(x)`
732
+
733
+ 3. Otherwise `\frac{\frac{\partial A}{\partial X}}{\frac{\partial A}{
734
+ \partial Y}} = \gamma` is calculated. If
735
+
736
+ a] `\gamma` is a function of `x` alone
737
+
738
+ b] `\frac{\gamma\frac{\partial h}{\partial y} - \gamma'(x) - \frac{
739
+ \partial h}{\partial x}}{h + \gamma} = G` is a function of `x` alone.
740
+ then, `e^{\int G \,dx}` gives `f(x)` and `-\gamma*f(x)` gives `g(x)`
741
+
742
+ The second assumption holds good if `\frac{dy}{dx} = h(x, y)` is rewritten as
743
+ `\frac{dy}{dx} = \frac{1}{h(y, x)}` and the same properties of the first assumption
744
+ satisfies. After obtaining `f(x)` and `g(x)`, the coordinates are again
745
+ interchanged, to get `\xi` as `f(x^*)` and `\eta` as `g(y^*)`
746
+
747
+ References
748
+ ==========
749
+ - E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
750
+ ODE Patterns, pp. 10 - pp. 12
751
+
752
+ """
753
+
754
+ h = match['h']
755
+ hx = match['hx']
756
+ hy = match['hy']
757
+ func = match['func']
758
+ hinv = match['hinv']
759
+ x = func.args[0]
760
+ y = match['y']
761
+ xi = Function('xi')(x, func)
762
+ eta = Function('eta')(x, func)
763
+
764
+ factor = cancel(h.diff(y)/h.diff(y, 2))
765
+ factorx = factor.diff(x)
766
+ factory = factor.diff(y)
767
+ if not factor.has(x) and not factor.has(y):
768
+ A = Wild('A', exclude=[y])
769
+ B = Wild('B', exclude=[y])
770
+ C = Wild('C', exclude=[x, y])
771
+ match = h.match(A + B*exp(y/C))
772
+ try:
773
+ tau = exp(-integrate(match[A]/match[C]), x)/match[B]
774
+ except NotImplementedError:
775
+ pass
776
+ else:
777
+ gx = match[A]*tau
778
+ return [{xi: tau, eta: gx}]
779
+
780
+ else:
781
+ gamma = cancel(factorx/factory)
782
+ if not gamma.has(y):
783
+ tauint = cancel((gamma*hy - gamma.diff(x) - hx)/(h + gamma))
784
+ if not tauint.has(y):
785
+ try:
786
+ tau = exp(integrate(tauint, x))
787
+ except NotImplementedError:
788
+ pass
789
+ else:
790
+ gx = -tau*gamma
791
+ return [{xi: tau, eta: gx}]
792
+
793
+ factor = cancel(hinv.diff(y)/hinv.diff(y, 2))
794
+ factorx = factor.diff(x)
795
+ factory = factor.diff(y)
796
+ if not factor.has(x) and not factor.has(y):
797
+ A = Wild('A', exclude=[y])
798
+ B = Wild('B', exclude=[y])
799
+ C = Wild('C', exclude=[x, y])
800
+ match = h.match(A + B*exp(y/C))
801
+ try:
802
+ tau = exp(-integrate(match[A]/match[C]), x)/match[B]
803
+ except NotImplementedError:
804
+ pass
805
+ else:
806
+ gx = match[A]*tau
807
+ return [{eta: tau.subs(x, func), xi: gx.subs(x, func)}]
808
+
809
+ else:
810
+ gamma = cancel(factorx/factory)
811
+ if not gamma.has(y):
812
+ tauint = cancel((gamma*hinv.diff(y) - gamma.diff(x) - hinv.diff(x))/(
813
+ hinv + gamma))
814
+ if not tauint.has(y):
815
+ try:
816
+ tau = exp(integrate(tauint, x))
817
+ except NotImplementedError:
818
+ pass
819
+ else:
820
+ gx = -tau*gamma
821
+ return [{eta: tau.subs(x, func), xi: gx.subs(x, func)}]
822
+
823
+
824
+ def lie_heuristic_abaco2_unique_unknown(match, comp=False):
825
+ r"""
826
+ This heuristic assumes the presence of unknown functions or known functions
827
+ with non-integer powers.
828
+
829
+ 1. A list of all functions and non-integer powers containing x and y
830
+ 2. Loop over each element `f` in the list, find `\frac{\frac{\partial f}{\partial x}}{
831
+ \frac{\partial f}{\partial x}} = R`
832
+
833
+ If it is separable in `x` and `y`, let `X` be the factors containing `x`. Then
834
+
835
+ a] Check if `\xi = X` and `\eta = -\frac{X}{R}` satisfy the PDE. If yes, then return
836
+ `\xi` and `\eta`
837
+ b] Check if `\xi = \frac{-R}{X}` and `\eta = -\frac{1}{X}` satisfy the PDE.
838
+ If yes, then return `\xi` and `\eta`
839
+
840
+ If not, then check if
841
+
842
+ a] :math:`\xi = -R,\eta = 1`
843
+
844
+ b] :math:`\xi = 1, \eta = -\frac{1}{R}`
845
+
846
+ are solutions.
847
+
848
+ References
849
+ ==========
850
+ - E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
851
+ ODE Patterns, pp. 10 - pp. 12
852
+
853
+ """
854
+
855
+ h = match['h']
856
+ hx = match['hx']
857
+ hy = match['hy']
858
+ func = match['func']
859
+ x = func.args[0]
860
+ y = match['y']
861
+ xi = Function('xi')(x, func)
862
+ eta = Function('eta')(x, func)
863
+
864
+ funclist = []
865
+ for atom in h.atoms(Pow):
866
+ base, exp = atom.as_base_exp()
867
+ if base.has(x) and base.has(y):
868
+ if not exp.is_Integer:
869
+ funclist.append(atom)
870
+
871
+ for function in h.atoms(AppliedUndef):
872
+ syms = function.free_symbols
873
+ if x in syms and y in syms:
874
+ funclist.append(function)
875
+
876
+ for f in funclist:
877
+ frac = cancel(f.diff(y)/f.diff(x))
878
+ sep = separatevars(frac, dict=True, symbols=[x, y])
879
+ if sep and sep['coeff']:
880
+ xitry1 = sep[x]
881
+ etatry1 = -1/(sep[y]*sep['coeff'])
882
+ pde1 = etatry1.diff(y)*h - xitry1.diff(x)*h - xitry1*hx - etatry1*hy
883
+ if not simplify(pde1):
884
+ return [{xi: xitry1, eta: etatry1.subs(y, func)}]
885
+ xitry2 = 1/etatry1
886
+ etatry2 = 1/xitry1
887
+ pde2 = etatry2.diff(x) - (xitry2.diff(y))*h**2 - xitry2*hx - etatry2*hy
888
+ if not simplify(expand(pde2)):
889
+ return [{xi: xitry2.subs(y, func), eta: etatry2}]
890
+
891
+ else:
892
+ etatry = -1/frac
893
+ pde = etatry.diff(x) + etatry.diff(y)*h - hx - etatry*hy
894
+ if not simplify(pde):
895
+ return [{xi: S.One, eta: etatry.subs(y, func)}]
896
+ xitry = -frac
897
+ pde = -xitry.diff(x)*h -xitry.diff(y)*h**2 - xitry*hx -hy
898
+ if not simplify(expand(pde)):
899
+ return [{xi: xitry.subs(y, func), eta: S.One}]
900
+
901
+
902
+ def lie_heuristic_abaco2_unique_general(match, comp=False):
903
+ r"""
904
+ This heuristic finds if infinitesimals of the form `\eta = f(x)`, `\xi = g(y)`
905
+ without making any assumptions on `h`.
906
+
907
+ The complete sequence of steps is given in the paper mentioned below.
908
+
909
+ References
910
+ ==========
911
+ - E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
912
+ ODE Patterns, pp. 10 - pp. 12
913
+
914
+ """
915
+ hx = match['hx']
916
+ hy = match['hy']
917
+ func = match['func']
918
+ x = func.args[0]
919
+ y = match['y']
920
+ xi = Function('xi')(x, func)
921
+ eta = Function('eta')(x, func)
922
+
923
+ A = hx.diff(y)
924
+ B = hy.diff(y) + hy**2
925
+ C = hx.diff(x) - hx**2
926
+
927
+ if not (A and B and C):
928
+ return
929
+
930
+ Ax = A.diff(x)
931
+ Ay = A.diff(y)
932
+ Axy = Ax.diff(y)
933
+ Axx = Ax.diff(x)
934
+ Ayy = Ay.diff(y)
935
+ D = simplify(2*Axy + hx*Ay - Ax*hy + (hx*hy + 2*A)*A)*A - 3*Ax*Ay
936
+ if not D:
937
+ E1 = simplify(3*Ax**2 + ((hx**2 + 2*C)*A - 2*Axx)*A)
938
+ if E1:
939
+ E2 = simplify((2*Ayy + (2*B - hy**2)*A)*A - 3*Ay**2)
940
+ if not E2:
941
+ E3 = simplify(
942
+ E1*((28*Ax + 4*hx*A)*A**3 - E1*(hy*A + Ay)) - E1.diff(x)*8*A**4)
943
+ if not E3:
944
+ etaval = cancel((4*A**3*(Ax - hx*A) + E1*(hy*A - Ay))/(S(2)*A*E1))
945
+ if x not in etaval:
946
+ try:
947
+ etaval = exp(integrate(etaval, y))
948
+ except NotImplementedError:
949
+ pass
950
+ else:
951
+ xival = -4*A**3*etaval/E1
952
+ if y not in xival:
953
+ return [{xi: xival, eta: etaval.subs(y, func)}]
954
+
955
+ else:
956
+ E1 = simplify((2*Ayy + (2*B - hy**2)*A)*A - 3*Ay**2)
957
+ if E1:
958
+ E2 = simplify(
959
+ 4*A**3*D - D**2 + E1*((2*Axx - (hx**2 + 2*C)*A)*A - 3*Ax**2))
960
+ if not E2:
961
+ E3 = simplify(
962
+ -(A*D)*E1.diff(y) + ((E1.diff(x) - hy*D)*A + 3*Ay*D +
963
+ (A*hx - 3*Ax)*E1)*E1)
964
+ if not E3:
965
+ etaval = cancel(((A*hx - Ax)*E1 - (Ay + A*hy)*D)/(S(2)*A*D))
966
+ if x not in etaval:
967
+ try:
968
+ etaval = exp(integrate(etaval, y))
969
+ except NotImplementedError:
970
+ pass
971
+ else:
972
+ xival = -E1*etaval/D
973
+ if y not in xival:
974
+ return [{xi: xival, eta: etaval.subs(y, func)}]
975
+
976
+
977
+ def lie_heuristic_linear(match, comp=False):
978
+ r"""
979
+ This heuristic assumes
980
+
981
+ 1. `\xi = ax + by + c` and
982
+ 2. `\eta = fx + gy + h`
983
+
984
+ After substituting the following assumptions in the determining PDE, it
985
+ reduces to
986
+
987
+ .. math:: f + (g - a)h - bh^{2} - (ax + by + c)\frac{\partial h}{\partial x}
988
+ - (fx + gy + c)\frac{\partial h}{\partial y}
989
+
990
+ Solving the reduced PDE obtained, using the method of characteristics, becomes
991
+ impractical. The method followed is grouping similar terms and solving the system
992
+ of linear equations obtained. The difference between the bivariate heuristic is that
993
+ `h` need not be a rational function in this case.
994
+
995
+ References
996
+ ==========
997
+ - E.S. Cheb-Terrab, A.D. Roche, Symmetries and First Order
998
+ ODE Patterns, pp. 10 - pp. 12
999
+
1000
+ """
1001
+ h = match['h']
1002
+ hx = match['hx']
1003
+ hy = match['hy']
1004
+ func = match['func']
1005
+ x = func.args[0]
1006
+ y = match['y']
1007
+ xi = Function('xi')(x, func)
1008
+ eta = Function('eta')(x, func)
1009
+
1010
+ coeffdict = {}
1011
+ symbols = numbered_symbols("c", cls=Dummy)
1012
+ symlist = [next(symbols) for _ in islice(symbols, 6)]
1013
+ C0, C1, C2, C3, C4, C5 = symlist
1014
+ pde = C3 + (C4 - C0)*h - (C0*x + C1*y + C2)*hx - (C3*x + C4*y + C5)*hy - C1*h**2
1015
+ pde, denom = pde.as_numer_denom()
1016
+ pde = powsimp(expand(pde))
1017
+ if pde.is_Add:
1018
+ terms = pde.args
1019
+ for term in terms:
1020
+ if term.is_Mul:
1021
+ rem = Mul(*[m for m in term.args if not m.has(x, y)])
1022
+ xypart = term/rem
1023
+ if xypart not in coeffdict:
1024
+ coeffdict[xypart] = rem
1025
+ else:
1026
+ coeffdict[xypart] += rem
1027
+ else:
1028
+ if term not in coeffdict:
1029
+ coeffdict[term] = S.One
1030
+ else:
1031
+ coeffdict[term] += S.One
1032
+
1033
+ sollist = coeffdict.values()
1034
+ soldict = solve(sollist, symlist)
1035
+ if soldict:
1036
+ if isinstance(soldict, list):
1037
+ soldict = soldict[0]
1038
+ subval = soldict.values()
1039
+ if any(t for t in subval):
1040
+ onedict = dict(zip(symlist, [1]*6))
1041
+ xival = C0*x + C1*func + C2
1042
+ etaval = C3*x + C4*func + C5
1043
+ xival = xival.subs(soldict)
1044
+ etaval = etaval.subs(soldict)
1045
+ xival = xival.subs(onedict)
1046
+ etaval = etaval.subs(onedict)
1047
+ return [{xi: xival, eta: etaval}]
1048
+
1049
+
1050
+ def _lie_group_remove(coords):
1051
+ r"""
1052
+ This function is strictly meant for internal use by the Lie group ODE solving
1053
+ method. It replaces arbitrary functions returned by pdsolve as follows:
1054
+
1055
+ 1] If coords is an arbitrary function, then its argument is returned.
1056
+ 2] An arbitrary function in an Add object is replaced by zero.
1057
+ 3] An arbitrary function in a Mul object is replaced by one.
1058
+ 4] If there is no arbitrary function coords is returned unchanged.
1059
+
1060
+ Examples
1061
+ ========
1062
+
1063
+ >>> from sympy.solvers.ode.lie_group import _lie_group_remove
1064
+ >>> from sympy import Function
1065
+ >>> from sympy.abc import x, y
1066
+ >>> F = Function("F")
1067
+ >>> eq = x**2*y
1068
+ >>> _lie_group_remove(eq)
1069
+ x**2*y
1070
+ >>> eq = F(x**2*y)
1071
+ >>> _lie_group_remove(eq)
1072
+ x**2*y
1073
+ >>> eq = x*y**2 + F(x**3)
1074
+ >>> _lie_group_remove(eq)
1075
+ x*y**2
1076
+ >>> eq = (F(x**3) + y)*x**4
1077
+ >>> _lie_group_remove(eq)
1078
+ x**4*y
1079
+
1080
+ """
1081
+ if isinstance(coords, AppliedUndef):
1082
+ return coords.args[0]
1083
+ elif coords.is_Add:
1084
+ subfunc = coords.atoms(AppliedUndef)
1085
+ if subfunc:
1086
+ for func in subfunc:
1087
+ coords = coords.subs(func, 0)
1088
+ return coords
1089
+ elif coords.is_Pow:
1090
+ base, expr = coords.as_base_exp()
1091
+ base = _lie_group_remove(base)
1092
+ expr = _lie_group_remove(expr)
1093
+ return base**expr
1094
+ elif coords.is_Mul:
1095
+ mulargs = []
1096
+ coordargs = coords.args
1097
+ for arg in coordargs:
1098
+ if not isinstance(coords, AppliedUndef):
1099
+ mulargs.append(_lie_group_remove(arg))
1100
+ return Mul(*mulargs)
1101
+ return coords
env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/nonhomogeneous.py ADDED
@@ -0,0 +1,499 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)
env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/ode.py ADDED
The diff for this file is too large to render. See raw diff
 
env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/riccati.py ADDED
@@ -0,0 +1,893 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 {k:v for k, v in 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
env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/single.py ADDED
The diff for this file is too large to render. See raw diff
 
env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/subscheck.py ADDED
@@ -0,0 +1,392 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)
env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/systems.py ADDED
@@ -0,0 +1,2135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 j, scc in enumerate(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 = {func: 2 for func in funcs}
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 = {func: 1 for func in funcs}
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 = {func: 2 for func in funcs}
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 = {func: new_func for func, new_func in 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
env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/tests/__init__.py ADDED
File without changes
env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (188 Bytes). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/tests/__pycache__/test_lie_group.cpython-310.pyc ADDED
Binary file (5.94 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/tests/__pycache__/test_ode.cpython-310.pyc ADDED
Binary file (37.5 kB). View file
 
env-llmeval/lib/python3.10/site-packages/sympy/solvers/ode/tests/__pycache__/test_riccati.cpython-310.pyc ADDED
Binary file (29.3 kB). View file