Я пытаюсь построить анимацию простого маятника, используя модель https://matplotlib.org/gallery/animation/double_pendulum_sgskip.html.
Мой код выглядит следующим образом:
from numpy import sin, cos
import numpy as np
import matplotlib.pyplot as plt
import scipy.integrate as integrate
import matplotlib.animation as animation
#some constants
g = 9.81
l = 0.1
m = 0.01
def sh(r,t):
theta = r[0]
omega = r[1]
sh_theta = omega
sh_omega = -g/l*sin(theta)
return np.array([sh_theta,sh_omega],float)
init_state = [np.radians(89.0),0]
time = np.arange(0,50.0,0.025)
time_elapsed = time
def step_solver(eq, ist, dt):
"""
Execute one time step of length dt and update status
"""
global time_elapsed
state1,state2 = integrate.odeint(eq,ist,[0,dt])
time_elapsed += dt
return state1, state2,time_elapsed
dt = 1/30
ysol,ysolv,timex = step_solver(sh,init_state,dt)
print("This is the y0 values: ", ysol,"y values",ysolv,"This is the time ", timex)
##===================================
##Setting up figure and animation
#======================================
fig = plt.figure()
ax = plt.axes(xlim = (0,2), ylim = (-2,2))
line, = ax.plot([],[],lw=2)
#time_text = ax.text(0.02,0.95,'',transform = ax.transAxes)
#==========================================
##initialisation function: plot the background of each frame
def init():
line.set_data([],[])
#time_text.set_text('')
return line,
def animate(ysol,timex):
x = timex
y = ysol
line.set_data(x,y)
#time_text.set_text(str(i))
return line,
#================================================
#Call the animator
#================================================
anim = animation.FuncAnimation(fig,animate(ysolv,timex), init_func = init, frames = 200, interval =20, blit = True)
anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])
plt.show()
РЕДАКТИРОВАТЬ: Я получаю сообщение об ошибке:
ValueError: shape mismatch: objects cannot be broadcast to a single shape
<Figure size 432x288 with 1 Axes>
Я проверил, что моя функция step_solver печатает с
print(len(ysol),len(ysolv),len(timex))
, и после рекомендации другой вывод y для odeint, который дал только 2значения для моей переменной ysol и ysolv для 2200 значений времени.
Я ожидал получить диапазон значений y для каждого временного шага.Я не уверен, как это отсортировать.Моя функция step_solver неправильно закодирована?Почему я получаю только 2 значения, как я могу анимировать решение так же, как это было сделано для двойного маятника?
Есть предложения о том, где может быть проблема?Спасибо заранее.