[PYTHON] [Poincare recurrence theorem] I tried playing with 100 snake pendulums expanded to a long period ♬

Since it is a mass game, I think that it is meaningless (natural), but considering the planetary series etc., I think that such calculations are actually meaningful, so I will summarize it. After all, Poincare's recurrence theorem. I reminded myself that the dynamical system is meaningful as a concrete example of "if certain conditions are met, it almost returns to its arbitrary initial state within a finite time." In addition, the calculation and simulation of the planet series will not be done this time. So, this time, I would like to freely change the number and cycle of previous formula.

Simulation of 100 pieces per dance for 120 seconds

And it is an extension in the case of 100 pieces. This is not possible with the previous formula, so change it as follows.

N = 60
z0 =500
L0=980*(120/130)**2/(2*np.pi)**2
Fc0=1.0
Fc=[]
fc=1
Fc.append(fc)
for i in range(1,100,1):
    fc=fc*((131-i)/(130-i))
    Fc.append(fc)

Also, since it was restored in 120 seconds, the result is as follows.

I tried playing by simulating 100 snake pendulums ♬ <img src="http://img.youtube.com/vi/cDJWJdXN4Q4/0.jpg "

Simulation of 15 pieces per dance for 120 seconds

This time, let's dance 15 pendulums with a period of 120 seconds. This shows that virtually any number, length and period of pendulums can be designed. [Snake pendulum] I made a simulation of 15 pieces for 120 seconds per dance and played with it ♬ <img src="http://img.youtube.com/vi/oe34YS3I5QE/0.jpg " The main code could be achieved below.

N = 60
L0=980*(120/65)**2/(2*np.pi)**2  #120 here/65 of 120 is important
print(L0, 2*np.pi/np.sqrt(980/L0))
Fc0=1.0
z0 =150
Fc=[]
fc=1
Fc.append(fc)
for i in range(1,15,1):
    fc=fc*((66-i)/(65-i))  #65/Adjust the shift of each one with 64
    Fc.append(fc)

dataz=[]
linez=[]
y=0
for j in range(15):
    y += 2  #Pendulum y-axis spacing
    dataz0 = np.array(list(genxy(N,L=L0*Fc[j]**2,z0=z0,y0=y))).T
    linez0, = ax.plot(dataz0[0, 0:1], dataz0[1, 0:1], dataz0[2, 0:1],'o')
    dataz.append(dataz0)
    linez.append(linez0)

Compared to the previous one, the generator has been expanded so that it can be arranged in the y-axis direction as follows.

def genxy(n,L=20,z0=0,y0=0):
    phi = 0
    g = 980
    x0=5  #2.5
    omega = np.sqrt(g/L)
    theta0 = np.arcsin(x0/L)
    while phi < 600:
        yield np.array([L*np.sin(np.sin(phi*omega+np.pi/2)*theta0), y0,z0-L+L*(1-np.cos(np.sin(phi*omega+np.pi/2)*theta0))])
        phi += 1/n

Summary

-Expanded the number and length of snake pendulums so that they can be freely changed. ・ The overwhelming power of 100 pieces and the long period of 120 seconds are interesting in terms of appreciation.

・ I would like to simulate the realization of Poincare's recurrence theorem in the natural world such as the planetary series. ・ I want to realize a real snake pendulum in a free cycle

bonus

from matplotlib import pyplot as plt
import numpy as np
import mpl_toolkits.mplot3d.axes3d as p3
from matplotlib import animation

fig, ax = plt.subplots(1,1,figsize=(1.6180 * 4, 4*1),dpi=200)
ax = p3.Axes3D(fig)

def genxy(n,L=20,z0=0,y0=0):
    phi = 0
    g = 980
    x0=5
    omega = np.sqrt(g/L)
    theta0 = np.arcsin(x0/L)
    while phi < 600:
        yield np.array([L*np.sin(np.sin(phi*omega+np.pi/2)*theta0), y0,z0-L+L*(1-np.cos(np.sin(phi*omega+np.pi/2)*theta0))])
        phi += 1/n
        
def update(num, data, line,s):
    line.set_data(data[:2,num-1 :num])
    line.set_3d_properties(data[2,num-1 :num])
    ax.set_xticklabels([])
    ax.grid(False)
    
N = 60
L0=980*(120/65)**2/(2*np.pi)**2
print(L0, 2*np.pi/np.sqrt(980/L0)) #84.6cm 1.846sec
Fc0=1.0   #omega=2pi/T
z0 =150
Fc=[]
fc=1
Fc.append(fc)
for i in range(1,15,1):
    fc=fc*((66-i)/(65-i))
    Fc.append(fc)

dataz=[]
linez=[]
y=0
for j in range(15):
    y += 2
    dataz0 = np.array(list(genxy(N,L=L0*Fc[j]**2,z0=z0,y0=y))).T
    linez0, = ax.plot(dataz0[0, 0:1], dataz0[1, 0:1], dataz0[2, 0:1],'o')
    dataz.append(dataz0)
    linez.append(linez0)

# Setting the axes properties
ax.set_xlim3d([-10., 10])
ax.set_xlabel('X')

ax.set_ylim3d([0.0, 30.0])
ax.set_ylabel('Y')

ax.set_zlim3d([0.0, z0-L0])
ax.set_zlabel('Z')
elev=0 #20. 
azim=90 #35.
ax.view_init(elev, azim)

