Thursday, March 28, 2024

PMAE 7 : regular star polygon

Python Matplotlib Animation Example7

regular star polygon

The Python code presented utilizes matplotlib to dynamically visualize a regular star polygon, employing mathematical principles to compute its coordinates. The getdata function calculates these coordinates based on the number of vertices (n) and a parameter (k) determining the star's density. Trigonometric functions are employed for computation. The update function dynamically updates the plot with generated coordinates as the animation progresses, controlled by the drawfig function for timing and theta calculation. Through the FuncAnimation class, the animation smoothly portrays the rotation of the star polygon, showcasing its geometric properties. This code exemplifies Python's capacity for mathematical visualization, facilitating both exploration and representation of complex geometric concepts in an interactive manner.

 

 

The Python code skillfully animates a regular star polygon by first leveraging a function called getdata to accurately compute the vertices of the star based on the desired number of points and a scaling factor. It then harnesses the power of Matplotlib for visualization, creating a clean and well-defined figure. The animation is achieved through a time-dependent loop that continuously updates the plot with a calculated portion of the star's points, masterfully generating the illusion of smooth rotation. This code showcases a deep understanding of both geometric principles and Python's plotting and animation tools, resulting in an informative and visually engaging experience.

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, 0.0, 1.0, 1.0])
ax.set_xlim([-1.2, 1.2])
ax.set_ylim([-1.2, 1.2])
ax.axis("off")

def getdata(n, k):
nth = 3000
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 = cos(sth/2*k)
y2 = y1*(tan(sth/2*k)*x2)/(tan(sth/2)*x1)
x3 = x2*cos(rth*k) + y2*sin(rth*k)
y3 = -x2*sin(rth*k) + y2*cos(rth*k)
xs.append(x3)
ys.append(y3)
xs.append(xs[0])
ys.append(ys[0])
return xs, ys

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

xs, ys = getdata(5, 2)

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

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

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

plt.show()

 ■ Import Necessary Libraries:

   • `time` for time-based operations
• `matplotlib.pyplot` for creating visualizations
• `matplotlib.animation` for animating the plot
• `math` for mathematical functions

■ Figure Setup:
• Create a figure with a white background and square dimensions.
• Define axes with limits ranging from -1.2 to 1.2 for both x and y.
• Turn off axis labels and ticks for visual clarity.

■ Polygon Data Generation (`getdata` Function):
• Takes two parameters: the number of points (`n`) and a scaling factor (`k`).
• Calculates the x and y coordinates of the star polygon's vertices using trigonometric functions and rotations.
• Returns lists of x and y coordinates for the polygon.

■ Initial Plot Creation:
• Create an empty plot with blue color for later updates.

■ Polygon Data Calculation:
• Call `getdata` to generate coordinates for a 5-pointed star with scale factor 2.

■ Animation Loop (`drawfig` Function):
• Calculate a time-dependent angle `theta`.
• Call `update` to update the plot with a portion of the polygon based on `theta`.

■ Plot Update (`update` Function):
• Determine how much of the polygon to display based on `theta`.
• Set the plot's data to the calculated portion of coordinates.

■ Animation Initialization:
• Create an animation using `matplotlib.animation.FuncAnimation`.
• Call `drawfig` repeatedly for animation, with a 40-millisecond interval.

■ Show the Animation:
• Display the animated plot using `plt.show()`.

Sunday, March 24, 2024

PMAE 6 : rounded rectangle

Python Matplotlib Animation Example 6

rounded rectangle

The provided Python code generates an animated plot of a rounded rectangle using matplotlib, initializing the figure and axes and defining parameters such as dimensions and curvature. Through trigonometric computations, the getdata function determines coordinates along the rectangle's outline, accounting for the specified curvature. The update function dynamically modifies the plot during animation, adjusting data points based on the current angle, while the draw function regulates animation timing. Utilizing FuncAnimation, the code orchestrates continuous plot updates, exemplifying matplotlib's capabilities and mathematical techniques for geometric manipulation in Python. This illustrative example showcases the transformation of a rounded rectangle over time, providing insights into graphical representation and animation methodologies.



This Python code animates a rotating, filled rounded rectangle using Matplotlib's libraries. It defines functions to generate the shape's data based on a radius value. The getdata function calculates corner points using trigonometric functions and adjusts them for smooth curvature. An animation loop continuously updates the visible portion of the rectangle. It receives a time-dependent angle, calculates the visible data points, and creates the illusion of rotation. This showcases how to create and animate a visually appealing rounded rectangle.

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, 1])
ax.set_ylim([-1, 1])
ax.axis('off')

thmin = 0
thmax = pi
nth = 100
dth = pi/(nth-1)

rmin = 0.5
rmax = 1.0
nr = 3
dr = (rmax-rmin)/(nr)

