passagemath-symbolics 10.6.43__cp314-cp314t-musllinux_1_2_x86_64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of passagemath-symbolics might be problematic. Click here for more details.

Files changed (171) hide show
  1. passagemath_symbolics/__init__.py +3 -0
  2. passagemath_symbolics-10.6.43.dist-info/METADATA +187 -0
  3. passagemath_symbolics-10.6.43.dist-info/RECORD +171 -0
  4. passagemath_symbolics-10.6.43.dist-info/WHEEL +5 -0
  5. passagemath_symbolics-10.6.43.dist-info/top_level.txt +3 -0
  6. sage/all__sagemath_symbolics.py +17 -0
  7. sage/calculus/all.py +14 -0
  8. sage/calculus/calculus.py +2826 -0
  9. sage/calculus/desolvers.py +1866 -0
  10. sage/calculus/predefined.py +51 -0
  11. sage/calculus/tests.py +225 -0
  12. sage/calculus/var.cpython-314t-x86_64-linux-musl.so +0 -0
  13. sage/calculus/var.pyx +401 -0
  14. sage/dynamics/all__sagemath_symbolics.py +6 -0
  15. sage/dynamics/complex_dynamics/all.py +5 -0
  16. sage/dynamics/complex_dynamics/mandel_julia.py +765 -0
  17. sage/dynamics/complex_dynamics/mandel_julia_helper.cpython-314t-x86_64-linux-musl.so +0 -0
  18. sage/dynamics/complex_dynamics/mandel_julia_helper.pyx +1035 -0
  19. sage/ext/all__sagemath_symbolics.py +1 -0
  20. sage/ext_data/kenzo/CP2.txt +45 -0
  21. sage/ext_data/kenzo/CP3.txt +349 -0
  22. sage/ext_data/kenzo/CP4.txt +4774 -0
  23. sage/ext_data/kenzo/README.txt +49 -0
  24. sage/ext_data/kenzo/S4.txt +20 -0
  25. sage/ext_data/magma/latex/latex.m +1021 -0
  26. sage/ext_data/magma/latex/latex.spec +1 -0
  27. sage/ext_data/magma/sage/basic.m +356 -0
  28. sage/ext_data/magma/sage/sage.spec +1 -0
  29. sage/ext_data/magma/spec +9 -0
  30. sage/geometry/all__sagemath_symbolics.py +8 -0
  31. sage/geometry/hyperbolic_space/all.py +5 -0
  32. sage/geometry/hyperbolic_space/hyperbolic_coercion.py +743 -0
  33. sage/geometry/hyperbolic_space/hyperbolic_constants.py +5 -0
  34. sage/geometry/hyperbolic_space/hyperbolic_geodesic.py +2409 -0
  35. sage/geometry/hyperbolic_space/hyperbolic_interface.py +206 -0
  36. sage/geometry/hyperbolic_space/hyperbolic_isometry.py +1082 -0
  37. sage/geometry/hyperbolic_space/hyperbolic_model.py +1502 -0
  38. sage/geometry/hyperbolic_space/hyperbolic_point.py +621 -0
  39. sage/geometry/riemannian_manifolds/all.py +7 -0
  40. sage/geometry/riemannian_manifolds/parametrized_surface3d.py +1632 -0
  41. sage/geometry/riemannian_manifolds/surface3d_generators.py +461 -0
  42. sage/interfaces/all__sagemath_symbolics.py +1 -0
  43. sage/interfaces/magma.py +3017 -0
  44. sage/interfaces/magma_free.py +92 -0
  45. sage/interfaces/maple.py +1397 -0
  46. sage/interfaces/mathematica.py +1345 -0
  47. sage/interfaces/mathics.py +1312 -0
  48. sage/interfaces/sympy.py +1398 -0
  49. sage/interfaces/sympy_wrapper.py +197 -0
  50. sage/interfaces/tides.py +938 -0
  51. sage/libs/all__sagemath_symbolics.py +6 -0
  52. sage/manifolds/all.py +7 -0
  53. sage/manifolds/calculus_method.py +555 -0
  54. sage/manifolds/catalog.py +437 -0
  55. sage/manifolds/chart.py +4019 -0
  56. sage/manifolds/chart_func.py +3419 -0
  57. sage/manifolds/continuous_map.py +2183 -0
  58. sage/manifolds/continuous_map_image.py +155 -0
  59. sage/manifolds/differentiable/affine_connection.py +2475 -0
  60. sage/manifolds/differentiable/all.py +1 -0
  61. sage/manifolds/differentiable/automorphismfield.py +1383 -0
  62. sage/manifolds/differentiable/automorphismfield_group.py +604 -0
  63. sage/manifolds/differentiable/bundle_connection.py +1445 -0
  64. sage/manifolds/differentiable/characteristic_cohomology_class.py +1840 -0
  65. sage/manifolds/differentiable/chart.py +1241 -0
  66. sage/manifolds/differentiable/curve.py +1028 -0
  67. sage/manifolds/differentiable/de_rham_cohomology.py +541 -0
  68. sage/manifolds/differentiable/degenerate.py +559 -0
  69. sage/manifolds/differentiable/degenerate_submanifold.py +1671 -0
  70. sage/manifolds/differentiable/diff_form.py +1658 -0
  71. sage/manifolds/differentiable/diff_form_module.py +1062 -0
  72. sage/manifolds/differentiable/diff_map.py +1315 -0
  73. sage/manifolds/differentiable/differentiable_submanifold.py +291 -0
  74. sage/manifolds/differentiable/examples/all.py +1 -0
  75. sage/manifolds/differentiable/examples/euclidean.py +2517 -0
  76. sage/manifolds/differentiable/examples/real_line.py +897 -0
  77. sage/manifolds/differentiable/examples/sphere.py +1186 -0
  78. sage/manifolds/differentiable/examples/symplectic_space.py +187 -0
  79. sage/manifolds/differentiable/examples/symplectic_space_test.py +40 -0
  80. sage/manifolds/differentiable/integrated_curve.py +4035 -0
  81. sage/manifolds/differentiable/levi_civita_connection.py +841 -0
  82. sage/manifolds/differentiable/manifold.py +4254 -0
  83. sage/manifolds/differentiable/manifold_homset.py +1826 -0
  84. sage/manifolds/differentiable/metric.py +3032 -0
  85. sage/manifolds/differentiable/mixed_form.py +1507 -0
  86. sage/manifolds/differentiable/mixed_form_algebra.py +559 -0
  87. sage/manifolds/differentiable/multivector_module.py +800 -0
  88. sage/manifolds/differentiable/multivectorfield.py +1520 -0
  89. sage/manifolds/differentiable/poisson_tensor.py +268 -0
  90. sage/manifolds/differentiable/pseudo_riemannian.py +755 -0
  91. sage/manifolds/differentiable/pseudo_riemannian_submanifold.py +1839 -0
  92. sage/manifolds/differentiable/scalarfield.py +1343 -0
  93. sage/manifolds/differentiable/scalarfield_algebra.py +472 -0
  94. sage/manifolds/differentiable/symplectic_form.py +910 -0
  95. sage/manifolds/differentiable/symplectic_form_test.py +220 -0
  96. sage/manifolds/differentiable/tangent_space.py +412 -0
  97. sage/manifolds/differentiable/tangent_vector.py +616 -0
  98. sage/manifolds/differentiable/tensorfield.py +4665 -0
  99. sage/manifolds/differentiable/tensorfield_module.py +963 -0
  100. sage/manifolds/differentiable/tensorfield_paral.py +2450 -0
  101. sage/manifolds/differentiable/tensorfield_paral_test.py +16 -0
  102. sage/manifolds/differentiable/vector_bundle.py +1728 -0
  103. sage/manifolds/differentiable/vectorfield.py +1717 -0
  104. sage/manifolds/differentiable/vectorfield_module.py +2445 -0
  105. sage/manifolds/differentiable/vectorframe.py +1832 -0
  106. sage/manifolds/family.py +270 -0
  107. sage/manifolds/local_frame.py +1490 -0
  108. sage/manifolds/manifold.py +3090 -0
  109. sage/manifolds/manifold_homset.py +452 -0
  110. sage/manifolds/operators.py +359 -0
  111. sage/manifolds/point.py +994 -0
  112. sage/manifolds/scalarfield.py +3718 -0
  113. sage/manifolds/scalarfield_algebra.py +629 -0
  114. sage/manifolds/section.py +3111 -0
  115. sage/manifolds/section_module.py +831 -0
  116. sage/manifolds/structure.py +229 -0
  117. sage/manifolds/subset.py +2764 -0
  118. sage/manifolds/subsets/all.py +1 -0
  119. sage/manifolds/subsets/closure.py +131 -0
  120. sage/manifolds/subsets/pullback.py +885 -0
  121. sage/manifolds/topological_submanifold.py +891 -0
  122. sage/manifolds/trivialization.py +733 -0
  123. sage/manifolds/utilities.py +1348 -0
  124. sage/manifolds/vector_bundle.py +1342 -0
  125. sage/manifolds/vector_bundle_fiber.py +332 -0
  126. sage/manifolds/vector_bundle_fiber_element.py +111 -0
  127. sage/matrix/all__sagemath_symbolics.py +1 -0
  128. sage/matrix/matrix_symbolic_dense.cpython-314t-x86_64-linux-musl.so +0 -0
  129. sage/matrix/matrix_symbolic_dense.pxd +6 -0
  130. sage/matrix/matrix_symbolic_dense.pyx +1022 -0
  131. sage/matrix/matrix_symbolic_sparse.cpython-314t-x86_64-linux-musl.so +0 -0
  132. sage/matrix/matrix_symbolic_sparse.pxd +6 -0
  133. sage/matrix/matrix_symbolic_sparse.pyx +1029 -0
  134. sage/modules/all__sagemath_symbolics.py +1 -0
  135. sage/modules/vector_callable_symbolic_dense.py +105 -0
  136. sage/modules/vector_symbolic_dense.py +116 -0
  137. sage/modules/vector_symbolic_sparse.py +118 -0
  138. sage/rings/all__sagemath_symbolics.py +4 -0
  139. sage/rings/asymptotic/all.py +6 -0
  140. sage/rings/asymptotic/asymptotic_expansion_generators.py +1485 -0
  141. sage/rings/asymptotic/asymptotic_ring.py +4858 -0
  142. sage/rings/asymptotic/asymptotics_multivariate_generating_functions.py +4153 -0
  143. sage/rings/asymptotic/growth_group.py +5373 -0
  144. sage/rings/asymptotic/growth_group_cartesian.py +1400 -0
  145. sage/rings/asymptotic/term_monoid.py +5237 -0
  146. sage/rings/function_field/all__sagemath_symbolics.py +2 -0
  147. sage/rings/polynomial/all__sagemath_symbolics.py +1 -0
  148. sage/symbolic/all.py +15 -0
  149. sage/symbolic/assumptions.py +985 -0
  150. sage/symbolic/benchmark.py +93 -0
  151. sage/symbolic/callable.py +459 -0
  152. sage/symbolic/complexity_measures.py +35 -0
  153. sage/symbolic/constants.py +1287 -0
  154. sage/symbolic/expression_conversion_algebraic.py +310 -0
  155. sage/symbolic/expression_conversion_sympy.py +317 -0
  156. sage/symbolic/expression_conversions.py +1713 -0
  157. sage/symbolic/function_factory.py +355 -0
  158. sage/symbolic/integration/all.py +1 -0
  159. sage/symbolic/integration/external.py +270 -0
  160. sage/symbolic/integration/integral.py +1115 -0
  161. sage/symbolic/maxima_wrapper.py +162 -0
  162. sage/symbolic/operators.py +267 -0
  163. sage/symbolic/random_tests.py +462 -0
  164. sage/symbolic/relation.py +1907 -0
  165. sage/symbolic/ring.cpython-314t-x86_64-linux-musl.so +0 -0
  166. sage/symbolic/ring.pxd +5 -0
  167. sage/symbolic/ring.pyx +1396 -0
  168. sage/symbolic/subring.py +1025 -0
  169. sage/symbolic/symengine.py +19 -0
  170. sage/symbolic/tests.py +40 -0
  171. sage/symbolic/units.py +1470 -0
