Monday, February 26, 2024

PMAE 4 : regular polygons resembling a Ferris wheel

Python Matplotlib Animation Example 4

regular polygons resembling a Ferris wheel

This Python code utilizes the Matplotlib library to generate an animated Ferris wheel-like visualization featuring rotating regular polygons. The animation continues indefinitely, showcasing polygons with varying numbers of sides rotating around a central point. The update function dynamically adjusts the positions of the polygons based on a rotating angle, creating an engaging and visually intriguing effect. The rotation speed is controlled by the P parameter in the draw function, and each frame is updated at a 40-millisecond interval. Users can customize parameters such as the number of polygon sides, colors, and animation speed to achieve different visual effects. Overall, this code delivers a captivating and customizable representation of regular polygons in continuous rotation, resembling a Ferris wheel.



This Python code visualizes a rotating Ferris wheel with attached regular polygons. It combines mathematical functions, animation libraries, and visualization tools to create a visually appealing and informative animation of a rotating Ferris wheel with various polygons attached. The code effectively simulates the rotation of different sized polygons, showcasing animation capabilities in Python.

Python source code

import time
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from math import cos, sin, tan, pi

fig = plt.figure(figsize=(3,3), facecolor="#FFFFFF")
ax = plt.axes([0, 0, 1, 1])
ax.set_xlim([-1.3, 1.3])
ax.set_ylim([-1.5, 1.1])
ax.axis('off')

def getdata(n):
nth = 361
dth = 2*pi/(nth-1)
sth = 2*pi/n
xs, ys = [], []
for ith in range(nth):
theta = ith*dth
rth = int(theta/sth)*sth
x1 = cos(sth/2)
y1 = tan(sth/2-(theta-rth))*x1
x2 = x1*cos(rth) + y1*sin(rth)
y2 = -x1*sin(rth) + y1*cos(rth)
xs.append(x2)
ys.append(y2)
return xs, ys

def getinit(n):
dth = 2*pi/8
theta = dth*(n-3)
x0 = cos(theta)
y0 = sin(theta)
return x0, y0

def getposdata(n):
x, y = getdata(n)
sth = 2*pi/n
x0, y0 = getinit(n)
xs, ys = [], []
for i in range(len(x)):
x3 = x[i]*cos(pi/2-sth/2) - y[i]*sin(pi/2-sth/2)
y3 = x[i]*sin(pi/2-sth/2) + y[i]*cos(pi/2-sth/2)
x4 = x3*0.2+x0
y4 = (y3-1)*0.2+y0
xs.append(x4)
ys.append(y4)
return xs, ys

def getwheel():
nth = 25
dth = 2*pi/(nth-1)
xs, ys = [], []
for ith in range(nth):
theta = ith*dth
x1 = cos(theta)
y1 = sin(theta)
xs.append(x1)
ys.append(y1)
if ith%3 == 0:
nth2 = 13
dth2 = 2*pi/(nth2-1)
for ith2 in range(nth2):
theta2 = ith2*dth2
x2 = cos(theta2)*0.05 + x1
y2 = sin(theta2)*0.05 + y1
xs.append(x2)
ys.append(y2)
xs.append(x1)
ys.append(y1)
return xs, ys

xs1, ys1 = getwheel()
xs2, ys2 = getposdata(3)
xs3, ys3 = getposdata(4)
xs4, ys4 = getposdata(5)
xs5, ys5 = getposdata(6)
xs6, ys6 = getposdata(7)
xs7, ys7 = getposdata(8)
xs8, ys8 = getposdata(9)
xs9, ys9 = getposdata(10)

