Issue
I have a function Q which takes 3 arguments, x, y, and z. How can I plot Q vs. x,y and z? Here is my code:
from scipy.special import ellipk, ellipe, ellipkm1
from numpy import pi, sqrt, linspace
from pylab import plot, xlabel, ylabel, suptitle, legend, show
from mpl_toolkits import mplot3d
import numpy as np
uo = 4*pi # Permeability constant - units of milligauss
u=uo
N=18
i=0.4
a=0.413
#z=0.214
r= lambda x,y: sqrt(x**2+y**2)
k = lambda x, y, z, a: sqrt((4*sqrt(x**2+y**2)*a)/(a**2+(sqrt(x**2+y**2+z**2))**2+2*a*sqrt(x**2+y**2))) # k = f(distance to meas. point, loop radius)
K = lambda k: ellipk(k**2.0)
E = lambda k: ellipe(k**2.0)
def Q(x,y,z):
return np.where(((x==0)) & (y==0), 0, (((N*u*i)/(2.0*pi))*(x*z)/(((x**2+y**2)*sqrt(a**2+x**2+y**2+z**2+2*a*sqrt(x**2+y**2)))))*\
((E(k(x,y,z,a))*(a**2+x**2+y**2+z**2)/(a**2+x**2+y**2+z**2-2*a*sqrt(x**2+y**2))) - K(k(x,y,z,a))))
Solution
You can use check out 3D-contour plot to visualize the function Q(x, y, z)
as a 3D map over a range of x, y, and z. Here's an example with your code:
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
from scipy.special import ellipk, ellipe
uo = 4 * np.pi # Permeability constant - units of milligauss
u = uo
N = 18
i = 0.4
a = 0.413
#z=0.214
r = lambda x, y: np.sqrt(x**2 + y**2)
k = lambda x, y, z, a: np.sqrt((4 * r(x, y) * a) / (a**2 + (r(x, y) + z)**2))
K = lambda k: ellipk(k**2.0)
E = lambda k: ellipe(k**2.0)
def Q(x, y, z):
return np.where((x == 0) & (y == 0), 0, ((N * u * i) / (2.0 * np.pi)) * (x * z) / ((x**2 + y**2) * np.sqrt(a**2 + x**2 + y**2 + z**2 + 2 * a * r(x, y))) *\
((E(k(x, y, z, a)) * (a**2 + x**2 + y**2 + z**2) / (a**2 + x**2 + y**2 + z**2 - 2 * a * r(x, y))) - K(k(x, y, z, a))))
# example grid in x, y, z space
x_vals = np.linspace(-1, 1, 50)
y_vals = np.linspace(-1, 1, 50)
z_vals = np.linspace(-1, 1, 50)
# Create mesh grid for 3D plot
X, Y, Z = np.meshgrid(x_vals, y_vals, z_vals)
# Calculate Q for each point in the grid
Q_vals = Q(np.ravel(X), np.ravel(Y), np.ravel(Z))
# Create 3D plot
fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(111, projection='3d')
# Plot the surface
img = ax.scatter(np.ravel(X), np.ravel(Y), np.ravel(Z), c=Q_vals, cmap='viridis')
# Adding color bar
cbar = fig.colorbar(img, shrink=0.5, aspect=5)
cbar.set_label('Q value')
# Labels and title
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_title('3D Map of Q(x, y, z)')
plt.show()
Output:
checkout more about 3D-plotting from here: https://matplotlib.org/stable/gallery/index.html#d-plotting
Answered By - Musabbir Arrafi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.