I'm comparing the results of convolution in Python (using sympy's symbolic variables) and Mathematica with its Convolve function.
In Python, my MWE is
from numpy import linspace, pi
from numpy.random import randn
from scipy.signal import fftconvolve
import matplotlib.pyplot as plt
from sympy import symbols
from sympy.utilities.lambdify import lambdify
a = 0.43
b = 0.41
c = 0.65
d = 0.71
x = symbols('x')
f = 2*b / ((x-a)**2 + b**2)
g = 2*d / ((x-c)**2 + d**2)
fog = fftconvolve(f,g,mode='same')
fog_fun = lambdify(x,fog,'numpy') # returns a numpy-ready function
x = linspace(-20,20,int(1e3))
dx = x[1]-x[0]
fogS = fog_fun(x)
fogA = 4*pi*(b+d)/((x-a-c)**2+(b+d)**2) # correct analytic solution
plt.figure()
plt.plot(x,fogA,lw=2,label='analytic')
plt.plot(x,fogS,lw=2,label='sympy')
plt.grid()
plt.legend(loc='best')
plt.show()
which calculates a convolution using symbolic variable x. The resulting function (before lambdifying) is
fog = 1.1644/(((x - 0.65)**2 + 0.5041)*((x - 0.43)**2 + 0.1681))
There is no agreement between analytic (fogA, Mathematica) and sympy (fogS, Python):
My Mathematica code is:
a = 0.43; b = 0.41; c = 0.65; d = 0.71;
fogA = FullSimplify[Convolve[2*b/((t-a)^2+b^2),2*d/((t-c)^2+d^2), t, x]];
fogS = 1.1644/(((x - 0.65)^2 + 0.5041)*((x - 0.43)^2 + 0.1681));
where
fogA = (17.683+x*(-30.4006+14.0743*x))/(3.04149+x*(-7.9428+x*(8.3428+x*(-4.32+1.*x))))
and graphs for fogS and fogA are the same as for Python.
Why is there such a large disagreement between the analytic and sympy solution? I suspect the problem lies with sympy. Another Pythonic method is to convolve two arrays which seems to agree with the analytic solution.
f = 2*b / ((x-a)**2 + b**2)
g = 2*d / ((x-c)**2 + d**2)
fogN = fftconvolve(f,g,mode='same')*dx # numeric
(Note: this is a MWE. The actual f and g I want to convolve are much more complicated than the Lorentzians defined in this post.)
I do not think this is a reasonable way of using scipy + sympy.
I am actually quite surprised that you get a result from lambdify at all.
What you should be doing, instead of using scipy.signal.fftconvolve(), is to use a symbolic definition of the convolution, e.g.:
from sympy import oo, Symbol, integrate
def convolve(f, g, t, lower=-oo, upper=oo):
tau = Symbol('__very_unlikely_name__', real=True)
return integrate(
f.subs(t, tau) * g.subs(t, t - tau), (tau, lower, upper))
adapted from here.
Related
I am solving an ODE with Sympy. The equation is
ODE
To solve it, I used this little code, which returns this result.
from sympy import *
from numpy import *
import matplotlib.pyplot as plt
x = symbols('x')
y = Function('y')
f = y(x)
print(f)
edo = Eq(f.diff()+3*x**2*f, 6*x**2)
print(edo)
edoSolve = dsolve(edo, f)
print(edoSolve)
C1*exp(-x**3) + 2
My question is, how can I plot the result with x being a range from 0 to 10?
Firstly it's problematic to combine these two lines:
from sympy import *
from numpy import *
These two libraries define many functions with the same names and mixing those together will lead to problems. For clarity it is better to do something like:
import sympy as sym
import numpy as np
You can only plot a sympy expression if you give numbers for all of the symbols apart from the one that you want to plot against (i.e. x in this example). That means that you need to have a concrete value for the integration constant C1. You can get that by giving an initial conditions (ics) argument to dsolve. Also since dsolve returns an equation you need to choose a side of the equation as the expression that you want to plot. Having done that the sym.plot function will do precisely what you ask for:
In [10]: import sympy as sym
In [11]: sol = sym.dsolve(edo, f, ics={f.subs(x, 0): 1})
In [12]: sol
Out[12]:
3
-x
y(x) = 2 - ℯ
In [13]: sym.plot(sol.rhs, (x, 0, 10))
Out[13]: <sympy.plotting.plot.Plot at 0x7f346de1caf0>
If you want to show solutions for multiple values for C1 together, you could append plots:
from sympy import symbols, Function, Eq, dsolve, plot
x = symbols('x')
y = Function('y')
f = y(x)
edo = Eq(f.diff() + 3 * x ** 2 * f, 6 * x ** 2)
edoSolve = dsolve(edo, f)
plot1 = plot(show=False)
for c1 in range(-5, 6):
plotc1 = plot(edoSolve.subs('C1', c1).rhs, (x, 0, 10), show=False)
plot1.append(plotc1[0])
plot1.show()
How to solve a ODE,I have tried to use scipy.integrate.odeint, but what should I do if I don't know the initial value,
That's what I've defined:
alpha=0.204
beta=0.196
b=5.853
c=241.38
def Left_equation(x):
return alpha * x
def Right_equation(x):
return (b * (x ** 2)) + c
def diff_equation(x, t):
return (t ** beta) * (Right_equation(x) - Left_equation(x))
I also want to get the graph of the result,I don't know if I need to get the analytic solution first.
If the initial condition is not known, then the integration would need to be done symbolically. The Python package sympy can be used for symbolic integration of ordinary differential equations, as follows (using the function sympy.dsolve):
"""How to integrate symbolically an ordinary differential equation."""
import sympy
def main():
alpha = 0.204
beta = 0.196
b = 5.853
c = 241.38
t = sympy.symbols('t')
x = sympy.Function('x')(t)
dxdt = sympy.Derivative(x, t)
e = (t**beta) * ((b * (x**2)) + c - alpha * x)
x_eq = sympy.dsolve(dxdt - e)
if __name__ == '__main__':
main()
For this example, the function sympy.solvers.ode.ode.dsolve raises the exception PolynomialDivisionFailed. But the above code shows how to do symbolic integration.
An alternative is to numerically solve the differential equation (for specific initial condition), and compute solutions for a range of initial conditions, to explore how the solution depends on the initial condition. Using the function scipy.integrate.odepack.odeint of the Python package scipy, and the Python packages matplotlib and numpy, this can be done as follows:
"""How to integrate numerically an ordinary differential equation."""
from matplotlib import pyplot as plt
import numpy as np
import scipy.integrate
def main():
x0 = np.linspace(0, 0.2, 10) # multiple alternative initial conditions
t = np.linspace(0, 0.01, 100) # where to solve
x = scipy.integrate.odeint(deriv, x0, t)
# plot results
plt.plot(t, x)
plt.xlabel('t')
plt.ylabel('x')
plt.grid(True)
plt.show()
def deriv(x, t):
alpha = 0.204
beta = 0.196
b = 5.853
c = 241.38
return (t ** beta) * ((b * (x**2)) + c - alpha * x)
if __name__ == '__main__':
main()
As noted though in the documentation of the function scipy.integrate.odeint:
For new code, use scipy.integrate.solve_ivp to solve a differential equation.
The function scipy.integrate.solve_ivp can be used as follows:
"""How to integrate numerically an ordinary differential equation."""
from matplotlib import pyplot as plt
import numpy as np
import scipy.integrate
def main():
x0 = np.linspace(0, 0.2, 10) # multiple alternative initial conditions
t = (0.0, 0.01) # where to solve: (start, end)
res = scipy.integrate.solve_ivp(deriv, t, x0) # different order of
# arguments than for the function `scipy.integrate.odeint`
# plot results
plt.plot(res.t, res.y.T)
plt.xlabel('t')
plt.ylabel('x')
plt.grid(True)
plt.show()
def deriv(t, x): # not x, t as for the function `scipy.integrate.odeint`
alpha = 0.204
beta = 0.196
b = 5.853
c = 241.38
return (t ** beta) * ((b * (x**2)) + c - alpha * x)
if __name__ == '__main__':
main()
Please note the differences in arguments between the function scipy.integrate.odeint and the function scipy.integrate.solve_ivp.
The above code produces the following plot:
I am working on the following code, which solves a system of coupled differential equations. I have been able to solve them, and I plotted one of them. I am curious how to compute and plot the derivative of this graph numerically (I know the derivative is given in the first function, but suppose I didn't have that). I was thinking that I could use a for-loop, but is there a faster way?
import numpy as np
from scipy.integrate import odeint
from scipy.interpolate import interp1d
import matplotlib.pyplot as plt
import math
def hiv(x,t):
kr1 = 1e5
kr2 = 0.1
kr3 = 2e-7
kr4 = 0.5
kr5 = 5
kr6 = 100
h = x[0] # Healthy Cells -- function of time
i= x[1] #Infected Cells -- function of time
v = x[2] # Virus -- function of time
p = kr3 * h * v
dhdt = kr1 - kr2*h - p
didt = p - kr4*i
dvdt = -p -kr5*v + kr6*i
return [dhdt, didt, dvdt]
print(hiv([1e6, 0, 100], 0))
x0 = [1e6, 0, 100] #initial conditions
t = np.linspace(0,15,1000) #time in years
x = odeint(hiv, x0, t) #vector of the functions H(t), I(t), V(t)
h = x[:,0]
i = x[:,1]
v = x[:,2]
plt.semilogy(t,h)
plt.show()
I need to obtain a derivative to use it later in numerical calculations. And my code doesn't work at all. I tried to use lambdify but the error is "can't convert symbols int". I read other answers for similar questions but it still doesn't work.
import numpy as np
from scipy.integrate import odeint
from scipy.integrate import quad
from scipy.integrate import solve_bvp as bvp
import matplotlib.pyplot as plt
from scipy.special import genlaguerre as L
from scipy.special import gamma as G
from math import factorial
from math import sqrt
import sympy as sym
from sympy.utilities.lambdify import lambdify
mp = 938.2720813
mn = 939.5654133
mu = (mn + mp)/4
hbar = 197.3270533
h2m = hbar**2/(2*mu)
V0 = 20
Rv = 1.5
Q0 = 1.5
Rq = 4.5
EIm = 0.3
ERe = 1
V = lambda r : -V0*np.exp(-r/Rv)
Q = lambda r : -Q0*np.exp(-r/Rq)
chi = lambda r, l : sqrt(factorial(l)*beta**3/(G(3 + l))) * r * L(l,2)(beta * r) * np.exp(- beta * r / 2)
r, l, beta = sym.symbols('r, l, beta')
def chifD(r, l, beta):
return sqrt(factorial(l)*beta**3/(G(3 + l))) * r * L(l,2)(beta * r) * np.exp(- beta * r / 2)
def chiD(r, l, beta):
return sym.diff(chifD(r ,l, beta), r)
print(chiD(r, l, beta))
chiLambdified = lambdify(((r,l, beta),),chiD(r,l, beta),"numpy")
print(chiD(1, 1, 1))
I'm pretty sure you're mixing modules you shouldn't. I kept modifying your chi function until I got something that works. Nothing short of removing all math and scipy functions returned something that wasn't a TypeError.
# works with sympy sqrt.
chi = lambda r, l : sym.sqrt(l*r)
print(chi(r,l))
# doesn't work with math or numpy sqrt.
chi = lambda r, l : math.sqrt(l*r)
print(chi(r,l))
If you want to use functions, you'll have to use the ones that come with sympy, define your own using basic operators (so that sympy objects will be accepted) or find simpler ways to define your operations: sqrt() can simply be substituted by **(1/2).
Maybe you should look for a way that can make sympy accept functions from other modules because writing all of the special functions from scipy yourself looks like it will be a pain.
This code only works for solving the differential equation v_equation if v(t) isn't squared. When I squared it it returned the error PolynomialDivisionFailed. Is there another way of doing this with Sympy or should I find a different python package for doing these sorts of calculations.
from sympy import *
from matplotlib import pyplot as plt
import numpy as np
m = float(raw_input('Mass:\n> '))
g = 9.8
k = float(raw_input('Drag Coefficient:\n> '))
f1 = g * m
t = Symbol('t')
v = Function('v')
v_equation = dsolve(f1 - k * (v(t) ** 2) - m * Derivative(v(t)), 0)
C1 = Symbol('C1')
C1_ic = solve(v_equation.rhs.subs({t:0}),C1)[0]
v_equation = v_equation.subs({C1:C1_ic})
func = lambdify(t, v_equation.rhs,'numpy')
From my experience with symbolic math packages, I would not recommend performing (symbolic) calculations using floating point constants. It is better to define equations using symbolic constants, perform calculations as far as possible, and then substitute with numerical values.
With this approach, Sympy can provide a solution for this D.E.
First, define symbolic constants. To aid calculations, note that we can provide additional information about these constants (e.g., real, positive, e.t.c)
import sympy as sp
t = sp.symbols('t', real = True)
g, k, m = sp.symbols('g, k, m', real = True, positive = True)
v = sp.Function('v')
The symbolic solution for the DE can be obtained as follows
f1 = g * m
eq = f1 - k * (v(t) ** 2) - m * sp.Derivative(v(t))
sol = sp.dsolve(eq,v(t)).simplify()
The solution sol will be a function of k, m, g, and a constant C1. In general, there will be two, complex C1 values corresponding to the initial condition. However, both values of C1 result in the same (real-valued) solution when substituted in sol.
Note that if you don't need a symbolic solution, a numerical ODE solver, such as Scipy's odeint, may be used. The code would be the following (for an initial condition 0):
from scipy.integrate import odeint
def fun(v, t, m, k, g):
return (g*m - k*v**2)/m
tn = np.linspace(0, 10, 101)
soln = odeint(fun, 0, tn, args=(1000, 0.2, 9.8))
soln is an array of samples v(t) corresponding to the tn elements