frames =60*120
fr0=60
s0=0
s=s0

while 1:
    s+=1
    num = s
    for j in range(15):        
        update(num,dataz[j],linez[j],s0)
    """
    if s%fr0==0:
        print(s/fr0, s)
    plt.pause(0.001)    
    """

    if s%(fr0/10)==0:
        ax.set_title("s={}_sec".format(int(10*s/fr0)/10),loc='center')
        plt.pause(0.001)
        print(s/fr0)
        plt.savefig('./pendulum/'+str(int(10*s/fr0))+'.png')
        if s>=s0+frames:
            break

s0=30*120
s=s0+30*120
fr0=60
from PIL import Image,ImageFilter
images = []
for n in range(1,1201,1):
    exec('a'+str(n)+'=Image.open("./pendulum/'+str(n)+'.png ")')
    images.append(eval('a'+str(n)))
images[0].save('./pendulum/pendulum_{}_.gif'.format(100),
               save_all=True,
               append_images=images[1:],
               duration=100,
               loop=1)

Save video

I can't paste the gif animation, so save the mp4 file with the following code and upload it to youtube.

from matplotlib import pyplot as plt
import numpy as np
import mpl_toolkits.mplot3d.axes3d as p3
import cv2

def cv_fourcc(c1, c2, c3, c4):
        return (ord(c1) & 255) + ((ord(c2) & 255) << 8) + \
            ((ord(c3) & 255) << 16) + ((ord(c4) & 255) << 24)

OUT_FILE_NAME = "output_video.mp4"
fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
dst = cv2.imread('./pendulum/1.png')
rows,cols,channels = dst.shape
out = cv2.VideoWriter(OUT_FILE_NAME, int(fourcc), int(10), (int(cols), int(rows)))

from PIL import Image,ImageFilter
for n in range(1,1201,1):
    dst = cv2.imread('./pendulum/'+str(n)+'.png')
    out.write(dst) #Output to mp4 or avi

Recommended Posts

[Poincare recurrence theorem] I tried playing with 100 snake pendulums expanded to a long period ♬
I tried to create a table only with Django
I tried to draw a route map with Python
I tried to automatically generate a password with Python3
[Introduction to AWS] I tried playing with voice-text conversion ♪
I tried to implement a volume moving average with Quantx
I tried to solve a combination optimization problem with Qiskit
I tried to get started with Hy ・ Define a class
I tried to sort a random FizzBuzz column with bubble sort.
I tried to divide with a deep learning language model
[5th] I tried to make a certain authenticator-like tool with python
[2nd] I tried to make a certain authenticator-like tool with python
A memorandum when I tried to get it automatically with selenium
[3rd] I tried to make a certain authenticator-like tool with python
[Python] A memo that I tried to get started with asyncio
I tried to create a list of prime numbers with python
I tried to make a periodical process with Selenium and Python
I tried to make a 2channel post notification application with Python
I tried to create Bulls and Cows with a shell program
I tried to make a todo application using bottle with python
[4th] I tried to make a certain authenticator-like tool with python
[1st] I tried to make a certain authenticator-like tool with python
I tried to make a strange quote for Jojo with LSTM
I tried to make a mechanism of exclusive control with Go
I tried to introduce a serverless chatbot linked with Rakuten API to Teams
Python: I tried to make a flat / flat_map just right with a generator
I tried to implement a blockchain that actually works with about 170 lines
I tried to create a program to convert hexadecimal numbers to decimal numbers with python
I tried to create a plug-in with HULFT IoT Edge Streaming [Development] (2/3)
I tried to make a calculator with Tkinter so I will write it
I tried to make "Sakurai-san" a LINE BOT with API Gateway + Lambda
I tried to draw a system configuration diagram with Diagrams on Docker
I tried to make a traffic light-like with Raspberry Pi 4 (Python edition)
I tried to create a plug-in with HULFT IoT Edge Streaming [Execution] (3/3)
I tried to discriminate a 6-digit number with a number discrimination application made with python
I tried to send a registration completion email from Gmail with django.
[Outlook] I tried to automatically create a daily report email with Python
I tried to create a plug-in with HULFT IoT Edge Streaming [Setup] (1/3)
I tried to build a Mac Python development environment with pythonz + direnv
I tried to make a url shortening service serverless with AWS CDK
I tried to implement a card game of playing cards in Python
I tried to create a linebot (implementation)
I tried to implement Autoencoder with TensorFlow
I tried to create a linebot (preparation)
I tried to visualize AutoEncoder with TensorFlow
I tried to get started with Hy
I tried playing a ○ ✕ game using TensorFlow
I tried a functional language with Python
I tried to implement CVAE with PyTorch
I tried playing with the image with Pillow
I tried to make a Web API
I tried to solve TSP with QAOA
I tried to make a periodical process with CentOS7, Selenium, Python and Chrome
I tried to make a simple mail sending application with tkinter of Python
When I tried to make a VPC with AWS CDK but couldn't make it
[Patent analysis] I tried to make a patent map with Python without spending money
When I tried to create a virtual environment with Python, it didn't work
I tried to make a castle search API with Elasticsearch + Sudachi + Go + echo
[ES Lab] I tried to develop a WEB application with Python and Flask ②
When I tried to connect with SSH, I got a warning about free space.
I tried to easily create a fully automatic attendance system with Selenium + Python