def getdata(rr):
if rr < 0.0: rr = 0.0
if rr > 1.0: rr = 1.0
nth = int(300/4)*4
dth = 2*pi/(nth)
sth = 2*pi/4
xmax = cos(sth/2)
ymax = sin(sth/2)
xsmall0 = xmax - xmax*rr
ysmall0 = ymax - ymax*rr
rsmall = xmax*rr
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
if abs(y1) > ysmall0:
if y1 == 0: sign = 1.0
else: sign = abs(y1)/(y1)
thsmall = (rsmall-(ymax-abs(y1)))/rsmall*pi/4
xsmall = cos(thsmall*sign)*rsmall
ysmall = sin(thsmall*sign)*rsmall
x1 = xsmall + xsmall0
y1 = ysmall + ysmall0*sign
x2 = x1*cos(rth) + y1*sin(rth)
y2 = -x1*sin(rth) + y1*cos(rth)
xs.append(x2)
ys.append(y2)
xs.append(xs[0])
ys.append(ys[0])
return xs, ys

xs, ys = getdata(0.5)

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

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

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()


■  Setting Up the Environment:
• Imports libraries for plotting (matplotlib) and animation.
• Creates a figure with a white background and an axis without labels or ticks.
• Defines parameters for angles and radii used in the animation.

■ Calculating Rounded Rectangle Points:
• The `getdata` function takes a radius value (`rr`) as input.
• It calculates trigonometric values based on a reference angle (`sth`).
• It iterates through a range of angles (`nth`) to define points along the rounded rectangle's edge.
• For points falling outside the rectangle due to curvature, it adjusts them using additional calculations to maintain a smooth shape.
• Finally, it returns lists containing the x and y coordinates of all the points for the rounded rectangle.

■ Creating the Initial Plot and Animation Functions:
• The code retrieves points for a medium radius and creates the initial plot of the rounded rectangle using `ax.plot`.
• The `update` function takes an angle (`theta`) as input. It calculates the number of points visible based on the rotation and updates the line plot data accordingly.
• The `draw` function is called repeatedly during the animation. It calculates a time-dependent angle, calls `update` to adjust the visible portion, and creates the illusion of rotation.

■ Running the Animation:
• `FuncAnimation` from matplotlib's animation library is used to initiate the animation process. It calls the `draw` function at set intervals (40 milliseconds in this case).
• Finally, `plt.show()` displays the animation on the screen.

Sunday, March 10, 2024

PMAE 5 : curved regular polygon

Python Matplotlib Animation Example 5

curved regular polygon

The provided Python code generates an animated plot of a curved regular polygon using the Matplotlib library. The polygon is dynamically drawn with a specified number of sides (in this case, 4), resulting in a visually appealing animation. The getdata function computes the coordinates of the polygon vertices based on the number of sides, utilizing trigonometric functions like cosine and sine. The update function progressively updates the plot during the animation, while the draw function, invoked by the animation framework, calculates the current angle of rotation for the polygon based on time, creating the illusion of continuous motion. The animation interval is set to 40 milliseconds, controlling the speed of the rotation and showcasing a smoothly rotating regular polygon within the specified plot limits. The code efficiently utilizes mathematical computations and animation functionalities from Matplotlib to generate an engaging visualization of a curved regular polygon. It's a concise and well-structured piece of code that leverages the strengths of Matplotlib for dynamic graphics generation.



This Python code animates a curved regular polygon. The getdata function calculates the coordinates for a curved shape by rotating smaller line segments. The animation function continuously reveals more segments as time progresses, creating the illusion of a curved polygon rotating and unfolding. Libraries like matplotlib handle plotting and animation. In essence, the code dynamically generates and animates a curved regular polygon with continuous motion. This animation hinges on a clever interplay of trigonometric functions, coordinate transformations, and Matplotlib's animation capabilities.

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
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(pi-sth/2+(theta-rth)) + cos(sth/2)*2
y1 = sin(pi-sth/2+(theta-rth))
x2 = x1*cos(rth) + y1*sin(rth)
y2 = -x1*sin(rth) + y1*cos(rth)
xs.append(x2)
ys.append(y2)
xs.append(xs[0])
ys.append(xs[0])
return xs, ys

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

xs, ys = getdata(4)

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()

■  Imports:
• Brings in `time`, `matplotlib.pyplot`, `matplotlib.animation`, and `math` for time-related functions, plotting, animation, and mathematical calculations.

■ Figure and Axes Setup:
• Creates a figure for the animation with a white background.
• Sets up axes with specified limits and turns off axis labels.

■ `getdata` Function:
• Takes the number of sides (`n`) as input.
• Calculates coordinates for a curved n-sided polygon using trigonometric functions.
• Returns lists of x- and y-coordinates representing the polygon's points.

■ Plotting Elements:
• Creates an empty plot with blue color for future updates.
• Calls `getdata(4)` to generate coordinates for a 4-sided polygon.

■ Animation Functions:
• `update(theta)`: Takes an angle `theta`, calculates which portion of the polygon to display based on `theta`, and updates the plot accordingly.
• `draw(i)`: Calculates a time-dependent angle `theta`, calls `update(theta)`, and handles animation frame updates.

■ Animation Creation:
• Uses `matplotlib.animation.FuncAnimation` to create a continuous animation based on the `draw` function.

■ Display:
• `plt.show()`: Shows the animated plot.