@@ -0,0 +1,1866 @@
1
+ # sage_setup: distribution = sagemath-symbolics
2
+ r"""
3
+ Solving ordinary differential equations
4
+
5
+ This file contains functions useful for solving differential equations
6
+ which occur commonly in a 1st semester differential equations
7
+ course. For another numerical solver see the :meth:`ode_solver` function
8
+ and the optional package Octave.
9
+
10
+ Solutions from the Maxima package can contain the three constants
11
+ ``_C``, ``_K1``, and ``_K2`` where the underscore is used to distinguish
12
+ them from symbolic variables that the user might have used. You can
13
+ substitute values for them, and make them into accessible usable
14
+ symbolic variables, for example with ``var("_C")``.
15
+
16
+ Commands:
17
+
18
+ - :func:`desolve` -- compute the "general solution" to a 1st or 2nd order
19
+ ODE via Maxima
20
+
21
+ - :func:`desolve_laplace` -- solve an ODE using Laplace transforms via
22
+ Maxima. Initial conditions are optional
23
+
24
+ - :func:`desolve_rk4` -- solve numerically an IVP for one first order
25
+ equation, return list of points or plot
26
+
27
+ - :func:`desolve_system_rk4` -- solve numerically an IVP for a system of first
28
+ order equations, return list of points
29
+
30
+ - :func:`desolve_odeint` -- solve numerically a system of first-order ordinary
31
+ differential equations using :func:`~scipy:scipy.integrate.odeint` from
32
+ the module :mod:`scipy:scipy.integrate`.
33
+
34
+ - :func:`desolve_system` -- solve a system of 1st order ODEs of any size using
35
+ Maxima. Initial conditions are optional
36
+
37
+ - :func:`eulers_method` -- approximate solution to a 1st order DE,
38
+ presented as a table
39
+
40
+ - :func:`eulers_method_2x2` -- approximate solution to a 1st order system
41
+ of DEs, presented as a table
42
+
43
+ - :func:`eulers_method_2x2_plot` -- plot the sequence of points obtained
44
+ from Euler's method
45
+
46
+ The following functions require the optional package ``tides``:
47
+
48
+ - :func:`desolve_mintides` -- numerical solution of a system of 1st order ODEs via
49
+ the Taylor series integrator method implemented in TIDES
50
+
51
+ - :func:`desolve_tides_mpfr` -- arbitrary precision Taylor series integrator implemented in TIDES
52
+
53
+ AUTHORS:
54
+
55
+ - David Joyner (3-2006) - Initial version of functions
56
+
57
+ - Marshall Hampton (7-2007) - Creation of Python module and testing
58
+
59
+ - Robert Bradshaw (10-2008) - Some interface cleanup.
60
+
61
+ - Robert Marik (10-2009) - Some bugfixes and enhancements
62
+
63
+ - Miguel Marco (06-2014) - Tides desolvers
64
+ """
65
+
66
+ ##########################################################################
67
+ # Copyright (C) 2006 David Joyner <wdjoyner@gmail.com>, Marshall Hampton,
68
+ # Robert Marik <marik@mendelu.cz>
69
+ #
70
+ # Distributed under the terms of the GNU General Public License (GPL):
71
+ #
72
+ # https://www.gnu.org/licenses/
73
+ ##########################################################################
74
+
75
+ import shutil
76
+ import os
77
+
78
+ from sage.interfaces.maxima import Maxima
79
+ from sage.misc.functional import N
80
+ from sage.rings.real_mpfr import RealField
81
+ from sage.structure.element import Expression
82
+
83
+ from .functional import diff
84
+
85
+
86
+ maxima = Maxima()
87
+
88
+
89
+ def fricas_desolve(de, dvar, ics, ivar):
90
+ r"""
91
+ Solve an ODE using FriCAS.
92
+
93
+ EXAMPLES::
94
+
95
+ sage: x = var('x')
96
+ sage: y = function('y')(x)
97
+ sage: desolve(diff(y,x) + y - 1, y, algorithm='fricas') # optional - fricas
98
+ _C0*e^(-x) + 1
99
+
100
+ sage: desolve(diff(y, x) + y == y^3*sin(x), y, algorithm='fricas') # optional - fricas
101
+ -1/5*(2*cos(x)*y(x)^2 + 4*sin(x)*y(x)^2 - 5)*e^(-2*x)/y(x)^2
102
+
103
+ TESTS::
104
+
105
+ sage: from sage.calculus.desolvers import fricas_desolve
106
+ sage: Y = fricas_desolve(diff(y,x) + y - 1, y, [42,1783], x) # optional - fricas
107
+ sage: Y.subs(x=42) # optional - fricas
108
+ 1783
109
+ """
110
+ from sage.interfaces.fricas import fricas
111
+ from sage.symbolic.ring import SR
112
+ if ics is None:
113
+ y = fricas(de).solve(dvar.operator(), ivar).sage()
114
+ else:
115
+ eq = fricas.equation(ivar, ics[0])
116
+ y = fricas(de).solve(dvar.operator(), eq, ics[1:]).sage()
117
+
118
+ if isinstance(y, dict):
119
+ basis = y["basis"]
120
+ particular = y["particular"]
121
+ return particular + sum(SR.var("_C" + str(i)) * v
122
+ for i, v in enumerate(basis))
123
+ return y
124
+
125
+
126
+ def fricas_desolve_system(des, dvars, ics, ivar):
127
+ r"""
128
+ Solve a system of first order ODEs using FriCAS.
129
+
130
+ EXAMPLES::
131
+
132
+ sage: t = var('t')
133
+ sage: x = function('x')(t)
134
+ sage: y = function('y')(t)
135
+ sage: de1 = diff(x,t) + y - 1 == 0
136
+ sage: de2 = diff(y,t) - x + 1 == 0
137
+ sage: desolve_system([de1, de2], [x, y], algorithm='fricas') # optional - fricas
138
+ [x(t) == _C0*cos(t) + cos(t)^2 + _C1*sin(t) + sin(t)^2,
139
+ y(t) == -_C1*cos(t) + _C0*sin(t) + 1]
140
+
141
+ sage: desolve_system([de1, de2], [x,y], [0,1,2], algorithm='fricas') # optional - fricas
142
+ [x(t) == cos(t)^2 + sin(t)^2 - sin(t), y(t) == cos(t) + 1]
143
+
144
+ TESTS::
145
+
146
+ sage: from sage.calculus.desolvers import fricas_desolve_system
147
+ sage: t = var('t')
148
+ sage: x = function('x')(t)
149
+ sage: fricas_desolve_system([diff(x,t) + 1 == 0], [x], None, t) # optional - fricas
150
+ [x(t) == _C0 - t]
151
+
152
+ sage: y = function('y')(t)
153
+ sage: de1 = diff(x,t) + y - 1 == 0
154
+ sage: de2 = diff(y,t) - x + 1 == 0
155
+ sage: sol = fricas_desolve_system([de1,de2], [x,y], [0,1,-1], t) # optional - fricas
156
+ sage: sol # optional - fricas
157
+ [x(t) == cos(t)^2 + sin(t)^2 + 2*sin(t), y(t) == -2*cos(t) + 1]
158
+ """
159
+ from sage.interfaces.fricas import fricas
160
+ from sage.symbolic.ring import SR
161
+ from sage.symbolic.relation import solve
162
+ ops = [dvar.operator() for dvar in dvars]
163
+ y = fricas(des).solve(ops, ivar).sage()
164
+ basis = y["basis"]
165
+ particular = y["particular"]
166
+ pars = [SR.var("_C" + str(i)) for i in range(len(basis))]
167
+ solv = particular + sum(p * v for p, v in zip(pars, basis))
168
+
169
+ if ics is None:
170
+ sols = solv
171
+ else:
172
+ ics0 = ics[0]
173
+ eqs = [val == sol.subs({ivar: ics0}) for val, sol in zip(ics[1:], solv)]
174
+ pars_values = solve(eqs, pars, solution_dict=True)
175
+ sols = [sol.subs(pars_values[0]) for sol in solv]
176
+
177
+ return [dvar == sol for dvar, sol in zip(dvars, sols)]
178
+
179
+
180
+ def desolve(de, dvar, ics=None, ivar=None, show_method=False, contrib_ode=False,
181
+ algorithm='maxima'):
182
+ r"""
183
+ Solve a 1st or 2nd order linear ODE, including IVP and BVP.
184
+
185
+ INPUT:
186
+
187
+ - ``de`` -- an expression or equation representing the ODE
188
+
189
+ - ``dvar`` -- the dependent variable (hereafter called `y`)
190
+
191
+ - ``ics`` -- (optional) the initial or boundary conditions
192
+
193
+ - for a first-order equation, specify the initial `x` and `y`
194
+
195
+ - for a second-order equation, specify the initial `x`, `y`,
196
+ and `dy/dx`, i.e. write `[x_0, y(x_0), y'(x_0)]`
197
+
198
+ - for a second-order boundary solution, specify initial and
199
+ final `x` and `y` boundary conditions, i.e. write `[x_0, y(x_0), x_1, y(x_1)]`.
200
+
201
+ - gives an error if the solution is not SymbolicEquation (as happens for
202
+ example for a Clairaut equation)
203
+
204
+ - ``ivar`` -- (optional) the independent variable (hereafter called
205
+ `x`), which must be specified if there is more than one
206
+ independent variable in the equation
207
+
208
+ - ``show_method`` -- (optional) if ``True``, then Sage returns pair
209
+ ``[solution, method]``, where method is the string describing
210
+ the method which has been used to get a solution (Maxima uses the
211
+ following order for first order equations: linear, separable,
212
+ exact (including exact with integrating factor), homogeneous,
213
+ bernoulli, generalized homogeneous) - use carefully in class,
214
+ see below the example of an equation which is separable but
215
+ this property is not recognized by Maxima and the equation is solved
216
+ as exact.
217
+
218
+ - ``contrib_ode`` -- (optional) if ``True``, ``desolve`` allows to solve
219
+ Clairaut, Lagrange, Riccati and some other equations. This may take
220
+ a long time and is thus turned off by default. Initial conditions
221
+ can be used only if the result is one SymbolicEquation (does not
222
+ contain a singular solution, for example).
223
+
224
+ - ``algorithm`` -- (default: ``'maxima'``) one of
225
+
226
+ * ``'maxima'`` -- use maxima
227
+ * ``'fricas'`` -- use FriCAS (the optional fricas spkg has to be installed)
228
+
229
+ OUTPUT:
230
+
231
+ In most cases return a SymbolicEquation which defines the solution
232
+ implicitly. If the result is in the form `y(x)=\ldots` (happens for
233
+ linear eqs.), return the right-hand side only. The possible
234
+ constant solutions of separable ODEs are omitted.
235
+
236
+ .. NOTE::
237
+
238
+ Use ``desolve? <tab>`` if the output in the Sage notebook is truncated.
239
+
240
+ EXAMPLES::
241
+
242
+ sage: x = var('x')
243
+ sage: y = function('y')(x)
244
+ sage: desolve(diff(y,x) + y - 1, y)
245
+ (_C + e^x)*e^(-x)
246
+
247
+ ::
248
+
249
+ sage: f = desolve(diff(y,x) + y - 1, y, ics=[10,2]); f
250
+ (e^10 + e^x)*e^(-x)
251
+
252
+ ::
253
+
254
+ sage: plot(f) # needs sage.plot
255
+ Graphics object consisting of 1 graphics primitive
256
+
257
+ We can also solve second-order differential equations::
258
+
259
+ sage: x = var('x')
260
+ sage: y = function('y')(x)
261
+ sage: de = diff(y,x,2) - y == x
262
+ sage: desolve(de, y)
263
+ _K2*e^(-x) + _K1*e^x - x
264
+
265
+ ::
266
+
267
+ sage: f = desolve(de, y, [10,2,1]); f
268
+ -x + 7*e^(x - 10) + 5*e^(-x + 10)
269
+
270
+ ::
271
+
272
+ sage: f(x=10)
273
+ 2
274
+
275
+ ::
276
+
277
+ sage: diff(f,x)(x=10)
278
+ 1
279
+
280
+ ::
281
+
282
+ sage: de = diff(y,x,2) + y == 0
283
+ sage: desolve(de, y)
284
+ _K2*cos(x) + _K1*sin(x)
285
+
286
+ ::
287
+
288
+ sage: desolve(de, y, [0,1,pi/2,4])
289
+ cos(x) + 4*sin(x)
290
+
291
+ ::
292
+
293
+ sage: desolve(y*diff(y,x)+sin(x)==0,y)
294
+ -1/2*y(x)^2 == _C - cos(x)
295
+
296
+ Clairaut equation: general and singular solutions::
297
+
298
+ sage: desolve(diff(y,x)^2+x*diff(y,x)-y==0,y,contrib_ode=True,show_method=True)
299
+ [[y(x) == _C^2 + _C*x, y(x) == -1/4*x^2], 'clairau...']
300
+
301
+ For equations involving more variables we specify an independent variable::
302
+
303
+ sage: a,b,c,n=var('a b c n')
304
+ sage: desolve(x^2*diff(y,x)==a+b*x^n+c*x^2*y^2,y,ivar=x,contrib_ode=True)
305
+ [[y(x) == 0, (b*x^(n - 2) + a/x^2)*c^2*u == 0]]
306
+
307
+ ::
308
+
309
+ sage: desolve(x^2*diff(y,x)==a+b*x^n+c*x^2*y^2,y,ivar=x,contrib_ode=True,show_method=True)
310
+ [[[y(x) == 0, (b*x^(n - 2) + a/x^2)*c^2*u == 0]], 'riccati']
311
+
312
+
313
+ Higher order equations, not involving independent variable::
314
+
315
+ sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y).expand()
316
+ 1/6*y(x)^3 + _K1*y(x) == _K2 + x
317
+
318
+ ::
319
+
320
+ sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,1,3]).expand()
321
+ 1/6*y(x)^3 - 5/3*y(x) == x - 3/2
322
+
323
+ ::
324
+
325
+ sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,1,3],show_method=True)
326
+ [1/6*y(x)^3 - 5/3*y(x) == x - 3/2, 'freeofx']
327
+
328
+ Separable equations - Sage returns solution in implicit form::
329
+
330
+ sage: desolve(diff(y,x)*sin(y) == cos(x),y)
331
+ -cos(y(x)) == _C + sin(x)
332
+
333
+ ::
334
+
335
+ sage: desolve(diff(y,x)*sin(y) == cos(x),y,show_method=True)
336
+ [-cos(y(x)) == _C + sin(x), 'separable']
337
+
338
+ ::
339
+
340
+ sage: desolve(diff(y,x)*sin(y) == cos(x),y,[pi/2,1])
341
+ -cos(y(x)) == -cos(1) + sin(x) - 1
342
+
343
+ Linear equation - Sage returns the expression on the right hand side only::
344
+
345
+ sage: desolve(diff(y,x)+(y) == cos(x),y)
346
+ 1/2*((cos(x) + sin(x))*e^x + 2*_C)*e^(-x)
347
+
348
+ ::
349
+
350
+ sage: desolve(diff(y,x)+(y) == cos(x),y,show_method=True)
351
+ [1/2*((cos(x) + sin(x))*e^x + 2*_C)*e^(-x), 'linear']
352
+
353
+ ::
354
+
355
+ sage: desolve(diff(y,x)+(y) == cos(x),y,[0,1])
356
+ 1/2*(cos(x)*e^x + e^x*sin(x) + 1)*e^(-x)
357
+
358
+ This ODE with separated variables is solved as
359
+ exact. Explanation - factor does not split `e^{x-y}` in Maxima
360
+ into `e^{x}e^{y}`::
361
+
362
+ sage: desolve(diff(y,x)==exp(x-y),y,show_method=True)
363
+ [-e^x + e^y(x) == _C, 'exact']
364
+
365
+ You can solve Bessel equations, also using initial
366
+ conditions, but you cannot put (sometimes desired) the initial
367
+ condition at `x=0`, since this point is a singular point of the
368
+ equation. Anyway, if the solution should be bounded at `x=0`, then
369
+ ``_K2=0``. ::
370
+
371
+ sage: desolve(x^2*diff(y,x,x)+x*diff(y,x)+(x^2-4)*y==0,y)
372
+ _K1*bessel_J(2, x) + _K2*bessel_Y(2, x)
373
+
374
+ Example of difficult ODE producing an error::
375
+
376
+ sage: desolve(sqrt(y)*diff(y,x)+e^(y)+cos(x)-sin(x+y)==0,y) # not tested
377
+ Traceback (click to the left for traceback)
378
+ ...
379
+ NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True."
380
+
381
+ Another difficult ODE with error - moreover, it takes a long time::
382
+
383
+ sage: desolve(sqrt(y)*diff(y,x)+e^(y)+cos(x)-sin(x+y)==0,y,contrib_ode=True) # not tested
384
+
385
+ Some more types of ODEs::
386
+
387
+ sage: desolve(x*diff(y,x)^2-(1+x*y)*diff(y,x)+y==0,y,contrib_ode=True,show_method=True)
388
+ [[y(x) == _C + log(x), y(x) == _C*e^x], 'factor']
389
+
390
+ ::
391
+
392
+ sage: desolve(diff(y,x)==(x+y)^2,y,contrib_ode=True,show_method=True)
393
+ [[[x == _C - arctan(sqrt(t)), y(x) == -x - sqrt(t)], [x == _C + arctan(sqrt(t)), y(x) == -x + sqrt(t)]], 'lagrange']
394
+
395
+ These two examples produce an error (as expected, Maxima 5.18 cannot
396
+ solve equations from initial conditions). Maxima 5.18
397
+ returns false answer in this case! ::
398
+
399
+ sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,2]).expand() # not tested
400
+ Traceback (click to the left for traceback)
401
+ ...
402
+ NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True."
403
+
404
+ ::
405
+
406
+ sage: desolve(diff(y,x,2)+y*(diff(y,x,1))^3==0,y,[0,1,2],show_method=True) # not tested
407
+ Traceback (click to the left for traceback)
408
+ ...
409
+ NotImplementedError, "Maxima was unable to solve this ODE. Consider to set option contrib_ode to True."
410
+
411
+ Second order linear ODE::
412
+
413
+ sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y)
414
+ (_K2*x + _K1)*e^(-x) + 1/2*sin(x)
415
+
416
+ ::
417
+
418
+ sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,show_method=True)
419
+ [(_K2*x + _K1)*e^(-x) + 1/2*sin(x), 'variationofparameters']
420
+
421
+ ::
422
+
423
+ sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,1])
424
+ 1/2*(7*x + 6)*e^(-x) + 1/2*sin(x)
425
+
426
+ ::
427
+
428
+ sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,1],show_method=True)
429
+ [1/2*(7*x + 6)*e^(-x) + 1/2*sin(x), 'variationofparameters']
430
+
431
+ ::
432
+
433
+ sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,pi/2,2])
434
+ 3*(x*(e^(1/2*pi) - 2)/pi + 1)*e^(-x) + 1/2*sin(x)
435
+
436
+ ::
437
+
438
+ sage: desolve(diff(y,x,2)+2*diff(y,x)+y == cos(x),y,[0,3,pi/2,2],show_method=True)
439
+ [3*(x*(e^(1/2*pi) - 2)/pi + 1)*e^(-x) + 1/2*sin(x), 'variationofparameters']
440
+
441
+ ::
442
+
443
+ sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y)
444
+ (_K2*x + _K1)*e^(-x)
445
+
446
+ ::
447
+
448
+ sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,show_method=True)
449
+ [(_K2*x + _K1)*e^(-x), 'constcoeff']
450
+
451
+ ::
452
+
453
+ sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,1])
454
+ (4*x + 3)*e^(-x)
455
+
456
+ ::
457
+
458
+ sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,1],show_method=True)
459
+ [(4*x + 3)*e^(-x), 'constcoeff']
460
+
461
+ ::
462
+
463
+ sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,pi/2,2])
464
+ (2*x*(2*e^(1/2*pi) - 3)/pi + 3)*e^(-x)
465
+
466
+ ::
467
+
468
+ sage: desolve(diff(y,x,2)+2*diff(y,x)+y == 0,y,[0,3,pi/2,2],show_method=True)
469
+ [(2*x*(2*e^(1/2*pi) - 3)/pi + 3)*e^(-x), 'constcoeff']
470
+
471
+ Using ``algorithm='fricas'`` we can invoke the differential
472
+ equation solver from FriCAS. For example, it can solve higher
473
+ order linear equations::
474
+
475
+ sage: de = x^3*diff(y, x, 3) + x^2*diff(y, x, 2) - 2*x*diff(y, x) + 2*y - 2*x^4
476
+ sage: Y = desolve(de, y, algorithm='fricas'); Y # optional - fricas
477
+ (2*x^3 - 3*x^2 + 1)*_C0/x + (x^3 - 1)*_C1/x
478
+ + (x^3 - 3*x^2 - 1)*_C2/x + 1/15*(x^5 - 10*x^3 + 20*x^2 + 4)/x
479
+
480
+ The initial conditions are then interpreted as `[x_0, y(x_0),
481
+ y'(x_0), \ldots, y^(n)(x_0)]`::
482
+
483
+ sage: Y = desolve(de, y, ics=[1,3,7], algorithm='fricas'); Y # optional - fricas
484
+ 1/15*(x^5 + 15*x^3 + 50*x^2 - 21)/x
485
+
486
+ FriCAS can also solve some non-linear equations::
487
+
488
+ sage: de = diff(y, x) == y / (x+y*log(y))
489
+ sage: Y = desolve(de, y, algorithm='fricas'); Y # optional - fricas
490
+ 1/2*(log(y(x))^2*y(x) - 2*x)/y(x)
491
+
492
+ TESTS:
493
+
494
+ :issue:`9961` fixed (allow assumptions on the dependent variable in desolve)::
495
+
496
+ sage: y=function('y')(x); assume(x>0); assume(y>0)
497
+ sage: sage.calculus.calculus.maxima('domain:real') # needed since Maxima 5.26.0 to get the answer as below
498
+ real
499
+ sage: desolve(x*diff(y,x)-x*sqrt(y^2+x^2)-y == 0, y, contrib_ode=True)
500
+ [x - arcsinh(y(x)/x) == _C]
501
+
502
+ :issue:`10682` updated Maxima to 5.26, and it started to show a different
503
+ solution in the complex domain for the ODE above::
504
+
505
+ sage: forget()
506
+ sage: sage.calculus.calculus.maxima('domain:complex') # back to the default complex domain
507
+ complex
508
+ sage: assume(x>0)
509
+ sage: assume(y>0)
510
+ sage: desolve(x*diff(y,x)-x*sqrt(y^2+x^2)-y == 0, y, contrib_ode=True)
511
+ [x - arcsinh(y(x)^2/(x*sqrt(y(x)^2))) - arcsinh(y(x)/x) + 1/2*log(4*(x^2 + 2*y(x)^2 + 2*sqrt(x^2*y(x)^2 + y(x)^4))/x^2) == _C]
512
+
513
+ :issue:`6479` fixed::
514
+
515
+ sage: x = var('x')
516
+ sage: y = function('y')(x)
517
+ sage: desolve( diff(y,x,x) == 0, y, [0,0,1])
518
+ x
519
+
520
+ ::
521
+
522
+ sage: desolve( diff(y,x,x) == 0, y, [0,1,1])
523
+ x + 1
524
+
525
+ :issue:`9835` fixed::
526
+
527
+ sage: x = var('x')
528
+ sage: y = function('y')(x)
529
+ sage: desolve(diff(y,x,2)+y*(1-y^2)==0,y,[0,-1,1,1])
530
+ Traceback (most recent call last):
531
+ ...
532
+ NotImplementedError: Unable to use initial condition for this equation (freeofx).
533
+
534
+ :issue:`8931` fixed::
535
+
536
+ sage: x=var('x'); f=function('f')(x); k=var('k'); assume(k>0)
537
+ sage: desolve(diff(f,x,2)/f==k,f,ivar=x)
538
+ _K1*e^(sqrt(k)*x) + _K2*e^(-sqrt(k)*x)
539
+
540
+ :issue:`15775` fixed::
541
+
542
+ sage: forget()
543
+ sage: y = function('y')(x)
544
+ sage: desolve(diff(y, x) == sqrt(abs(y)), dvar=y, ivar=x)
545
+ integrate(1/sqrt(abs(y(x))), y(x)) == _C + x
546
+
547
+ AUTHORS:
548
+
549
+ - David Joyner (1-2006)
550
+ - Robert Bradshaw (10-2008)
551
+ - Robert Marik (10-2009)
552
+ """
553
+ if isinstance(de, Expression) and de.is_relational():
554
+ de = de.lhs() - de.rhs()
555
+ if isinstance(dvar, Expression) and dvar.is_symbol():
556
+ raise ValueError("You have to declare dependent variable as a function evaluated at the independent variable, eg. y=function('y')(x)")
557
+ # for backwards compatibility
558
+ if isinstance(dvar, list):
559
+ dvar, ivar = dvar
560
+ elif ivar is None:
561
+ ivars = de.variables()
562
+ ivars = [t for t in ivars if t is not dvar]
563
+ if len(ivars) != 1:
564
+ raise ValueError("Unable to determine independent variable, please specify.")
565
+ ivar = ivars[0]
566
+
567
+ if algorithm == "fricas":
568
+ return fricas_desolve(de, dvar, ics, ivar)
569
+ elif algorithm != "maxima":
570
+ raise ValueError("unknown algorithm %s" % algorithm)
571
+
572
+ de00 = de._maxima_()
573
+ P = de00.parent()
574
+ dvar_str = P(dvar.operator()).str()
575
+ ivar_str = P(ivar).str()
576
+ de00 = de00.str()
577
+
578
+ def sanitize_var(exprs):
579
+ return exprs.replace("'" + dvar_str + "(" + ivar_str + ")", dvar_str)
580
+ de0 = sanitize_var(de00)
581
+ ode_solver = "ode2"
582
+ cmd = "(TEMP:%s(%s,%s,%s), if TEMP=false then TEMP else substitute(%s=%s(%s),TEMP))" % (ode_solver, de0, dvar_str, ivar_str, dvar_str, dvar_str, ivar_str)
583
+ # we produce string like this
584
+ # ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y(x),x)
585
+ soln = P(cmd)
586
+
587
+ if str(soln).strip() == 'false':
588
+ if contrib_ode:
589
+ ode_solver = "contrib_ode"
590
+ P("load('contrib_ode)")
591
+ cmd = "(TEMP:%s(%s,%s,%s), if TEMP=false then TEMP else substitute(%s=%s(%s),TEMP))" % (ode_solver, de0, dvar_str, ivar_str, dvar_str, dvar_str, ivar_str)
592
+ # we produce string like this
593
+ # (TEMP:contrib_ode(x*('diff(y,x,1))^2-(x*y+1)*'diff(y,x,1)+y,y,x), if TEMP=false then TEMP else substitute(y=y(x),TEMP))
594
+ soln = P(cmd)
595
+ if str(soln).strip() == 'false':
596
+ raise NotImplementedError("Maxima was unable to solve this ODE.")
597
+ else:
598
+ raise NotImplementedError("Maxima was unable to solve this ODE. Consider to set option contrib_ode to True.")
599
+
600
+ if show_method:
601
+ maxima_method = P("method")
602
+
603
+ if ics is not None:
604
+ if not (isinstance(soln.sage(), Expression) and soln.sage().is_relational()):
605
+ if not show_method:
606
+ maxima_method = P("method")
607
+ raise NotImplementedError("Unable to use initial condition for this equation (%s)." % (str(maxima_method).strip()))
608
+ if len(ics) == 2:
609
+ tempic = (ivar == ics[0])._maxima_().str()
610
+ tempic = tempic + "," + (dvar == ics[1])._maxima_().str()
611
+ cmd = "(TEMP:ic1(%s(%s,%s,%s),%s),substitute(%s=%s(%s),TEMP))" % (ode_solver, de00, dvar_str, ivar_str, tempic, dvar_str, dvar_str, ivar_str)
612
+ cmd = sanitize_var(cmd)
613
+ # we produce string like this
614
+ # (TEMP:ic2(ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y,x),x=0,y=3,'diff(y,x)=1),substitute(y=y(x),TEMP))
615
+ soln = P(cmd)
616
+ if len(ics) == 3:
617
+ # fixed ic2 command from Maxima - we have to ensure that %k1, %k2 do not depend on variables, should be removed when fixed in Maxima
618
+ P("ic2_sage(soln,xa,ya,dya):=block([programmode:true,backsubst:true,singsolve:true,temp,%k2,%k1,TEMP_k], \
619
+ noteqn(xa), noteqn(ya), noteqn(dya), boundtest('%k1,%k1), boundtest('%k2,%k2), \
620
+ temp: lhs(soln) - rhs(soln), \
621
+ TEMP_k:solve([subst([xa,ya],soln), subst([dya,xa], lhs(dya)=-subst(0,lhs(dya),diff(temp,lhs(xa)))/diff(temp,lhs(ya)))],[%k1,%k2]), \
622
+ if not freeof(lhs(ya),TEMP_k) or not freeof(lhs(xa),TEMP_k) then return (false), \
623
+ temp: maplist(lambda([zz], subst(zz,soln)), TEMP_k), \
624
+ if length(temp)=1 then return(first(temp)) else return(temp))")
625
+ tempic = P(ivar == ics[0]).str()
626
+ tempic += "," + P(dvar == ics[1]).str()
627
+ tempic += ",'diff(" + dvar_str + "," + ivar_str + ")=" + P(ics[2]).str()
628
+ cmd = "(TEMP:ic2_sage(%s(%s,%s,%s),%s),substitute(%s=%s(%s),TEMP))" % (ode_solver, de00, dvar_str, ivar_str, tempic, dvar_str, dvar_str, ivar_str)
629
+ cmd = sanitize_var(cmd)
630
+ # we produce string like this
631
+ # (TEMP:ic2(ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y,x),x=0,y=3,'diff(y,x)=1),substitute(y=y(x),TEMP))
632
+ soln = P(cmd)
633
+ if str(soln).strip() == 'false':
634
+ raise NotImplementedError("Maxima was unable to solve this IVP. Remove the initial condition to get the general solution.")
635
+ if len(ics) == 4:
636
+ # fixed bc2 command from Maxima - we have to ensure that %k1, %k2 do not depend on variables, should be removed when fixed in Maxima
637
+ P("bc2_sage(soln,xa,ya,xb,yb):=block([programmode:true,backsubst:true,singsolve:true,temp,%k1,%k2,TEMP_k], \
638
+ noteqn(xa), noteqn(ya), noteqn(xb), noteqn(yb), boundtest('%k1,%k1), boundtest('%k2,%k2), \
639
+ TEMP_k:solve([subst([xa,ya],soln), subst([xb,yb],soln)], [%k1,%k2]), \
640
+ if not freeof(lhs(ya),TEMP_k) or not freeof(lhs(xa),TEMP_k) then return (false), \
641
+ temp: maplist(lambda([zz], subst(zz,soln)),TEMP_k), \
642
+ if length(temp)=1 then return(first(temp)) else return(temp))")
643
+ cmd = "bc2_sage(%s(%s,%s,%s),%s,%s=%s,%s,%s=%s)" % (ode_solver, de00, dvar_str, ivar_str, P(ivar == ics[0]).str(), dvar_str, P(ics[1]).str(), P(ivar == ics[2]).str(), dvar_str, P(ics[3]).str())
644
+ cmd = "(TEMP:%s,substitute(%s=%s(%s),TEMP))" % (cmd, dvar_str, dvar_str, ivar_str)
645
+ cmd = sanitize_var(cmd)
646
+ # we produce string like this
647
+ # (TEMP:bc2(ode2('diff(y,x,2)+2*'diff(y,x,1)+y-cos(x),y,x),x=0,y=3,x=%pi/2,y=2),substitute(y=y(x),TEMP))
648
+ soln = P(cmd)
649
+ if str(soln).strip() == 'false':
650
+ raise NotImplementedError("Maxima was unable to solve this BVP. Remove the initial condition to get the general solution.")
651
+
652
+ soln = soln.sage()
653
+ if isinstance(soln, Expression) and soln.is_relational() and soln.lhs() == dvar:
654
+ # Remark: Here we do not check that the right hand side does not depend on dvar.
655
+ # This probably will not happen for solutions obtained via ode2, anyway.
656
+ soln = soln.rhs()
657
+ if show_method:
658
+ return [soln, maxima_method.str()]
659
+ return soln
660
+
661
+
662
+ def desolve_laplace(de, dvar, ics=None, ivar=None):
663
+ """
664
+ Solve an ODE using Laplace transforms. Initial conditions are optional.
665
+
666
+ INPUT:
667
+
668
+ - ``de`` -- a lambda expression representing the ODE (e.g. ``de =
669
+ diff(y,x,2) == diff(y,x)+sin(x)``)
670
+
671
+ - ``dvar`` -- the dependent variable (e.g. ``y``)
672
+
673
+ - ``ivar`` -- (optional) the independent variable (hereafter called
674
+ `x`), which must be specified if there is more than one
675
+ independent variable in the equation.
676
+
677
+ - ``ics`` -- list of numbers representing initial conditions, (e.g.
678
+ ``f(0)=1``, ``f'(0)=2`` corresponds to ``ics = [0,1,2]``)
679
+
680
+ OUTPUT: solution of the ODE as symbolic expression
681
+
682
+ EXAMPLES::
683
+
684
+ sage: u=function('u')(x)
685
+ sage: eq = diff(u,x) - exp(-x) - u == 0
686
+ sage: desolve_laplace(eq,u)
687
+ 1/2*(2*u(0) + 1)*e^x - 1/2*e^(-x)
688
+
689
+ We can use initial conditions::
690
+
691
+ sage: desolve_laplace(eq,u,ics=[0,3])
692
+ -1/2*e^(-x) + 7/2*e^x
693
+
694
+ The initial conditions do not persist in the system (as they persisted
695
+ in previous versions)::
696
+
697
+ sage: desolve_laplace(eq,u)
698
+ 1/2*(2*u(0) + 1)*e^x - 1/2*e^(-x)
699
+
700
+ ::
701
+
702
+ sage: f=function('f')(x)
703
+ sage: eq = diff(f,x) + f == 0
704
+ sage: desolve_laplace(eq,f,[0,1])
705
+ e^(-x)
706
+
707
+ ::
708
+
709
+ sage: x = var('x')
710
+ sage: f = function('f')(x)
711
+ sage: de = diff(f,x,x) - 2*diff(f,x) + f
712
+ sage: desolve_laplace(de,f)
713
+ -x*e^x*f(0) + x*e^x*D[0](f)(0) + e^x*f(0)
714
+
715
+ ::
716
+
717
+ sage: desolve_laplace(de,f,ics=[0,1,2])
718
+ x*e^x + e^x
719
+
720
+ TESTS:
721
+
722
+ Check that :issue:`4839` is fixed::
723
+
724
+ sage: t = var('t')
725
+ sage: x = function('x')(t)
726
+ sage: soln = desolve_laplace(diff(x,t)+x==1, x, ics=[0,2])
727
+ sage: soln
728
+ e^(-t) + 1
729
+
730
+ ::
731
+
732
+ sage: soln(t=3)
733
+ e^(-3) + 1
734
+
735
+ AUTHORS:
736
+
737
+ - David Joyner (1-2006,8-2007)
738
+
739
+ - Robert Marik (10-2009)
740
+ """
741
+ # This is the original code from David Joyner (inputs and outputs strings)
742
+ # maxima("de:"+de._repr_()+"=0;")
743
+ # if ics is not None:
744
+ # d = len(ics)
745
+ # for i in range(d-1):
746
+ # ic = "atvalue(diff("+vars[1]+"("+vars[0]+"),"+str(vars[0])+","+str(i)+"),"+str(vars[0])+"="+str(ics[0])+","+str(ics[1+i])+")"
747
+ # maxima(ic)
748
+ #
749
+ # cmd = "desolve("+de._repr_()+","+vars[1]+"("+vars[0]+"));"
750
+ # return maxima(cmd).rhs()._maxima_init_()
751
+
752
+ # verbatim copy from desolve - begin
753
+ if isinstance(de, Expression) and de.is_relational():
754
+ de = de.lhs() - de.rhs()
755
+ if isinstance(dvar, Expression) and dvar.is_symbol():
756
+ raise ValueError("You have to declare dependent variable as a function evaluated at the independent variable, eg. y=function('y')(x)")
757
+ # for backwards compatibility
758
+ if isinstance(dvar, list):
759
+ dvar, ivar = dvar
760
+ elif ivar is None:
761
+ ivars = de.variables()
762
+ ivars = [t for t in ivars if t is not dvar]
763
+ if len(ivars) != 1:
764
+ raise ValueError("Unable to determine independent variable, please specify.")
765
+ ivar = ivars[0]
766
+ # verbatim copy from desolve - end
767
+
768
+ dvar_str = str(dvar)
769
+
770
+ def sanitize_var(exprs):
771
+ # 'y(x) -> y(x)
772
+ return exprs.replace("'" + dvar_str, dvar_str)
773
+
774
+ de0 = de._maxima_()
775
+ P = de0.parent()
776
+ i = dvar_str.find('(')
777
+ dvar_str = dvar_str[:i + 1] + '_SAGE_VAR_' + dvar_str[i + 1:]
778
+ cmd = sanitize_var("desolve(" + de0.str() + "," + dvar_str + ")")
779
+ soln = P(cmd).rhs()
780
+ if str(soln).strip() == 'false':
781
+ raise NotImplementedError("Maxima was unable to solve this ODE.")
782
+ soln = soln.sage()
783
+ if ics is not None:
784
+ d = len(ics)
785
+ for i in range(d - 1):
786
+ soln = eval('soln.substitute(diff(dvar,ivar,i)(' + str(ivar) + '=ics[0])==ics[i+1])')
787
+ return soln
788
+
789
+
790
+ def desolve_system(des, vars, ics=None, ivar=None, algorithm='maxima'):
791
+ r"""
792
+ Solve a system of any size of 1st order ODEs. Initial conditions
793
+ are optional.
794
+
795
+ One dimensional systems are passed to :meth:`desolve_laplace`.
796
+
797
+ INPUT:
798
+
799
+ - ``des`` -- list of ODEs
800
+
801
+ - ``vars`` -- list of dependent variables
802
+
803
+ - ``ics`` -- (optional) list of initial values for ``ivar`` and ``vars``;
804
+ if ``ics`` is defined, it should provide initial conditions for each
805
+ variable, otherwise an exception would be raised
806
+
807
+ - ``ivar`` -- (optional) the independent variable, which must be
808
+ specified if there is more than one independent variable in the
809
+ equation
810
+
811
+ - ``algorithm`` -- (default: ``'maxima'``) one of
812
+
813
+ * ``'maxima'`` -- use maxima
814
+ * ``'fricas'`` -- use FriCAS (the optional fricas spkg has to be installed)
815
+
816
+ EXAMPLES::
817
+
818
+ sage: t = var('t')
819
+ sage: x = function('x')(t)
820
+ sage: y = function('y')(t)
821
+ sage: de1 = diff(x,t) + y - 1 == 0
822
+ sage: de2 = diff(y,t) - x + 1 == 0
823
+ sage: desolve_system([de1, de2], [x,y])
824
+ [x(t) == (x(0) - 1)*cos(t) - (y(0) - 1)*sin(t) + 1,
825
+ y(t) == (y(0) - 1)*cos(t) + (x(0) - 1)*sin(t) + 1]
826
+
827
+ The same system solved using FriCAS::
828
+
829
+ sage: desolve_system([de1, de2], [x,y], algorithm='fricas') # optional - fricas
830
+ [x(t) == _C0*cos(t) + cos(t)^2 + _C1*sin(t) + sin(t)^2,
831
+ y(t) == -_C1*cos(t) + _C0*sin(t) + 1]
832
+
833
+ Now we give some initial conditions::
834
+
835
+ sage: sol = desolve_system([de1, de2], [x,y], ics=[0,1,2]); sol
836
+ [x(t) == -sin(t) + 1, y(t) == cos(t) + 1]
837
+
838
+ ::
839
+
840
+ sage: solnx, solny = sol[0].rhs(), sol[1].rhs()
841
+ sage: plot([solnx,solny],(0,1)) # not tested
842
+ sage: parametric_plot((solnx,solny),(0,1)) # not tested
843
+
844
+ TESTS:
845
+
846
+ Check that :issue:`9823` is fixed::
847
+
848
+ sage: t = var('t')
849
+ sage: x = function('x')(t)
850
+ sage: de1 = diff(x,t) + 1 == 0
851
+ sage: desolve_system([de1], [x])
852
+ -t + x(0)
853
+
854
+ Check that :issue:`16568` is fixed::
855
+
856
+ sage: t = var('t')
857
+ sage: x = function('x')(t)
858
+ sage: y = function('y')(t)
859
+ sage: de1 = diff(x,t) + y - 1 == 0
860
+ sage: de2 = diff(y,t) - x + 1 == 0
861
+ sage: des = [de1,de2]
862
+ sage: ics = [0,1,-1]
863
+ sage: vars = [x,y]
864
+ sage: sol = desolve_system(des, vars, ics); sol
865
+ [x(t) == 2*sin(t) + 1, y(t) == -2*cos(t) + 1]
866
+
867
+ ::
868
+
869
+ sage: solx, soly = sol[0].rhs(), sol[1].rhs()
870
+ sage: RR(solx(t=3))
871
+ 1.28224001611973
872
+
873
+ ::
874
+
875
+ sage: P1 = plot([solx,soly], (0,1)) # needs sage.plot
876
+ sage: P2 = parametric_plot((solx,soly), (0,1)) # needs sage.plot
877
+
878
+ Now type ``show(P1)``, ``show(P2)`` to view these plots.
879
+
880
+ Check that :issue:`9824` is fixed::
881
+
882
+ sage: t = var('t')
883
+ sage: epsilon = var('epsilon')
884
+ sage: x1 = function('x1')(t)
885
+ sage: x2 = function('x2')(t)
886
+ sage: de1 = diff(x1,t) == epsilon
887
+ sage: de2 = diff(x2,t) == -2
888
+ sage: desolve_system([de1, de2], [x1, x2], ivar=t)
889
+ [x1(t) == epsilon*t + x1(0), x2(t) == -2*t + x2(0)]
890
+ sage: desolve_system([de1, de2], [x1, x2], ics=[1,1], ivar=t)
891
+ Traceback (most recent call last):
892
+ ...
893
+ ValueError: Initial conditions aren't complete: number of vars is different
894
+ from number of dependent variables. Got ics = [1, 1], vars = [x1(t), x2(t)]
895
+
896
+ Check that :issue:`9825` is fixed::
897
+
898
+ sage: t = var('t')
899
+ sage: x1, x2=function("x1, x2")
900
+ sage: de1=x1(t).diff(t)==-3*(x2(t)-1)
901
+ sage: de2=x2(t).diff(t)==1
902
+ sage: Sol=desolve_system([de1, de2],[x1(t),x2(t)],ivar=t) ; Sol
903
+ [x1(t) == -3/2*t^2 - 3*t*x2(0) + 3*t + x1(0), x2(t) == t + x2(0)]
904
+
905
+
906
+ AUTHORS:
907
+
908
+ - Robert Bradshaw (10-2008)
909
+ - Sergey Bykov (10-2014)
910
+ """
911
+ if ics is not None:
912
+ if len(ics) != (len(vars) + 1):
913
+ raise ValueError("Initial conditions aren't complete: number of vars is different from number of dependent variables. Got ics = {0}, vars = {1}".format(ics, vars))
914
+
915
+ if len(des) == 1 and algorithm == "maxima":
916
+ return desolve_laplace(des[0], vars[0], ics=ics, ivar=ivar)
917
+ ivars = set()
918
+ for i, de in enumerate(des):
919
+ if not (isinstance(de, Expression) and de.is_relational()):
920
+ des[i] = de == 0
921
+ ivars = ivars.union(set(de.variables()))
922
+ if ivar is None:
923
+ ivars = ivars - set(vars)
924
+ if len(ivars) != 1:
925
+ raise ValueError("Unable to determine independent variable, please specify.")
926
+ ivar = list(ivars)[0]
927
+
928
+ if algorithm == "fricas":
929
+ return fricas_desolve_system(des, vars, ics, ivar)
930
+ elif algorithm != "maxima":
931
+ raise ValueError("unknown algorithm %s" % algorithm)
932
+
933
+ dvars = [v._maxima_() for v in vars]
934
+ if ics is not None:
935
+ ivar_ic = ics[0]
936
+ for dvar, ic in zip(dvars, ics[1:]):
937
+ dvar.atvalue(ivar == ivar_ic, ic)
938
+ soln = dvars[0].parent().desolve(des, dvars)
939
+ if str(soln).strip() == 'false':
940
+ raise NotImplementedError("Maxima was unable to solve this system.")
941
+ soln = list(soln)
942
+ for i, sol in enumerate(soln):
943
+ soln[i] = sol.sage()
944
+ if ics is not None:
945
+ ivar_ic = ics[0]
946
+ for dvar, ic in zip(dvars, ics[:1]):
947
+ dvar.atvalue(ivar == ivar_ic, dvar)
948
+ return soln
949
+
950
+
951
+ def eulers_method(f, x0, y0, h, x1, algorithm='table'):
952
+ r"""
953
+ This implements Euler's method for finding numerically the
954
+ solution of the 1st order ODE `y' = f(x,y)`, `y(a)=c`. The ``x``
955
+ column of the table increments from `x_0` to `x_1` by `h` (so
956
+ `(x_1-x_0)/h` must be an integer). In the ``y`` column, the new
957
+ `y`-value equals the old `y`-value plus the corresponding entry in the
958
+ last column.
959
+
960
+ .. NOTE::
961
+
962
+ This function is for pedagogical purposes only.
963
+
964
+ EXAMPLES::
965
+
966
+ sage: from sage.calculus.desolvers import eulers_method
967
+ sage: x,y = PolynomialRing(QQ,2,"xy").gens()
968
+ sage: eulers_method(5*x+y-5,0,1,1/2,1)
969
+ x y h*f(x,y)
970
+ 0 1 -2
971
+ 1/2 -1 -7/4
972
+ 1 -11/4 -11/8
973
+
974
+ ::
975
+
976
+ sage: x,y = PolynomialRing(QQ,2,"xy").gens()
977
+ sage: eulers_method(5*x+y-5,0,1,1/2,1,algorithm='none')
978
+ [[0, 1], [1/2, -1], [1, -11/4], [3/2, -33/8]]
979
+
980
+ ::
981
+
982
+ sage: RR = RealField(sci_not=0, prec=4, rnd='RNDU')
983
+ sage: x,y = PolynomialRing(RR,2,"xy").gens()
984
+ sage: eulers_method(5*x+y-5,0,1,1/2,1,algorithm="None")
985
+ [[0, 1], [1/2, -1.0], [1, -2.7], [3/2, -4.0]]
986
+
987
+ ::
988
+
989
+ sage: RR = RealField(sci_not=0, prec=4, rnd='RNDU')
990
+ sage: x,y=PolynomialRing(RR,2,"xy").gens()
991
+ sage: eulers_method(5*x+y-5,0,1,1/2,1)
992
+ x y h*f(x,y)
993
+ 0 1 -2.0
994
+ 1/2 -1.0 -1.7
995
+ 1 -2.7 -1.3
996
+
997
+ ::
998
+
999
+ sage: x,y=PolynomialRing(QQ,2,"xy").gens()
1000
+ sage: eulers_method(5*x+y-5,1,1,1/3,2)
1001
+ x y h*f(x,y)
1002
+ 1 1 1/3
1003
+ 4/3 4/3 1
1004
+ 5/3 7/3 17/9
1005
+ 2 38/9 83/27
1006
+
1007
+ ::
1008
+
1009
+ sage: eulers_method(5*x+y-5,0,1,1/2,1,algorithm='none')
1010
+ [[0, 1], [1/2, -1], [1, -11/4], [3/2, -33/8]]
1011
+
1012
+ ::
1013
+
1014
+ sage: pts = eulers_method(5*x+y-5,0,1,1/2,1,algorithm='none')
1015
+ sage: P1 = list_plot(pts) # needs sage.plot
1016
+ sage: P2 = line(pts) # needs sage.plot
1017
+ sage: (P1 + P2).show() # needs sage.plot
1018
+
1019
+ AUTHORS:
1020
+
1021
+ - David Joyner
1022
+ """
1023
+ if algorithm == "table":
1024
+ print("%10s %20s %25s" % ("x", "y", "h*f(x,y)"))
1025
+ n = int((1.0) * (x1 - x0) / h)
1026
+ x00 = x0
1027
+ y00 = y0
1028
+ soln = [[x00, y00]]
1029
+ for i in range(n + 1):
1030
+ if algorithm == "table":
1031
+ print("%10r %20r %20r" % (x00, y00, h * f(x00, y00)))
1032
+ y00 = y00 + h * f(x00, y00)
1033
+ x00 = x00 + h
1034
+ soln.append([x00, y00])
1035
+ if algorithm != "table":
1036
+ return soln
1037
+
1038
+
1039
+ def eulers_method_2x2(f, g, t0, x0, y0, h, t1, algorithm='table'):
1040
+ r"""
1041
+ This implements Euler's method for finding numerically the
1042
+ solution of the 1st order system of two ODEs
1043
+
1044
+ .. MATH::
1045
+
1046
+ \begin{aligned}
1047
+ x' &= f(t, x, y), x(t_0)=x_0 \\
1048
+ y' &= g(t, x, y), y(t_0)=y_0.
1049
+ \end{aligned}
1050
+
1051
+ The ``t`` column of the table increments from `t_0` to `t_1` by `h`
1052
+ (so `\frac{t_1-t_0}{h}` must be an integer). In the ``x`` column,
1053
+ the new `x`-value equals the old `x`-value plus the corresponding
1054
+ entry in the next (third) column. In the ``y`` column, the new
1055
+ `y`-value equals the old `y`-value plus the corresponding entry in the
1056
+ next (last) column.
1057
+
1058
+ .. NOTE::
1059
+
1060
+ This function is for pedagogical purposes only.
1061
+
1062
+ EXAMPLES::
1063
+
1064
+ sage: from sage.calculus.desolvers import eulers_method_2x2
1065
+ sage: t, x, y = PolynomialRing(QQ,3,"txy").gens()
1066
+ sage: f = x+y+t; g = x-y
1067
+ sage: eulers_method_2x2(f,g, 0, 0, 0, 1/3, 1,algorithm='none')
1068
+ [[0, 0, 0], [1/3, 0, 0], [2/3, 1/9, 0], [1, 10/27, 1/27], [4/3, 68/81, 4/27]]
1069
+
1070
+ ::
1071
+
1072
+ sage: eulers_method_2x2(f,g, 0, 0, 0, 1/3, 1)
1073
+ t x h*f(t,x,y) y h*g(t,x,y)
1074
+ 0 0 0 0 0
1075
+ 1/3 0 1/9 0 0
1076
+ 2/3 1/9 7/27 0 1/27
1077
+ 1 10/27 38/81 1/27 1/9
1078
+
1079
+ ::
1080
+
1081
+ sage: RR = RealField(sci_not=0, prec=4, rnd='RNDU')
1082
+ sage: t,x,y=PolynomialRing(RR,3,"txy").gens()
1083
+ sage: f = x+y+t; g = x-y
1084
+ sage: eulers_method_2x2(f,g, 0, 0, 0, 1/3, 1)
1085
+ t x h*f(t,x,y) y h*g(t,x,y)
1086
+ 0 0 0.00 0 0.00
1087
+ 1/3 0.00 0.13 0.00 0.00
1088
+ 2/3 0.13 0.29 0.00 0.043
1089
+ 1 0.41 0.57 0.043 0.15
1090
+
1091
+ To numerically approximate `y(1)`, where `(1+t^2)y''+y'-y=0`,
1092
+ `y(0)=1`, `y'(0)=-1`, using 4 steps of Euler's method, first
1093
+ convert to a system: `y_1' = y_2`, `y_1(0)=1`; `y_2' =
1094
+ \frac{y_1-y_2}{1+t^2}`, `y_2(0)=-1`.::
1095
+
1096
+ sage: RR = RealField(sci_not=0, prec=4, rnd='RNDU')
1097
+ sage: t, x, y=PolynomialRing(RR,3,"txy").gens()
1098
+ sage: f = y; g = (x-y)/(1+t^2)
1099
+ sage: eulers_method_2x2(f,g, 0, 1, -1, 1/4, 1)
1100
+ t x h*f(t,x,y) y h*g(t,x,y)
1101
+ 0 1 -0.25 -1 0.50
1102
+ 1/4 0.75 -0.12 -0.50 0.29
1103
+ 1/2 0.63 -0.054 -0.21 0.19
1104
+ 3/4 0.63 -0.0078 -0.031 0.11
1105
+ 1 0.63 0.020 0.079 0.071
1106
+
1107
+ To numerically approximate `y(1)`, where `y''+ty'+y=0`, `y(0)=1`, `y'(0)=0`::
1108
+
1109
+ sage: t,x,y=PolynomialRing(RR,3,"txy").gens()
1110
+ sage: f = y; g = -x-y*t
1111
+ sage: eulers_method_2x2(f,g, 0, 1, 0, 1/4, 1)
1112
+ t x h*f(t,x,y) y h*g(t,x,y)
1113
+ 0 1 0.00 0 -0.25
1114
+ 1/4 1.0 -0.062 -0.25 -0.23
1115
+ 1/2 0.94 -0.11 -0.46 -0.17
1116
+ 3/4 0.88 -0.15 -0.62 -0.10
1117
+ 1 0.75 -0.17 -0.68 -0.015
1118
+
1119
+ AUTHORS:
1120
+
1121
+ - David Joyner
1122
+ """
1123
+ if algorithm == "table":
1124
+ print("%10s %20s %25s %20s %20s" % ("t", "x", "h*f(t,x,y)", "y", "h*g(t,x,y)"))
1125
+ n = int((1.0) * (t1 - t0) / h)
1126
+ t00 = t0
1127
+ x00 = x0
1128
+ y00 = y0
1129
+ soln = [[t00, x00, y00]]
1130
+ for i in range(n + 1):
1131
+ if algorithm == "table":
1132
+ print("%10r %20r %25r %20r %20r" % (t00, x00, h * f(t00, x00, y00), y00, h * g(t00, x00, y00)))
1133
+ x01 = x00 + h * f(t00, x00, y00)
1134
+ y00 = y00 + h * g(t00, x00, y00)
1135
+ x00 = x01
1136
+ t00 = t00 + h
1137
+ soln.append([t00, x00, y00])
1138
+ if algorithm != "table":
1139
+ return soln
1140
+
1141
+
1142
+ def eulers_method_2x2_plot(f, g, t0, x0, y0, h, t1):
1143
+ r"""
1144
+ Plot solution of ODE.
1145
+
1146
+ This plots the solution in the rectangle with sides ``(xrange[0],xrange[1])`` and
1147
+ ``(yrange[0],yrange[1])``, and plots using Euler's method the
1148
+ numerical solution of the 1st order ODEs `x' = f(t,x,y)`,
1149
+ `x(a)=x_0`, `y' = g(t,x,y)`, `y(a) = y_0`.
1150
+
1151
+ .. NOTE::
1152
+
1153
+ This function is for pedagogical purposes only.
1154
+
1155
+ EXAMPLES:
1156
+
1157
+ The following example plots the solution to
1158
+ `\theta''+\sin(\theta)=0`, `\theta(0)=\frac 34`, `\theta'(0) =
1159
+ 0`. Type ``P[0].show()`` to plot the solution,
1160
+ ``(P[0]+P[1]).show()`` to plot `(t,\theta(t))` and
1161
+ `(t,\theta'(t))`::
1162
+
1163
+ sage: from sage.calculus.desolvers import eulers_method_2x2_plot
1164
+ sage: f = lambda z : z[2]; g = lambda z : -sin(z[1])
1165
+ sage: P = eulers_method_2x2_plot(f,g, 0.0, 0.75, 0.0, 0.1, 1.0) # needs sage.plot
1166
+ """
1167
+ from sage.plot.line import line
1168
+
1169
+ n = int((1.0) * (t1 - t0) / h)
1170
+ t00 = t0
1171
+ x00 = x0
1172
+ y00 = y0
1173
+ soln = [[t00, x00, y00]]
1174
+ for i in range(n + 1):
1175
+ x01 = x00 + h * f([t00, x00, y00])
1176
+ y00 = y00 + h * g([t00, x00, y00])
1177
+ x00 = x01
1178
+ t00 = t00 + h
1179
+ soln.append([t00, x00, y00])
1180
+ Q1 = line([[x[0], x[1]] for x in soln], rgbcolor=(.25, .125, .75))
1181
+ Q2 = line([[x[0], x[2]] for x in soln], rgbcolor=(.5, .125, .25))
1182
+ return [Q1, Q2]
1183
+
1184
+
1185
+ def desolve_rk4_determine_bounds(ics, end_points=None):
1186
+ """
1187
+ Used to determine bounds for numerical integration.
1188
+
1189
+ - If ``end_points`` is None, the interval for integration is from ``ics[0]``
1190
+ to ``ics[0]+10``
1191
+
1192
+ - If ``end_points`` is ``a`` or ``[a]``, the interval for integration is from ``min(ics[0],a)``
1193
+ to ``max(ics[0],a)``
1194
+
1195
+ - If ``end_points`` is ``[a,b]``, the interval for integration is from ``min(ics[0],a)``
1196
+ to ``max(ics[0],b)``
1197
+
1198
+ EXAMPLES::
1199
+
1200
+ sage: from sage.calculus.desolvers import desolve_rk4_determine_bounds
1201
+ sage: desolve_rk4_determine_bounds([0,2],1)
1202
+ (0, 1)
1203
+
1204
+ ::
1205
+
1206
+ sage: desolve_rk4_determine_bounds([0,2])
1207
+ (0, 10)
1208
+
1209
+ ::
1210
+
1211
+ sage: desolve_rk4_determine_bounds([0,2],[-2])
1212
+ (-2, 0)
1213
+
1214
+ ::
1215
+
1216
+ sage: desolve_rk4_determine_bounds([0,2],[-2,4])
1217
+ (-2, 4)
1218
+ """
1219
+ if end_points is None:
1220
+ return ics[0], ics[0] + 10
1221
+ if not isinstance(end_points, list):
1222
+ end_points = [end_points]
1223
+ if len(end_points) == 1:
1224
+ return min(ics[0], end_points[0]), max(ics[0], end_points[0])
1225
+ else:
1226
+ return min(ics[0], end_points[0]), max(ics[0], end_points[1])
1227
+
1228
+
1229
+ def desolve_rk4(de, dvar, ics=None, ivar=None, end_points=None, step=0.1, output='list', **kwds):
1230
+ """
1231
+ Solve numerically one first-order ordinary differential
1232
+ equation.
1233
+
1234
+ INPUT:
1235
+
1236
+ Input is similar to ``desolve`` command. The differential equation can be
1237
+ written in a form close to the ``plot_slope_field`` or ``desolve`` command.
1238
+
1239
+ - Variant 1 (function in two variables)
1240
+
1241
+ - ``de`` -- right hand side, i.e. the function `f(x,y)` from ODE `y'=f(x,y)`
1242
+
1243
+ - ``dvar`` -- dependent variable (symbolic variable declared by var)
1244
+
1245
+ - Variant 2 (symbolic equation)
1246
+
1247
+ - ``de`` -- equation, including term with ``diff(y,x)``
1248
+
1249
+ - ``dvar`` -- dependent variable (declared as function of independent variable)
1250
+
1251
+ - Other parameters
1252
+
1253
+ - ``ivar`` -- should be specified, if there are more variables or if the equation is autonomous
1254
+
1255
+ - ``ics`` -- initial conditions in the form ``[x0,y0]``
1256
+
1257
+ - ``end_points`` -- the end points of the interval
1258
+
1259
+ - if ``end_points`` is a or [a], we integrate between ``min(ics[0],a)`` and ``max(ics[0],a)``
1260
+ - if ``end_points`` is None, we use ``end_points=ics[0]+10``
1261
+
1262
+ - if end_points is [a,b] we integrate between ``min(ics[0], a)`` and ``max(ics[0], b)``
1263
+
1264
+ - ``step`` -- (default: 0.1) the length of the step (positive number)
1265
+
1266
+ - ``output`` -- (default: ``'list'``) one of ``'list'``,
1267
+ ``'plot'``, ``'slope_field'`` (graph of the solution with slope field)
1268
+
1269
+ OUTPUT:
1270
+
1271
+ Return a list of points, or plot produced by ``list_plot``,
1272
+ optionally with slope field.
1273
+
1274
+ .. SEEALSO::
1275
+
1276
+ :func:`ode_solver`.
1277
+
1278
+ EXAMPLES::
1279
+
1280
+ sage: from sage.calculus.desolvers import desolve_rk4
1281
+
1282
+ Variant 2 for input - more common in numerics::
1283
+
1284
+ sage: x,y = var('x,y')
1285
+ sage: desolve_rk4(x*y*(2-y),y,ics=[0,1],end_points=1,step=0.5)
1286
+ [[0, 1], [0.5, 1.12419127424558], [1.0, 1.46159016228882...]]
1287
+
1288
+ Variant 1 for input - we can pass ODE in the form used by
1289
+ desolve function In this example we integrate backwards, since
1290
+ ``end_points < ics[0]``::
1291
+
1292
+ sage: y = function('y')(x)
1293
+ sage: desolve_rk4(diff(y,x)+y*(y-1) == x-2,y,ics=[1,1],step=0.5, end_points=0)
1294
+ [[0.0, 8.904257108962112], [0.5, 1.90932794536153...], [1, 1]]
1295
+
1296
+ Here we show how to plot simple pictures. For more advanced
1297
+ applications use list_plot instead. To see the resulting picture
1298
+ use ``show(P)`` in Sage notebook. ::
1299
+
1300
+ sage: x,y = var('x,y')
1301
+ sage: P = desolve_rk4(y*(2-y), y, ics=[0,.1], ivar=x, # needs sage.plot
1302
+ ....: output='slope_field', end_points=[-4,6], thickness=3)
1303
+
1304
+ ALGORITHM:
1305
+
1306
+ `4`-th order Runge-Kutta method. Wrapper for command ``rk`` in
1307
+ Maxima's dynamics package. Perhaps could be faster by using
1308
+ fast_float instead.
1309
+
1310
+ AUTHORS:
1311
+
1312
+ - Robert Marik (10-2009)
1313
+ """
1314
+ if ics is None:
1315
+ raise ValueError("No initial conditions, specify with ics=[x0,y0].")
1316
+
1317
+ if output not in ['list', 'plot', 'slope_field']:
1318
+ raise ValueError("Option output should be 'list', 'plot' or 'slope_field'.")
1319
+
1320
+ if ivar is None:
1321
+ ivars = de.variables()
1322
+ ivars = [t for t in ivars if t != dvar]
1323
+ if len(ivars) != 1:
1324
+ raise ValueError("Unable to determine independent variable, please specify.")
1325
+ ivar = ivars[0]
1326
+
1327
+ step = abs(step)
1328
+
1329
+ def desolve_rk4_inner(de, dvar):
1330
+ de0 = de._maxima_()
1331
+ maxima("load('dynamics)")
1332
+ lower_bound, upper_bound = desolve_rk4_determine_bounds(ics, end_points)
1333
+ sol_1, sol_2 = [], []
1334
+ if lower_bound < ics[0]:
1335
+ cmd = "rk(%s,%s,%s,[%s,%s,%s,%s])\
1336
+ " % (de0.str(), '_SAGE_VAR_' + str(dvar), str(ics[1]), '_SAGE_VAR_' + str(ivar), str(ics[0]), lower_bound, -step)
1337
+ sol_1 = maxima(cmd).sage()
1338
+ sol_1.pop(0)
1339
+ sol_1.reverse()
1340
+ if upper_bound > ics[0]:
1341
+ cmd = "rk(%s,%s,%s,[%s,%s,%s,%s])\
1342
+ " % (de0.str(), '_SAGE_VAR_' + str(dvar), str(ics[1]), '_SAGE_VAR_' + str(ivar), str(ics[0]), upper_bound, step)
1343
+ sol_2 = maxima(cmd).sage()
1344
+ sol_2.pop(0)
1345
+ sol = sol_1
1346
+ sol.extend([[ics[0], ics[1]]])
1347
+ sol.extend(sol_2)
1348
+
1349
+ if output == 'list':
1350
+ return sol
1351
+ from sage.plot.plot import list_plot
1352
+ from sage.plot.plot_field import plot_slope_field
1353
+ R = list_plot(sol, plotjoined=True, **kwds)
1354
+ if output == 'plot':
1355
+ return R
1356
+ if output == 'slope_field':
1357
+ XMIN = sol[0][0]
1358
+ YMIN = sol[0][1]
1359
+ XMAX = XMIN
1360
+ YMAX = YMIN
1361
+ for s, t in sol:
1362
+ XMAX = max(s, XMAX)
1363
+ XMIN = min(s, XMIN)
1364
+ YMAX = max(t, YMAX)
1365
+ YMIN = min(t, YMIN)
1366
+ return plot_slope_field(de, (ivar, XMIN, XMAX), (dvar, YMIN, YMAX)) + R
1367
+
1368
+ if not (isinstance(dvar, Expression) and dvar.is_symbol()):
1369
+ from sage.symbolic.ring import SR
1370
+ from sage.calculus.all import diff
1371
+ from sage.symbolic.relation import solve
1372
+ if isinstance(de, Expression) and de.is_relational():
1373
+ de = de.lhs() - de.rhs()
1374
+ # consider to add warning if the solution is not unique
1375
+ de = solve(de, diff(dvar, ivar), solution_dict=True)
1376
+ if len(de) != 1:
1377
+ raise NotImplementedError("Sorry, cannot find explicit formula for right-hand side of the ODE.")
1378
+ with SR.temp_var() as dummy_dvar:
1379
+ return desolve_rk4_inner(de[0][diff(dvar, ivar)].subs({dvar: dummy_dvar}), dummy_dvar)
1380
+ else:
1381
+ return desolve_rk4_inner(de, dvar)
1382
+
1383
+
1384
+ def desolve_system_rk4(des, vars, ics=None, ivar=None, end_points=None, step=0.1):
1385
+ r"""
1386
+ Solve numerically a system of first-order ordinary differential
1387
+ equations using the `4`-th order Runge-Kutta method. Wrapper for
1388
+ Maxima command ``rk``.
1389
+
1390
+ INPUT:
1391
+
1392
+ Input is similar to ``desolve_system`` and ``desolve_rk4`` commands
1393
+
1394
+ - ``des`` -- right hand sides of the system
1395
+
1396
+ - ``vars`` -- dependent variables
1397
+
1398
+ - ``ivar`` -- (optional) should be specified, if there are more variables or
1399
+ if the equation is autonomous and the independent variable is
1400
+ missing
1401
+
1402
+ - ``ics`` -- initial conditions in the form ``[x0,y01,y02,y03,....]``
1403
+
1404
+ - ``end_points`` -- the end points of the interval
1405
+
1406
+ - if ``end_points`` is a or [a], we integrate on between ``min(ics[0], a)`` and ``max(ics[0], a)``
1407
+ - if ``end_points`` is None, we use ``end_points=ics[0]+10``
1408
+
1409
+ - if ``end_points`` is [a,b] we integrate on between ``min(ics[0], a)`` and ``max(ics[0], b)``
1410
+
1411
+ - ``step`` -- (default: 0.1) the length of the step
1412
+
1413
+ OUTPUT: a list of points
1414
+
1415
+ .. SEEALSO::
1416
+
1417
+ :func:`ode_solver`.
1418
+
1419
+ EXAMPLES::
1420
+
1421
+ sage: from sage.calculus.desolvers import desolve_system_rk4
1422
+
1423
+ Lotka Volterra system::
1424
+
1425
+ sage: from sage.calculus.desolvers import desolve_system_rk4
1426
+ sage: x,y,t = var('x y t')
1427
+ sage: P = desolve_system_rk4([x*(1-y),-y*(1-x)], [x,y], ics=[0,0.5,2],
1428
+ ....: ivar=t, end_points=20)
1429
+ sage: Q = [[i,j] for i,j,k in P]
1430
+ sage: LP = list_plot(Q) # needs sage.plot
1431
+
1432
+ sage: Q = [[j,k] for i,j,k in P]
1433
+ sage: LP = list_plot(Q) # needs sage.plot
1434
+
1435
+ ALGORITHM:
1436
+
1437
+ `4`-th order Runge-Kutta method. Wrapper for command ``rk`` in Maxima's
1438
+ dynamics package. Perhaps could be faster by using ``fast_float``
1439
+ instead.
1440
+
1441
+ AUTHOR:
1442
+
1443
+ - Robert Marik (10-2009)
1444
+ """
1445
+ if ics is None:
1446
+ raise ValueError("No initial conditions, specify with ics=[x0,y01,y02,...].")
1447
+
1448
+ ivars = set()
1449
+
1450
+ for de in des:
1451
+ ivars = ivars.union(set(de.variables()))
1452
+ if ivar is None:
1453
+ ivars = ivars - set(vars)
1454
+ if len(ivars) != 1:
1455
+ raise ValueError("Unable to determine independent variable, please specify.")
1456
+ ivar = list(ivars)[0]
1457
+
1458
+ dess = [de._maxima_().str() for de in des]
1459
+ desstr = "[" + ",".join(dess) + "]"
1460
+ varss = [varsi._maxima_().str() for varsi in vars]
1461
+ varstr = "[" + ",".join(varss) + "]"
1462
+ x0 = ics[0]
1463
+ icss = [ics[i]._maxima_().str() for i in range(1, len(ics))]
1464
+ icstr = "[" + ",".join(icss) + "]"
1465
+ step = abs(step)
1466
+
1467
+ maxima("load('dynamics)")
1468
+ lower_bound, upper_bound = desolve_rk4_determine_bounds(ics, end_points)
1469
+ sol_1, sol_2 = [], []
1470
+ if lower_bound < ics[0]:
1471
+ cmd = "rk(%s,%s,%s,[%s,%s,%s,%s])\
1472
+ " % (desstr, varstr, icstr, '_SAGE_VAR_' + str(ivar), str(x0), lower_bound, -step)
1473
+ sol_1 = maxima(cmd).sage()
1474
+ sol_1.pop(0)
1475
+ sol_1.reverse()
1476
+ if upper_bound > ics[0]:
1477
+ cmd = "rk(%s,%s,%s,[%s,%s,%s,%s])\
1478
+ " % (desstr, varstr, icstr, '_SAGE_VAR_' + str(ivar), str(x0), upper_bound, step)
1479
+ sol_2 = maxima(cmd).sage()
1480
+ sol_2.pop(0)
1481
+ sol = sol_1
1482
+ sol.append(ics)
1483
+ sol.extend(sol_2)
1484
+
1485
+ return sol
1486
+
1487
+
1488
+ def desolve_odeint(des, ics, times, dvars, ivar=None, compute_jac=False, args=(),
1489
+ rtol=None, atol=None, tcrit=None, h0=0.0, hmax=0.0, hmin=0.0, ixpr=0,
1490
+ mxstep=0, mxhnil=0, mxordn=12, mxords=5, printmessg=0):
1491
+ r"""
1492
+ Solve numerically a system of first-order ordinary differential equations
1493
+ using :func:`scipy:scipy.integrate.odeint`.
1494
+
1495
+ INPUT:
1496
+
1497
+ - ``des`` -- right hand sides of the system
1498
+
1499
+ - ``ics`` -- initial conditions
1500
+
1501
+ - ``times`` -- a sequence of time points in which the solution must be found
1502
+
1503
+ - ``dvars`` -- dependent variables. ATTENTION: the order must be the same as
1504
+ in ``des``, that means: ``d(dvars[i])/dt=des[i]``
1505
+
1506
+ - ``ivar`` -- independent variable, optional
1507
+
1508
+ - ``compute_jac`` -- boolean (default: ``False``); if ``True``, the
1509
+ Jacobian of ``des`` is computed and used during the integration of stiff
1510
+ systems
1511
+
1512
+ Other Parameters (taken from the documentation of the
1513
+ :func:`~scipy:scipy.integrate.odeint` function from
1514
+ :mod:`scipy:scipy.integrate`):
1515
+
1516
+ - ``rtol``, ``atol`` : float
1517
+ The input parameters ``rtol`` and ``atol`` determine the error
1518
+ control performed by the solver. The solver will control the
1519
+ vector, `e`, of estimated local errors in `y`, according to an
1520
+ inequality of the form:
1521
+
1522
+ max-norm of (e / ewt) <= 1
1523
+
1524
+ where ewt is a vector of positive error weights computed as:
1525
+
1526
+ ewt = rtol * abs(y) + atol
1527
+
1528
+ ``rtol`` and ``atol`` can be either vectors the same length as `y` or scalars.
1529
+
1530
+ - ``tcrit`` : array
1531
+ Vector of critical points (e.g. singularities) where integration
1532
+ care should be taken.
1533
+
1534
+ - ``h0`` : float, (0: solver-determined)
1535
+ The step size to be attempted on the first step.
1536
+
1537
+ - ``hmax`` : float, (0: solver-determined)
1538
+ The maximum absolute step size allowed.
1539
+
1540
+ - ``hmin`` : float, (0: solver-determined)
1541
+ The minimum absolute step size allowed.
1542
+
1543
+ - ``ixpr`` : boolean.
1544
+ Whether to generate extra printing at method switches.
1545
+
1546
+ - ``mxstep`` : integer, (0: solver-determined)
1547
+ Maximum number of (internally defined) steps allowed for each
1548
+ integration point in t.
1549
+
1550
+ - ``mxhnil`` : integer, (0: solver-determined)
1551
+ Maximum number of messages printed.
1552
+
1553
+ - ``mxordn`` : integer, (0: solver-determined)
1554
+ Maximum order to be allowed for the nonstiff (Adams) method.
1555
+
1556
+ - ``mxords`` : integer, (0: solver-determined)
1557
+ Maximum order to be allowed for the stiff (BDF) method.
1558
+
1559
+ OUTPUT: a list with the solution of the system at each time in ``times``
1560
+
1561
+ EXAMPLES:
1562
+
1563
+ Lotka Volterra Equations::
1564
+
1565
+ sage: from sage.calculus.desolvers import desolve_odeint
1566
+ sage: x,y = var('x,y')
1567
+ sage: f = [x*(1-y), -y*(1-x)]
1568
+ sage: sol = desolve_odeint(f, [0.5,2], srange(0,10,0.1), [x,y]) # needs scipy
1569
+ sage: p = line(zip(sol[:,0],sol[:,1])) # needs scipy sage.plot
1570
+ sage: p.show() # needs scipy sage.plot
1571
+
1572
+ Lorenz Equations::
1573
+
1574
+ sage: x,y,z = var('x,y,z')
1575
+ sage: # Next we define the parameters
1576
+ sage: sigma = 10
1577
+ sage: rho = 28
1578
+ sage: beta = 8/3
1579
+ sage: # The Lorenz equations
1580
+ sage: lorenz = [sigma*(y-x),x*(rho-z)-y,x*y-beta*z]
1581
+ sage: # Time and initial conditions
1582
+ sage: times = srange(0,50.05,0.05)
1583
+ sage: ics = [0,1,1]
1584
+ sage: sol = desolve_odeint(lorenz, ics, times, [x,y,z], # needs scipy
1585
+ ....: rtol=1e-13, atol=1e-14)
1586
+
1587
+ One-dimensional stiff system::
1588
+
1589
+ sage: y = var('y')
1590
+ sage: epsilon = 0.01
1591
+ sage: f = y^2*(1-y)
1592
+ sage: ic = epsilon
1593
+ sage: t = srange(0,2/epsilon,1)
1594
+ sage: sol = desolve_odeint(f, ic, t, y, # needs scipy
1595
+ ....: rtol=1e-9, atol=1e-10, compute_jac=True)
1596
+ sage: p = points(zip(t,sol[:,0])) # needs scipy sage.plot
1597
+ sage: p.show() # needs scipy sage.plot
1598
+
1599
+ Another stiff system with some optional parameters with no
1600
+ default value::
1601
+
1602
+ sage: y1,y2,y3 = var('y1,y2,y3')
1603
+ sage: f1 = 77.27*(y2+y1*(1-8.375*1e-6*y1-y2))
1604
+ sage: f2 = 1/77.27*(y3-(1+y1)*y2)
1605
+ sage: f3 = 0.16*(y1-y3)
1606
+ sage: f = [f1,f2,f3]
1607
+ sage: ci = [0.2,0.4,0.7]
1608
+ sage: t = srange(0,10,0.01)
1609
+ sage: v = [y1,y2,y3]
1610
+ sage: sol = desolve_odeint(f, ci, t, v, rtol=1e-3, atol=1e-4, # needs scipy
1611
+ ....: h0=0.1, hmax=1, hmin=1e-4, mxstep=1000, mxords=17)
1612
+
1613
+ AUTHOR:
1614
+
1615
+ - Oriol Castejon (05-2010)
1616
+ """
1617
+
1618
+ from scipy.integrate import odeint
1619
+ from sage.ext.fast_eval import fast_float
1620
+ from sage.calculus.functions import jacobian
1621
+
1622
+ def desolve_odeint_inner(ivar):
1623
+ # one-dimensional systems:
1624
+ if len(dvars) == 1:
1625
+ assert len(des) == 1
1626
+ dvar = dvars[0]
1627
+ de = des[0]
1628
+ func = fast_float(de, dvar, ivar)
1629
+ if not compute_jac:
1630
+ Dfun = None
1631
+ else:
1632
+ J = diff(de, dvar)
1633
+ J = fast_float(J, dvar, ivar)
1634
+
1635
+ def Dfun(y, t):
1636
+ return [J(y.item(), t)]
1637
+
1638
+ # n-dimensional systems:
1639
+ else:
1640
+ variabs = dvars[:]
1641
+ variabs.append(ivar)
1642
+ desc = [fast_float(de, *variabs) for de in des]
1643
+
1644
+ def func(y, t):
1645
+ v = list(y[:])
1646
+ v.append(t)
1647
+ return [dec(*v) for dec in desc]
1648
+
1649
+ if not compute_jac:
1650
+ Dfun = None
1651
+ else:
1652
+ J = jacobian(des, dvars)
1653
+ J = [list(v) for v in J]
1654
+ J = fast_float(J, *variabs)
1655
+
1656
+ def Dfun(y, t):
1657
+ v = list(y[:])
1658
+ v.append(t)
1659
+ return [[element(*v) for element in row] for row in J]
1660
+
1661
+ return odeint(func, ics, times, args=args, Dfun=Dfun, rtol=rtol, atol=atol,
1662
+ tcrit=tcrit, h0=h0, hmax=hmax, hmin=hmin, ixpr=ixpr, mxstep=mxstep,
1663
+ mxhnil=mxhnil, mxordn=mxordn, mxords=mxords, printmessg=printmessg)
1664
+
1665
+ if isinstance(dvars, Expression) and dvars.is_symbol():
1666
+ dvars = [dvars]
1667
+
1668
+ if not isinstance(des, (list, tuple)):
1669
+ des = [des]
1670
+
1671
+ if ivar is None:
1672
+ all_vars = set().union(*[de.variables() for de in des])
1673
+ ivars = all_vars - set(dvars)
1674
+
1675
+ if len(ivars) == 1:
1676
+ return desolve_odeint_inner(next(iter(ivars)))
1677
+ elif not ivars:
1678
+ from sage.symbolic.ring import SR
1679
+ with SR.temp_var() as ivar:
1680
+ return desolve_odeint_inner(ivar)
1681
+ else:
1682
+ raise ValueError("Unable to determine independent variable, please specify.")
1683
+ return desolve_odeint_inner(ivar)
1684
+
1685
+
1686
+ def desolve_mintides(f, ics, initial, final, delta, tolrel=1e-16, tolabs=1e-16):
1687
+ r"""
1688
+ Solve numerically a system of first order differential equations using the
1689
+ taylor series integrator implemented in mintides.
1690
+
1691
+ INPUT:
1692
+
1693
+ - ``f`` -- symbolic function; its first argument will be the independent
1694
+ variable, . Its output should be de derivatives of the dependent variables.
1695
+
1696
+ - ``ics`` -- list or tuple with the initial conditions
1697
+
1698
+ - ``initial`` -- the starting value for the independent variable
1699
+
1700
+ - ``final`` -- the final value for the independent value
1701
+
1702
+ - ``delta`` -- the size of the steps in the output
1703
+
1704
+ - ``tolrel`` -- the relative tolerance for the method
1705
+
1706
+ - ``tolabs`` -- the absolute tolerance for the method
1707
+
1708
+ OUTPUT: list with the positions of the IVP
1709
+
1710
+ EXAMPLES:
1711
+
1712
+ We integrate a periodic orbit of the Kepler problem along 50 periods::
1713
+
1714
+ sage: var('t,x,y,X,Y')
1715
+ (t, x, y, X, Y)
1716
+ sage: f(t,x,y,X,Y)=[X, Y, -x/(x^2+y^2)^(3/2), -y/(x^2+y^2)^(3/2)]
1717
+ sage: ics = [0.8, 0, 0, 1.22474487139159]
1718
+ sage: t = 100*pi
1719
+ sage: sol = desolve_mintides(f, ics, 0, t, t, 1e-12, 1e-12) # optional -tides
1720
+ sage: sol # optional -tides # abs tol 1e-5
1721
+ [[0.000000000000000,
1722
+ 0.800000000000000,
1723
+ 0.000000000000000,
1724
+ 0.000000000000000,
1725
+ 1.22474487139159],
1726
+ [314.159265358979,
1727
+ 0.800000000028622,
1728
+ -5.91973525754241e-9,
1729
+ 7.56887091890590e-9,
1730
+ 1.22474487136329]]
1731
+
1732
+
1733
+ ALGORITHM:
1734
+
1735
+ Uses TIDES.
1736
+
1737
+ REFERENCES:
1738
+
1739
+ - A. Abad, R. Barrio, F. Blesa, M. Rodriguez. Algorithm 924. *ACM
1740
+ Transactions on Mathematical Software* , *39* (1), 1-28.
1741
+
1742
+ - A. Abad, R. Barrio, F. Blesa, M. Rodriguez.
1743
+ `TIDES tutorial: Integrating ODEs by using the Taylor Series Method.
1744
+ <https://web.archive.org/web/20120206041615/http://www.unizar.es/acz/05Publicaciones/Monografias/MonografiasPublicadas/Monografia36/IndMonogr36.htm>`_
1745
+ """
1746
+ import subprocess
1747
+ if subprocess.call('command -v gcc', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE):
1748
+ raise RuntimeError('Unable to run because gcc cannot be found')
1749
+ from sage.interfaces.tides import genfiles_mintides
1750
+ from sage.misc.temporary_file import tmp_dir
1751
+ tempdir = tmp_dir()
1752
+ intfile = os.path.join(tempdir, 'integrator.c')
1753
+ drfile = os.path.join(tempdir, 'driver.c')
1754
+ fileoutput = os.path.join(tempdir, 'output')
1755
+ runmefile = os.path.join(tempdir, 'runme')
1756
+ genfiles_mintides(intfile, drfile, f, [N(_) for _ in ics],
1757
+ N(initial), N(final), N(delta), N(tolrel),
1758
+ N(tolabs), fileoutput)
1759
+ subprocess.check_call('gcc -o ' + runmefile + ' ' + os.path.join(tempdir, '*.c ') +
1760
+ os.path.join('$SAGE_LOCAL', 'lib', 'libTIDES.a') + ' $LDFLAGS '
1761
+ + os.path.join('-L$SAGE_LOCAL', 'lib ') + ' -lm -O2 ' +
1762
+ os.path.join('-I$SAGE_LOCAL', 'include '),
1763
+ shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1764
+ subprocess.check_call(os.path.join(tempdir, 'runme'), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1765
+ with open(fileoutput) as outfile:
1766
+ res = outfile.readlines()
1767
+ for i in range(len(res)):
1768
+ res[i] = [RealField()(_) for _ in res[i].split(' ') if len(_) > 2]
1769
+ shutil.rmtree(tempdir)
1770
+ return res
1771
+
1772
+
1773
+ def desolve_tides_mpfr(f, ics, initial, final, delta, tolrel=1e-16, tolabs=1e-16, digits=50):
1774
+ r"""
1775
+ Solve numerically a system of first order differential equations using the
1776
+ taylor series integrator in arbitrary precision implemented in tides.
1777
+
1778
+ INPUT:
1779
+
1780
+ - ``f`` -- symbolic function; its first argument will be the independent
1781
+ variable. Its output should be de derivatives of the dependent variables.
1782
+
1783
+ - ``ics`` -- list or tuple with the initial conditions
1784
+
1785
+ - ``initial`` -- the starting value for the independent variable
1786
+
1787
+ - ``final`` -- the final value for the independent value
1788
+
1789
+ - ``delta`` -- the size of the steps in the output
1790
+
1791
+ - ``tolrel`` -- the relative tolerance for the method
1792
+
1793
+ - ``tolabs`` -- the absolute tolerance for the method
1794
+
1795
+ - ``digits`` -- the digits of precision used in the computation
1796
+
1797
+ OUTPUT: list with the positions of the IVP
1798
+
1799
+ EXAMPLES:
1800
+
1801
+ We integrate the Lorenz equations with Saltzman values for the parameters
1802
+ along 10 periodic orbits with 100 digits of precision::
1803
+
1804
+ sage: var('t,x,y,z')
1805
+ (t, x, y, z)
1806
+ sage: s = 10
1807
+ sage: r = 28
1808
+ sage: b = 8/3
1809
+ sage: f(t,x,y,z)= [s*(y-x),x*(r-z)-y,x*y-b*z]
1810
+ sage: x0 = -13.7636106821342005250144010543616538641008648540923684535378642921202827747268115852940239346395038284
1811
+ sage: y0 = -19.5787519424517955388380414460095588661142400534276438649791334295426354746147526415973165506704676171
1812
+ sage: z0 = 27
1813
+ sage: T = 15.586522107161747275678702092126960705284805489972439358895215783190198756258880854355851082660142374
1814
+ sage: sol = desolve_tides_mpfr(f, [x0, y0, z0], 0, T, T, 1e-100, 1e-100, 100) # optional - tides
1815
+ sage: sol # optional -tides # abs tol 1e-50
1816
+ [[0.000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000,
1817
+ -13.7636106821342005250144010543616538641008648540923684535378642921202827747268115852940239346395038,
1818
+ -19.5787519424517955388380414460095588661142400534276438649791334295426354746147526415973165506704676,
1819
+ 27.0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000],
1820
+ [15.5865221071617472756787020921269607052848054899724393588952157831901987562588808543558510826601424,
1821
+ -13.7636106821342005250144010543616538641008648540923684535378642921202827747268115852940239346315658,
1822
+ -19.5787519424517955388380414460095588661142400534276438649791334295426354746147526415973165506778440,
1823
+ 26.9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999636628]]
1824
+
1825
+
1826
+ ALGORITHM:
1827
+
1828
+ Uses TIDES.
1829
+
1830
+
1831
+ .. WARNING::
1832
+
1833
+ This requires the package tides.
1834
+
1835
+ REFERENCES:
1836
+
1837
+ - [ABBR2011]_
1838
+ - [ABBR2012]_
1839
+ """
1840
+ import subprocess
1841
+ if subprocess.call('command -v gcc', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE):
1842
+ raise RuntimeError('Unable to run because gcc cannot be found')
1843
+ from sage.interfaces.tides import genfiles_mpfr
1844
+ from sage.functions.other import ceil
1845
+ from sage.functions.log import log
1846
+ from sage.misc.temporary_file import tmp_dir
1847
+ tempdir = tmp_dir()
1848
+ intfile = os.path.join(tempdir, 'integrator.c')
1849
+ drfile = os.path.join(tempdir, 'driver.c')
1850
+ fileoutput = os.path.join(tempdir, 'output')
1851
+ runmefile = os.path.join(tempdir, 'runme')
1852
+ genfiles_mpfr(intfile, drfile, f, ics, initial, final, delta, [], [],
1853
+ digits, tolrel, tolabs, fileoutput)
1854
+ subprocess.check_call('gcc -o ' + runmefile + ' ' + os.path.join(tempdir, '*.c ') +
1855
+ os.path.join('$SAGE_LOCAL', 'lib', 'libTIDES.a') + ' $LDFLAGS '
1856
+ + os.path.join('-L$SAGE_LOCAL', 'lib ') + '-lmpfr -lgmp -lm -O2 -w ' +
1857
+ os.path.join('-I$SAGE_LOCAL', 'include '),
1858
+ shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1859
+ subprocess.check_call(os.path.join(tempdir, 'runme'), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1860
+ with open(fileoutput) as outfile:
1861
+ res = outfile.readlines()
1862
+ for i in range(len(res)):
1863
+ res[i] = [RealField(ceil(digits * log(10, 2)))(piece)
1864
+ for piece in res[i].split(' ') if len(piece) > 2]
1865
+ shutil.rmtree(tempdir)
1866
+ return res