pl1 = ax.plot(xs1, ys1, color="#000000", lw=2.5, zorder=0)[0]
pl2 = ax.plot(xs2, ys2, color="#0000FF", lw=2.5, zorder=1)[0]
pl3 = ax.plot(xs3, ys3, color="#0000FF", lw=2.5, zorder=1)[0]
pl4 = ax.plot(xs4, ys4, color="#0000FF", lw=2.5, zorder=1)[0]
pl5 = ax.plot(xs5, ys5, color="#0000FF", lw=2.5, zorder=1)[0]
pl6 = ax.plot(xs6, ys6, color="#0000FF", lw=2.5, zorder=1)[0]
pl7 = ax.plot(xs7, ys7, color="#0000FF", lw=2.5, zorder=1)[0]
pl8 = ax.plot(xs8, ys8, color="#0000FF", lw=2.5, zorder=1)[0]
pl9 = ax.plot(xs9, ys9, color="#0000FF", lw=2.5, zorder=1)[0]

def rotate(x, y, theta):
xp, yp = [], []
for i in range(len(x)):
x1 = x[i]*cos(theta) - y[i]*sin(theta)
y1 = x[i]*sin(theta) + y[i]*cos(theta)
xp.append(x1)
yp.append(y1)
return xp, yp

def shift(x, y, n, theta):
x0, y0 = getinit(n)
x0p = x0*cos(theta) - y0*sin(theta)
y0p = x0*sin(theta) + y0*cos(theta)
xp, yp = [], []
for i in range(len(x)):
x1 = x[i] + (x0p-x0)
y1 = y[i] + (y0p-y0)
xp.append(x1)
yp.append(y1)
return xp, yp


def update(theta):
xp, yp = rotate(xs1, ys1, theta); pl1.set_data(xp, yp)
xp, yp = shift(xs2, ys2, 3, theta); pl2.set_data(xp, yp)
xp, yp = shift(xs3, ys3, 4, theta); pl3.set_data(xp, yp)
xp, yp = shift(xs4, ys4, 5, theta); pl4.set_data(xp, yp)
xp, yp = shift(xs5, ys5, 6, theta); pl5.set_data(xp, yp)
xp, yp = shift(xs6, ys6, 7, theta); pl6.set_data(xp, yp)
xp, yp = shift(xs7, ys7, 8, theta); pl7.set_data(xp, yp)
xp, yp = shift(xs8, ys8, 9, theta); pl8.set_data(xp, yp)
xp, yp = shift(xs9, ys9, 10, theta); pl9.set_data(xp, yp)

def draw(i):
P = 20.0
t = time.time()
theta = t/P*2*pi%(2*pi)
update(theta)

ani = animation.FuncAnimation(fig, draw, interval=40)

plt.show()

This code creates an animation of regular polygons resembling a Ferris wheel. Here's a breakdown:

■ Imports:
• Libraries for plotting (`matplotlib.pyplot`) and animation (`matplotlib.animation`) are imported.
• Mathematical functions (cosine, sine, tangent, and pi) are imported from the `math` library.

■ Figure and Axes Setup:
• A figure is created with a size of 3x3 inches and a white background.
• Axes are added to the figure, and their limits and visibility are set for a clean appearance.

■ Data Generation Functions:
• `getdata(n)`: Generates a regular polygon with `n` sides. It calculates the x and y coordinates of each vertex based on the angle and radius.
• `getinit(n)`: Provides the initial position (x and y coordinates) for a polygon with `n` sides.
• `getposdata(n)`: Creates a smaller, shifted, and rotated version of the polygon based on the original data and initial position.
• `getwheel()`: Defines the large base polygon with smaller polygons attached at specific intervals, resembling the Ferris wheel structure.

■ Variable Initialization:
• Nine sets of data (x and y coordinates) are generated for each polygon using the functions above.
• Each set is assigned to a corresponding variable (`xs1`, `ys1`, etc.).

■ Plotting:
• Nine lines representing the polygons are plotted using `ax.plot` with different colors and line widths.

■ Rotation and Shifting Functions:
• `rotate(x, y, theta)`: Takes x and y coordinates and a rotation angle. It returns the rotated coordinates.
• `shift(x, y, n, theta)`: Takes x and y coordinates, the number of sides (`n`), and a rotation angle. It returns the shifted and rotated coordinates based on the initial position.

