我有一个函数,我需要对它进行依赖于一个参数的偏导数,然后在另一个函数中使用它,然后解一个常微分方程组,我需要导出的函数是关于θ和φ的无向性能量
import sympy
import numpy as np
from sympy import Symbol, diff, sin, cos
theta = Symbol('theta')
phi = Symbol('phi')
theta_k = Symbol('theta_k')
phi_k = Symbol('phi_k')
def anizotropy_energy(theta, phi, theta_k, phi_k):
u_rx = sin(theta)*sin(phi)
u_ry = sin(theta)*sin(phi)
u_rz = cos(theta)
u_kx = sin(theta_k)*cos(phi_k)
u_ky = sin(theta_k)*sin(phi_k)
u_kz = cos(theta_k)
u_kx*u_rx + u_ky*u_ry + u_kz*u_rz
diff((u_kx*u_rx + u_ky*u_ry + u_kz*u_rz)**2, theta)
我是用sympy做的,但我不能在odeint使用这些Derivates 我有一个中间函数,在这个中间函数中,我必须把θ和φ加到一个结构中,然后在主程序中使用这个函数
中间功能:
import math
import numpy as np
from anisotropy_energy import anizotropy_energy
def thetafunc_anisotropy(alpha,theta,phi, hx, hy, hz, theta_k, phi_k):
return alpha*(hx*np.cos(theta)*np.cos(phi) + hy*np.cos(theta)*np.sin(phi)- \
hz*np.sin(theta) + \
anizotropy_energy(theta, phi, theta_k, phi_k) + \
(-hx*np.sin(phi) + hy*np.cos(phi))
# diff(anizotropy_energy(theta, phi, theta_k, phi_k), phi) )
主要方案:
import matplotlib as mpl
from scipy.integrate import odeint
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import thetafunc_anizotropy
from thetafunc_anizotropy import thetafunc_anisotropy
import phifunc_anizotropy
from phifunc_anizotropy import phifunc_anisotropy
import sympy
def LLG(y, t, alpha, hx, hy, hz, theta_k, phi_k):
theta, phi = y
dydt = [thetafunc_anisotropy(alpha,theta,phi, hx, hy, hz, theta_k, phi_k), thetafunc_anisotropy(alpha,theta,phi, hx, hy, hz, theta_k, phi_k)]
return dydt
alpha = 0.1
H = 1.0
t0 = 60.0*np.pi/180.0
p0 = 0.0*np.pi/180.0
hx = H*np.sin(t0)*np.cos(p0)
hy = H*np.sin(t0)*np.sin(p0)
hz = H*np.cos(t0)
theta_k = 60.0*np.pi/180.0
phi_k = 60.0*np.pi/180.0
y0 = [np.pi, -0*np.pi]
t = np.linspace(0, 1000, 10000)
sol = odeint(LLG, y0, t, args=(alpha,hx, hy, hz, theta_k, phi_k ))
print sol
mpl.rcParams['legend.fontsize'] = 10
#
fig = plt.figure()
ax = fig.gca(projection='3d')
#x = np.sol[:, 0]
#y = sol[:, 1]
#ax.plot(x, y, label='parametric curve')
#ax.legend()
x = np.sin(sol[:, 0])*np.cos(sol[:, 1])
y = np.sin(sol[:, 0])*np.sin(sol[:, 1])
z = np.cos(sol[:, 0])
ax.plot(x, y, z, label='parametric curve')
ax.legend()
#plt.show()
#plt.axes(projection='3d')
#plt.plot(t, sol[:, 0], 'b', label='$\\theta(t)$')
#plt.plot(t,sol[:,1], 'r', label='$\\varphi(t)$')
#
#plt.legend(loc='best')
#plt.xlabel('t')
#
#plt.grid()
#plt.show()
你的错误是无向性_能量.py. 您有与函数参数同名的全局变量。 在本例中,您有一个名为theta和phi的全局参数以及名为theta和phi的函数参数。必须重命名其中一对。 我把函数参数θ和φ标为inθ和inφ。你真的应该给它们改名。你知道吗
另外,注意在有些地方你说anis各向异性,有些地方你说aniz各向异性。你知道吗
相关问题 更多 >
编程相关推荐