2024 Spring Practice Week 13 Lecture 12
2024 Spring Practice Week 13 Lecture 12
Hyeon-Seung Shin
Seoul National University
Graphics & Media Lab
Today’s features to practice
• NumPy
• Matplotlib
Today’s mission
• (1) Shoot the ball on the player as (2) playing music.
– Define Circle and Rectangle class.
• (optional) Define Shape class and let the classes above inherit from Shape.
– Draw a guideline between the ball and mouse cursor.
– Shoot the ball along the guideline with LMB pressed.
– Reposition the ball when it is out of the boundary.
– Play any music.
– (optional) Modularization
• Shape.py
• Circle.py
• Rectangle.py
• etc.
• Import the modules above in main source code file.
Lecture review (NumPy)
What is Numpy?
• NumPy (Numeric Python)
– Provides routines for arrays and matrices.
– Use numpy for large numerical computation.
– Each numpy dimension is called axis. The total number of axes is rank.
Introduction to NumPy Arrays
• NumPy’s array is a collection of values, organized in a specific order.
import numpy as np
arr = np.array([1,2,3,4,5])
print(arr)
[1 2 3 4 5]
y = x*2; print(y)
y = x**2; print(y)
y = numpy.sin(x); print(y)
import numpy as np 1
4
x = np.array([1, 2, 3, 4])
print(x[0])
y = np.array([[1,2],[3,4]])
print(y[1,1])
Slicing
import numpy as np [2 3 4 5]
[[3 4]
a = np.array([1, 2, 3, 4, 5, 6, 7]) [7 6]]
print(a[1:5])
b = np.array([[1,2,3],[3,4,5],[7,6,7]])
print(b[1:,:2])
Reshaping Arrays
• The shape of an array means the number of elements in each dimension.
new_a2 = new_a.reshape(12,)
print(new_a2)
Concatenating Arrays
import numpy as np [1 2 3 4 5 6]
[[1 2]
a1 = np.array([1, 2, 3]) [3 4]
a2 = np.array([4, 5, 6]) [5 6]
a = np.concatenate((a1, a2), axis=0) [7 8]]
print(a) [[1 2 5 6]
[3 4 7 8]]
b1 = np.array([[1, 2], [3, 4]])
b2 = np.array([[5, 6], [7, 8]])
b = np.concatenate((b1, b2), axis=0)
print(b) axis 1
c = np.concatenate((b1, b2), axis=1)
1 2
axis 0
print(c)
3 4
Advanced
NumPy Array
linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)
Source code
import numpy
Result
x = numpy.linspace(0, 10, num=5);
print(x, '\n') [ 0. 2.5 5. 7.5 10. ]
print(arr1 is arr2)
print(arr1 is not arr2)
numpy array (5 minutes)
import numpy as np 0
1
arr1 = np.array([0, 1, 2]) 2
print(arr1[0]) 3
print(arr1[0:2]) 0
print(arr1[:], "\n") 1.0
0.816496580927726
print(arr1.sum()) 0.6666666666666666
print(arr1.prod()) 0
print(arr1.mean()) 2
print(arr1.std())
print(arr1.var())
print(arr1.min())
print(arr1.max())
linspace (5 minutes)
import numpy (array([[ 0., 1., 2.],
[ 1., 3., 6.],
start = [0,1,2] [ 2., 5., 10.],
end = [5,11,22] [ 3., 7., 14.],
x = numpy.linspace( [ 4., 9., 18.]]), array([1., 2., 4.]))
start,
end, [[[ 0. 1. 2. ]
num=5, [ 1. 2. 3. ]
endpoint = False, [ 2. 3. 4. ]]
dtype = float,
retstep = True) [[ 2.5 5.75 9. ]
print(x, '\n') [ 5.75 9. 12.25]
[ 9. 12.25 15.5 ]]
start = [[0,1,2], [1,2,3], [2,3,4]]
end = [[10,20,30], [20,30,40], [30,40,50]] [[ 5. 10.5 16. ]
x = numpy.linspace( [10.5 16. 21.5 ]
start, [16. 21.5 27. ]]
end,
num = 5) [[ 7.5 15.25 23. ]
print(x) [15.25 23. 30.75]
[23. 30.75 38.5 ]]
plt.plot(x_vals, y_vals)
plt.show()
plt.plot(y_vals)
plt.show()
Drawing options
's' Square
'D' Diamond
• We can use the keyword argument “marker”.
'd' Diamond (thin)
'p' Pentagon
import matplotlib.pyplot as plt
import numpy as np 'H' Hexagon 'o' Circle
'+' Plus
'1' Tri Down
'P' Plus (filled)
'2' Tri Up
's' Square
'3' Tri Left
'H' Hexagon
'h' Hexagon
Line Style
• We can use the keyword argument “linestyle”, or shorter “ls”.
• linestyles available:
• solid (default)
• dotted
• dashed
• dashdot
Color
• We can use the keyword argument “color”, or shorter “c”.
• colors available:
• r (red)
• g (green)
• b (blue)
• c (cyan)
• m (magenta)
• we can also use hexadecimal color values: #RRGGBB
Line Width
• We can use the keyword argument ‘linewidth’ or the shorter ‘lw’.
plt.plot(y_vals_1)
plt.plot(y_vals_2)
plt.show()
Putting Labels to the Plot
• We can use ‘xlabel()’ and ‘ylabel()’ to create labels for the x- and y-axes.
import numpy as np
import matplotlib.pyplot as plt
plt.plot(x, y)
plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")
plt.show()
Putting the Title
• We can use the ‘title()’ to create a title for the plot.
import numpy as np
import matplotlib.pyplot as plt
plt.plot(x, y)
plt.show()
Figure Consisting of Multiple Plots
• With the ‘subplot()’, we can organize multiple plots to a figure.
# plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(2, 1, 1)
plt.plot(x,y)
# plot 2:
x = np.array([0, 1, 2, 3])
y = np.array([10, 20, 30, 40])
plt.subplot(2, 1, 2)
plt.plot(x,y)
plt.show()
Plotting Points
• We can use ‘scatter()’ to plot points.
– It needs two arrays of the same length, one for the x values, and the other for y values.
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
plt.scatter(x, y)
plt.show()
Plotting Multiple Sets of Points
# first set:
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
plt.scatter(x, y)
# second set:
x = np.array([2,2,8,1,15,8,12,9,7,3,11,4])
y = np.array([100,105,84,105,90,99,90,95,94,100,79,112])
plt.scatter(x, y)
plt.show()
Setting Point Colors
• You can set the color for each point set with the ‘color’ or the ‘c’ argument
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
plt.scatter(x, y, color = 'hotpink')
x = np.array([2,2,8,1,15,8,12,9,7,3,11,4])
y = np.array([100,105,84,105,90,99,90,95,94,100,79,112])
plt.scatter(x, y, color = '#88c999')
plt.show()
Coloring Each Point
• We can control the color of each point by giving an array of colors as
the value for the ‘c’ argument.
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
c_arr =
np.array(["red","green","blue","yellow","pink","black","o
range","purple","beige","brown","gray","cyan","magenta"])
plt.scatter(x, y, c=c_arr)
plt.show()
Controlling the Point Size
• We can control the size of the points with the ‘s’ argument.
x = np.array([5,7,8,7,2,17,2,9,4, 6])
y = np.array([99,86,87,88,111,86,103,87,94,78])
sizes = np.array([20,50,100,200,500,1000,60,90,10,300])
plt.scatter(x, y, s=sizes)
plt.show()
Drawing Bar Graphs
• We can use ‘bar()’ to draw bar graphs
plt.bar(x,y)
plt.show()
Drawing Bar Graphs (Cont.)
• ‘barh()’ draws a horizontal bar graph.
plt.barh(x, y)
plt.show()
Other drawings
Source code
import math
import numpy as np
import matplotlib.pyplot as plt
nSamples = 64
x = np.linspace(-math.pi, math.pi, num=nSamples)
y1 = np.sin(x)
y2 = np.cos(x)
fig = plt.figure()
fig.canvas.set_window_title('My Figure')
axis = fig.add_subplot(1, 1, 1)
#axis = fig.add_subplot(111)
axis.set_ylim(-2, 2)
axis.grid(True)
plt.title('Plot')
plt.xlabel('x')
plt.ylabel('y')
plt.show()
Other drawings
Source code import math
import numpy as np
import matplotlib.pyplot as plt
nSamples = 64
x = np.linspace(-math.pi, math.pi, num=nSamples)
y1 = np.sin(x); y2 = np.cos(x); y3 = np.tan(x); y4 = x
fig = plt.figure()
fig.canvas.set_window_title('My Figure')
axis1 = fig.add_subplot(2, 2, 1)
axis1.set_ylim(-1, 1)
plt.title('Plot1', loc='left')
plt.ylabel('y')
plt.plot(x, y1, linestyle='-', color='b', label='sin(x)')
axis2 = fig.add_subplot(2, 2, 2)
axis2.set_xlim(-3, 3)
axis2.set_ylim(-3, 3)
plt.title('Plot2', loc='right')
plt.plot(x, y2, ls=':', c='r', label='cos(x)')
axis3 = fig.add_subplot(2, 2, 3)
plt.xlabel('x')
plt.plot(x, y3, ls='--', c='g', label='tan(x)')
plt.legend(loc='upper center')
axis4 = fig.add_subplot(2, 2, 4)
axis4.set_xticks([-2, -1, 0, 1, 2])
axis4.set_yticks([-2, -1, 0, 1, 2])
plt.plot(x, y4,ls='-.', c='m', label='x')
plt.legend(loc='lower right')
plt.xticks()
plt.show()
Practice
2D plotting (5 minutes)
Source code
import numpy as np
import matplotlib.pyplot as plt
nSamples = 50
x = np.linspace(-1, 1, num=nSamples)
y1 = np.log(x)
y2 = np.exp(x)
y3 = np.abs(x)
y4 = np.sqrt(x)
fig = plt.figure()
fig.canvas.set_window_title('My Figure')
axis1 = fig.add_subplot(1, 2, 1)
plt.title('Plot1')
plt.xlabel('x')
plt.ylabel('y')
plt.plot(x, y1, '.', x, y2, 's')
axis2 = fig.add_subplot(1, 2, 2)
plt.title('Plot2')
plt.xlabel('x')
plt.ylabel('y')
plt.plot(x, y3, 'x', x, y4, '+')
plt.show()
Lecture review (3D plotting)
3D Plotting
• Drawing a surface which represents a two-dimensional function.
z f ( x, y )
Introduction to mplot3d
import math
import numpy
import matplotlib.pyplot as plt
fig = plt.figure()
axis = fig.add_subplot(111, projection='3d')
def func(x,y):
return (1- x/2 + x**5 + y**3)*numpy.exp(-x**2-y**2)
, cmap = 'jet'
Plotting the Surface as an Image
import math
import numpy
import matplotlib.pyplot as plt
fig = plt.figure()
axis = fig.add_subplot(111)
def func(x,y):
return (1- x/2 + x**5 + y**3) \
* numpy.exp(-x**2-y**2)
plt.imshow(Z
, interpolation='nearest'
, origin='lower'
, extent=(-3,3,-3,3)
, cmap = 'jet')
plt.colorbar()
plt.show()
Practice #01
• Plot two-dimensional Gaussian functions.
– http://en.wikipedia.org/wiki/Gaussian_function
x2 2
y
2
2
x 2 y
2
f ( x, y ) Ae
Practice #01
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
axis1 = fig.add_subplot(221)
Z = func(1, 1, 1, X, Y)
plt.title('A=1, sigmaX=1, sigmaY=1', {'fontsize': 8, 'fontweight': 'bold'}, pad=0)
plt.imshow(Z, interpolation='nearest', extent=(-2,2,-2,2), cmap = 'jet')
axis2 = fig.add_subplot(222)
Z = func(1, 2, 2, X, Y)
plt.title('A=1, sigmaX=2, sigmaY=2', {'fontsize': 8, 'fontweight': 'bold'}, pad=0)
plt.imshow(Z, interpolation='nearest', extent=(-2,2,-2,2), cmap = 'jet')
axis3 = fig.add_subplot(223)
Z = func(1, 2, 1, X, Y)
plt.title('A=1, sigmaX=2, sigmaY=1', {'fontsize': 8, 'fontweight': 'bold'}, pad=0)
plt.imshow(Z, interpolation='nearest', extent=(-2,2,-2,2), cmap = 'jet')
axis4 = fig.add_subplot(224)
Z = func(1, 1, 2, X, Y)
plt.title('A=1, sigmaX=1, sigmaY=2', {'fontsize': 8, 'fontweight': 'bold'}, pad=0)
plt.imshow(Z, interpolation='nearest', extent=(-2,2,-2,2), cmap = 'jet')
plt.colorbar()
plt.show()
https://www.pygame.org/docs/ref/mixer.html
https://www.pygame.org/docs/ref/music.html
Pygame (music)
How to play music?
• Step1: Put a music file in the folder where the source code file exists.
Music file
filename
# music screen.fill('white')
pygame.mixer.init()
pygame.mixer.music.load("ukulele.mp3") # Update the screen
pygame.mixer.music.set_volume(0.5) pygame.display.flip()
pygame.mixer.music.play()
pygame.quit()
pygame.mixer.music.set_volume(volume)
0.0 ≤ volume ≤ 1.0
https://www.pygame.org/docs/ref/mixer.html
https://www.pygame.org/docs/ref/music.html
Pygame (mixer)
Playing music in different channels
Mixer (10 minutes)
import pygame # Run until the user asks to quit
running = True
# initialize while running:
pygame.init() # Main Event Loop
screen_width, screen_height = 320, 320 for event in pygame.event.get():
screen = pygame.display.set_mode((screen_width, screen_height)) if event.type == pygame.QUIT:
pygame.display.set_caption("Playing a music") running = False
# music screen.fill('white')
pygame.mixer.init()
# Update the screen
channel0 = pygame.mixer.Channel(0) pygame.display.flip()
channel0.set_volume(0.5)
sound0 = pygame.mixer.Sound("ukulele.mp3") pygame.quit()
channel1 = pygame.mixer.Channel(1)
channel1.set_volume(0.2)
sound1 = pygame.mixer.Sound("dreams.mp3")
channel0.play(sound0)
channel1.play(sound1)
Channel method:
- play, stop, pause, unpause, fadeout
- set_volume, get_volume, get_busy, get_sound
- …
Today’s mission
• (1) Shoot the ball on the player as (2) playing music.
– Define Circle and Rectangle class.
• (optional) Define Shape class and let the classes above inherit from Shape.
– Draw a guideline between the ball and mouse cursor.
– Shoot the ball along the guideline with LMB pressed.
– Reposition the ball when it is out of the boundary.
– Play any music.
– (optional) Modularization
• Shape.py
• Circle.py
• Rectangle.py
• etc.
• Import the modules above in main source code file.
Today’s mission (an example of class definition)
Shape Circle
x Instance
radius
y variable
Instance Instance
vx draw
variable method
vy
color
Rectangle
[Abstract]
draw Instance Width
Instance move variable Height
method
setPosition Instance
draw
method
setVelocity
Today’s mission (calculation the velocity)
1. Calculate the direction to shoot
Mouse
𝐝 = 𝑑𝑥 , 𝑑𝑦 = (𝑥𝑚 − 𝑥𝑏 , 𝑦𝑚 − 𝑦𝑏 )
(𝑥𝑚 , 𝑦𝑚 )
𝐝 𝑑𝑥 𝑑𝑦 Ball
𝑢𝑛𝑖𝑡 𝑣𝑒𝑐𝑡𝑜𝑟 𝐝ሚ = = ,
𝑚 𝑚 𝑚
(𝑥𝑏 , 𝑦𝑏 )
3. Calculate [speed x unit vector].
𝑆𝑝𝑒𝑒𝑑: 𝑠
𝑠 𝑠
𝐯 = s𝐝ሚ = 𝑑 , 𝑑
𝑚 𝑥 𝑚 𝑦