■ Animation Update Function:
• `update(theta)`: Takes a rotation angle (`theta`) as input.
• It updates the data (x and y coordinates) of each plotted line using the `shift` and `rotate` functions with appropriate arguments.
• This essentially rotates and shifts the individual polygons based on their defined parameters.

■ Animation Drawing Function:
• `draw(i)`: This function is called repeatedly during the animation loop.
• It calculates the rotation angle based on the current time and a desired animation period (`P`).
• It calls the `update` function to update the data for each polygon based on the calculated angle.

■ Animation Creation:
• `ani`: Creates an animation object using `FuncAnimation`.
• It specifies the figure (`fig`), the drawing function (`draw`), and the interval (40 milliseconds) between frame updates.

■ Display:
• `plt.show()`: Displays the generated animation.

Overall, this code effectively utilizes mathematical functions, data generation, animation techniques, and plotting libraries to create a visually appealing animation of regular polygons rotating like a Ferris wheel.



Sunday, February 25, 2024

PMAE 3 : grid plot of regular polygons

Python Matplotlib Animation Example 3

grid plot of regular polygons

The Python code utilizes the Matplotlib library to generate an animated grid plot of regular polygons. Employing trigonometric calculations, the code positions the polygons in a 4x4 grid and animates the plot, revealing diverse polygons over time. Each subplot features a regular polygon with an increasing number of sides, and the animation updates continuously, creating a dynamic and visually appealing pattern. The code achieves this by defining a function getdata to compute the vertices of regular polygons and utilizes the animation module of Matplotlib to update the plot at regular intervals. In summary, the code leverages Matplotlib to create an animated grid plot, showcasing a captivating sequence of regular polygons evolving in a visually compelling manner.



The code creates an animated grid of regular polygons, where each polygon has a different number of sides (from 3 to 18). The polygons are positioned in a 4x4 grid and smoothly transition between different shapes as the animation progresses. It utilizes trigonometry for accurate polygon generation and animation techniques for dynamic visualization, resulting in a visually appealing grid of evolving polygon shapes.

Python source code

import time
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from math import cos, sin, tan, pi

fig = plt.figure(figsize=(3,3), facecolor="#FFFFFF")
ax = plt.axes([0, 0, 1, 1])
ax.set_xlim([0, 1])
ax.set_ylim([0, 1])
ax.axis('off')

def getdata(n):
nth = int(500/n)*n+1
dth = 2*pi/(nth-1)
sth = 2*pi/n
xs, ys = [], []
for ith in range(nth):
theta = ith*dth
rth = int(theta/sth)*sth
x1 = cos(sth/2)
y1 = tan(sth/2-(theta-rth))*x1
x2 = x1*cos(rth) + y1*sin(rth)
y2 = -x1*sin(rth) + y1*cos(rth)
xs.append(x2)
ys.append(y2)
return xs, ys

nbin = 16
pl = [0 for i in range(nbin)]

def update(i):
if i > 0 and i%nbin == 0:
for j in range(nbin):
pl[j].set_data([], [])
ibin = i%nbin
ix = ibin%4
iy = ibin/4
n = ibin + 3
x0 = ix*1.0/4.0+1.0/8.0
y0 = (4-iy)*1.0/4.0-1.0/8.0
xs, ys = getdata(n)
for j in range(len(xs)):
xs[j] = xs[j]*0.1 + x0
ys[j] = ys[j]*0.1 + y0
pl[ibin] = ax.plot(xs, ys, color="#0000FF")[0]

def draw(i):
update(i)

ani = animation.FuncAnimation(fig, draw, interval=200)

plt.show()


This code creates an animation of a grid filled with regular polygons with varying numbers of sides.

■ Setting up the environment:
• Imports necessary libraries for plotting and animation (`matplotlib.pyplot`, `matplotlib.animation`, `math`).
   • Creates a figure and an axes object for plotting.
• Sets the axes limits and removes unnecessary labels.

