Issue
I have this computation (integral and then summation)
The result is s
it is in term of independent variables x
and t
.
But, when I try to define it as u(x,t)
with return s
, it cannot replace the x
variable with the one I define as x = np.linspace(0, 20, 50)
and the t
variable as t = np.linspace(0, 10, 50)
. I think it is still following x
that is defined by sympy at the beginning, the same happens with t
.
I want to draw a 3D plot / the wireframe of this. the Z
axis is the u(x,t)
. Hopefully anyone can help me on this.
My MWE:
import numpy as np
import sympy as sm
from sympy import *
#from spb import *
#from mpmath import nsum, inf
x = sm.symbols("x")
t = sm.symbols("t")
n = sm.symbols("n", integer=True)
L = 20
f1 = (2/L)*x*sin(n*np.pi*x/20)
f2 = (2/L)*(20-x)*sin(n*np.pi*x/20)
fint1 = sm.integrate(f1,(x,0,10))
fint2 = sm.integrate(f2,(x,10,20))
D = 0.475
g = (fint1+fint2)*sin(n*np.pi*x/20)*exp(-(n**2)*(np.pi**2)*D*t/400).nsimplify()
print('')
sm.pretty_print(g)
#gn = g.subs({n:1})
s = 0
for c in range(10):
s += g.subs({n:c})
print(s)
print('')
print('The function u(x,t) : ')
print('')
sm.pretty_print(s)
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
# defining surface and axes
x = np.linspace(0, 20, 50)
t = np.linspace(0, 10, 50)
def u(x, t):
return s
X, T = np.meshgrid(x, t)
Z = u(X, T)
print('')
print('u(x,t)')
print(Z)
#fig = plt.figure()
# syntax for 3-D plotting
#ax = plt.axes(projection='3d')
# syntax for plotting
#ax.plot_wireframe(X,T,Z, cmap='viridis',edgecolor='green')
#ax.set_title('Wireframe')
#plt.show()
Solution
First option: use sm.lambdify
to convert s
to a numerical function which can later be evaluated.
xx, tt = np.mgrid[0:20:n, 0:10:n]
f = sm.lambdify((x, t), s)
fig = plt.figure()
n=30j
ax = fig.add_subplot(projection="3d")
ax.plot_wireframe(xx, tt, f(xx, tt))
ax.set_xlabel("x")
ax.set_ylabel("t")
Second option: use SymPy Plotting Backend. With it, you can avoid using sm.lambdify
and Numpy. Everything is dealt by the module.
plot3d(
s, (x, 0, 20), (t, 0, 10), {"alpha": 0}, # hide the surface
wireframe=True, wf_n1=20, wf_n2=10,
wf_rendering_kw={"color": "tab:blue"} # optional step to customize the wireframe lines
)
The advantage of this module is that you can use different plotting libraries. For example, Plotly is better at 3D visualizations:
plot3d(
s, (x, 0, 20), (t, 0, 10),
wireframe=True, wf_n1=20, wf_n2=10,
backend=PB
)
Answered By - Davide_sd
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.