# 出典 http://matsulib.hatenablog.jp/entry/2013/07/15/203419 （改造 M.Murata）
# （シェルウインドウでは　python cycloid.pyと入力して起動する）
# （以下はコードウインドウで作成）
# -*- coding:utf-8 -*-
from matplotlib import pyplot as plt
from matplotlib import animation
import numpy as np

def circle(a, b, r):	# 円の方程式の定義関数
  	#### 円の方程式 Circle (x-a)^2 + (y-b)^2 = r^2 ####
	T = 100				# 円周の分割数
	x, y = [0]*T, [0]*T
	for i,theta in enumerate(np.linspace(0,2*np.pi,T)):
		x[i] = a + r*np.cos(theta)
		y[i] = b + r*np.sin(theta)
	return x, y

R = 1					# 円の半径

def gen():				# 円周の座標を準備する
	for theta in np.linspace(0,3*np.pi,100):
		yield R*(theta-np.sin(theta)), R*(1-np.cos(theta)), R*theta

fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_ylim(-1, 6)		# y軸
ax.set_xlim(0, 10)		# x軸
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.grid()				# グリッド線
time_text = ax.text(0.05, 0.9, '', transform=ax.transAxes)

cycloid, 	= ax.plot([], [], 'r-', lw=2)	# サイクロイド曲線を赤で描く
radius,		= ax.plot([], [], 'y-', lw=2)	# 半径を黄色で描く
circle_arc,	= ax.plot([], [], 'g',  lw=2)	# 円弧を緑色で描く
point, 		= ax.plot([], [], 'bo', ms=4)	# 点を青で描く

xx, yy = [], []
def func(data):			# 描画をまとめて担当する関数
	x, y, Rt = data
	time_text.set_text('theta = %.2f pi' % (Rt/np.pi))
	xx.append(x)
	yy.append(y)
	cx, cy = circle(Rt, R, R)

	cycloid.set_data(xx, yy)
	radius.set_data((x,Rt), (y,R))
	circle_arc.set_data(cx, cy)
	point.set_data(x, y)

ani = animation.FuncAnimation(fig, func, gen, blit=False, interval=100, repeat=False)

# save または pltのどちらかを選ぶこと
#ani.save("cycloid.mp4")	# mp4でsave 
plt.show()					# 画面表示