■ Generating polygon data:
• Defines the `getdata` function:
• Takes the number of sides (`n`) as input.
• Calculates the number of points needed for a smooth curve (`nth`).
• Iterates through each point and calculates its coordinates using trigonometric functions.
• Returns lists of x and y coordinates for the polygon.

■ Animation loop:
• Defines `nbin` as the total number of plots in the grid (16 in this case).
• Creates a list `pl` to store plot objects.
• Defines the `update` function:
• Clears previous plots at regular intervals.
• Calculates the index (`ibin`) for the current plot in the animation sequence.
• Determines the number of sides for the current polygon based on `ibin`.
• Calculates the position of the polygon within the grid.
• Generates polygon coordinates using `getdata`.
• Updates the corresponding plot in the list with the new polygon.
• Defines the `draw` function:
• Calls `update` to update the plot for each frame.

■ Running the animation:
• Creates an animation object using `FuncAnimation`.
• Sets the figure, update function, and frame interval (200 milliseconds).
• Displays the animation using `plt.show()`.

Overall, this code effectively utilizes trigonometry and animation techniques to create a visually appealing visualization of regular polygons with varying side counts.

Saturday, February 24, 2024

PMAE 2 : rotating regular polygon

Python Matplotlib Animation Example 2

rotating regular polygon

This Python code utilizes the Matplotlib library to create an animated visualization of a rotating regular polygon. The polygon, defined by the getdata function, has five sides in this example, but you can adjust the number of sides as desired. The rotation of the polygon is animated based on the current time, providing a continuous rotation effect. The code employs trigonometric functions to calculate the coordinates of the polygon's vertices and updates the plot accordingly. The resulting plot showcases a dynamic and visually appealing animation of a regularly rotating polygon in a window.


The Python code effectively generates a regular polygon and animates its rotation using mathematical calculations and Matplotlib's animation capabilities. Key functions include getdata for calculating vertex coordinates, update for rotating the polygon, and draw for controlling animation timing and updating the plot. The code demonstrates the use of trigonometry for polygon generation and rotation, and highlights the importance of FuncAnimation for creating smooth animations in Matplotlib. While currently generating a pentagon, the getdata function can be modified to handle polygons with different numbers of sides.

Python source code

import time
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from math import cos, sin, tan, pi

fig = plt.figure(figsize=(3,3), facecolor="#FFFFFF")
ax = plt.axes([0, 0, 1, 1])
ax.set_xlim([-1.2, 1.2])
ax.set_ylim([-1.2, 1.2])
ax.axis('off')

def getdata(n):
nth = int(500/n)*n+1
dth = 2*pi/(nth-1)
sth = 2*pi/n
xs, ys = [], []
for ith in range(nth):
theta = ith*dth
rth = int(theta/sth)*sth
x1 = cos(sth/2)
y1 = tan(sth/2-(theta-rth))*x1
x2 = x1*cos(rth) + y1*sin(rth)
y2 = -x1*sin(rth) + y1*cos(rth)
xs.append(x2)
ys.append(y2)
return xs, ys

pl = ax.plot([], [], color="#0000FF")[0]

xs, ys = getdata(5)

def update(theta):
ith = int(theta/(2*pi/(len(xs)-1)))
xp, yp = [], []
for i in range(len(xs)):
x = xs[i]*cos(theta) - ys[i]*sin(theta)
y = xs[i]*sin(theta) + ys[i]*cos(theta)
xp.append(x)
yp.append(y)
pl.set_data(xp, yp)

def draw(i):
P = 10.0
t = time.time()
theta = t/P*2*pi%(2*pi)
update(theta)

ani = animation.FuncAnimation(fig, draw, interval=40)

plt.show()

This Python code creates an animation of a rotating regular polygon using the `matplotlib` library.

■ Import necessary libraries:
• `time`: Provides access to time-related functions for animation.
• `matplotlib.pyplot as plt`: Offers functionalities for creating plots and visualizations.
• `matplotlib.animation as animation`: Enables creating animations from sequences of images.
• `math`: Contains mathematical functions like `cos`, `sin`, `tan`, and `pi`.

■ Set up the figure and axes:
• `fig = plt.figure(figsize=(3,3), facecolor="#FFFFFF")`: Creates a figure with a specified size (3x3 inches) and white background.
• `ax = plt.axes([0, 0, 1, 1])`: Defines an axes object within the figure, occupying the entire area.
• `ax.set_xlim([-1.2, 1.2])`: Sets the x-axis limits from -1.2 to 1.2.
• `ax.set_ylim([-1.2, 1.2])`: Sets the y-axis limits from -1.2 to 1.2.
• `ax.axis('off')`: Hides the axes labels and tick marks for a cleaner visualization.

■ Define the `getdata` function:
• `getdata(n)`: This function takes the number of sides (`n`) of the regular polygon as input and returns the coordinates of its vertices.
• `nth = int(500/n)*n+1`: Calculates a suitable number of points (`nth`) for smooth visualization, ensuring at least one point per side.
• `dth = 2*pi/(nth-1)`: Calculates the angular increment (`dth`) between consecutive points on the polygon's perimeter.
• `sth = 2*pi/n`: Computes the central angle (`sth`) subtended by each side.
• The function iterates through `nth` points, calculating their x and y coordinates using trigonometric functions and transformations.
• `xs` and `ys` lists store the calculated x and y coordinates, respectively.
• The function returns `xs` and `ys`.

■ Initialize the plot:
• `pl = ax.plot([], [], color="#0000FF")[0]`: Creates an empty line plot (`pl`) with blue color, initially representing the polygon.

■ Define the `update` function:
• `update(theta)`: This function takes the rotation angle (`theta`) as input and updates the coordinates of the polygon's vertices.
• `ith = int(theta/(2*pi/(len(xs)-1)))`: Calculates the index of the vertex that should be at the "front" based on the current rotation angle.
• `xp` and `yp` lists are created to store the updated x and y coordinates.
• The function iterates through all vertices, applying the rotation transformation using `cos` and `sin` functions.
• The updated coordinates are appended to `xp` and `yp`.
• The line plot (`pl`) is updated with the new coordinates using `pl.set_data(xp, yp)`.

■ Define the `draw` function:
• `draw(i)`: This function is called repeatedly to produce animation frames.
• `P = 10.0`: Sets the animation period (`P`) to 10 seconds (controls the speed of rotation).
• `t = time.time()`: Gets the current time.
• `theta = t/P*2*pi%(2*pi)`: Calculates the rotation angle (`theta`) based on the elapsed time and animation period, ensuring it stays within a full circle (0 to 2pi).
• The `update` function is called with the calculated `theta` to update the polygon's position.

■ Create and display the animation:
• `ani = animation.FuncAnimation(fig, draw, interval=40)`: Creates an animation object (`ani`) using the `FuncAnimation` class.
• `fig`: The figure to be animated.
• `draw`: The function to be called for each frame.
• `interval=40`: The time interval (in milliseconds) between frames, controlling the animation speed.
• `plt.show()`: Displays the animation.

PMAE 1 : n-sided regular polygon

Python Matplotlib Animation Example 1

n-sided regular polygon

This Python code employs the Matplotlib library to produce an animated plot illustrating the construction and rotation of an n-sided regular polygon. The polygon evolves over time, gradually connecting points on a circle to create the desired shape. The animation is orchestrated through the draw function, which calculates the angle based on the elapsed time and updates the plot accordingly. By adjusting the argument in the getdata function, users can modify the number of sides, allowing for customization such as generating a hexagon by using getdata(6). The code provides a versatile and visually engaging tool for exploring different polygon shapes and animation speeds, making it a valuable resource for interactive visualization and experimentation.


This code animates an n-sided regular polygon rotating smoothly at a constant speed. You can adjust the number of sides (n) and animation speed (P) to explore different shapes and behaviors. The code uses efficient trigonometric calculations for point generation. Overall, it effectively generates and animates an n-sided polygon, providing a visualization of its rotation in a circle.

Python source code

import time
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from math import cos, sin, tan, pi

fig = plt.figure(figsize=(3,3), facecolor="#FFFFFF")
ax = plt.axes([0, 0, 1, 1])
ax.set_xlim([-1.2, 1.2])
ax.set_ylim([-1.2, 1.2])
ax.axis('off')

def getdata(n):
nth = 361
dth = 2*pi/(nth-1)
sth = 2*pi/n
xs, ys = [], []
for ith in range(nth):
theta = ith*dth
rth = int(theta/sth)*sth
x1 = cos(sth/2)
y1 = tan(sth/2-(theta-rth))*x1
x2 = x1*cos(rth) + y1*sin(rth)
y2 = -x1*sin(rth) + y1*cos(rth)
xs.append(x2)
ys.append(y2)
return xs, ys

pl = ax.plot([], [], color="#0000FF")[0]

xs, ys = getdata(8)

def update(theta):
ith = int(theta/(2*pi/(len(xs)-1)))
pl.set_data(xs[0:ith], ys[0:ith])

def draw(i):
P = 5.0
t = time.time()
theta = t/P*2*pi%(2*pi)
update(theta)

ani = animation.FuncAnimation(fig, draw, interval=40)

plt.show()

Summary:
This Python code generates and animates an n-sided regular polygon, where `n` is specified as an input value. It employs mathematical calculations, matplotlib, and animation functionalities to achieve this.

Code Breakdown:

■ Imports:
• `time`: Used for timing the animation.
• `matplotlib.pyplot as plt`: Provides plotting functions.
• `matplotlib.animation as animation`: Used for creating the animation.
• `math`: Provides mathematical functions like `cos`, `sin`, `tan`, and `pi`.

■ Figure and Axis Setup:
• A figure with a fixed size of 300x300 and white background is created.
• An axis is added within the figure, setting the x and y limits to [-1.2, 1.2] and turning off the axis labels and ticks.

■ `getdata` Function:
• Takes `n` (the number of sides) as input.
• Initializes `nth` to 361 (number of points to create) and `dth` to the angular distance between points based on `n`.
• Calculates the step angle `sth` between vertices of the polygon.
• Creates empty lists `xs` and `ys` to store x and y coordinates of points.
• Iterates `nth` times to generate points:
• Calculates the current angle `theta`.
• Rounds `theta` down to the nearest multiple of `sth` using `int(theta/sth)*sth`.
• Calculates intermediate values `x1` and `y1` based on `sth` and `theta`.
• Rotates the point by `rth` using `x2` and `y2`.
• Appends the point's coordinates to `xs` and `ys`.
• Returns `xs` and `ys`.

■ Line Plot Setup:
• Creates an empty line plot with a blue color in the axis.

■ Data Generation:
• Calls `getdata(8)` to get data for an 8-sided polygon and stores the points in `xs` and `ys`.

■ `update` Function:
• Takes a `theta` value as input.
• Calculates the index `ith` of the point corresponding to `theta` based on the angular distance between points and the number of points.
• Updates the line plot data using `pl.set_data(xs[0:ith], ys[0:ith])`, showing only points up to `ith`.

■ `draw` Function:
• Takes a frame number `i` as input (not used in this code).
• Sets a period `P` for the animation (5.0 seconds).
• Calculates the current time `t`.
• Calculates the animation angle `theta` based on `t`, `P`, and a 2*pi factor to ensure a full rotation within `P`.
• Calls `update(theta)` to update the line plot data.

■ Animation Creation:
• Creates an animation using `animation.FuncAnimation`.
• Sets the animation function to `draw`.
• Sets the update interval to 40 milliseconds.

■ Displaying the Animation:
• Calls `plt.show()` to display the animation.

Key Points:

○ The animation creates a rotating polygon with `n` sides.
○ The animation speed is controlled by the `P` value in the `draw` function.
○ The code can be modified to change the number of sides, animation speed, and other parameters.