Skip to content

Commit 389e478

Browse files
committed
adding tests
1 parent ff72453 commit 389e478

File tree

6 files changed

+438
-0
lines changed

6 files changed

+438
-0
lines changed

tests/test_blitting.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import matplotlib
2+
import matplotlib.pyplot as plt
3+
4+
matplotlib.use('pygame')
5+
import numpy as np
6+
7+
8+
def test_blitting():
9+
10+
x = np.linspace(0, 2 * np.pi, 100)
11+
12+
fig, ax = plt.subplots()
13+
14+
# animated=True tells matplotlib to only draw the artist when we
15+
# explicitly request it
16+
(ln,) = ax.plot(x, np.sin(x), animated=True)
17+
18+
# make sure the window is raised, but the script keeps going
19+
plt.show(block=False)
20+
21+
# stop to admire our empty window axes and ensure it is rendered at
22+
# least once.
23+
#
24+
# We need to fully draw the figure at its final size on the screen
25+
# before we continue on so that :
26+
# a) we have the correctly sized and drawn background to grab
27+
# b) we have a cached renderer so that ``ax.draw_artist`` works
28+
# so we spin the event loop to let the backend process any pending operations
29+
plt.pause(0.1)
30+
31+
# get copy of entire figure (everything inside fig.bbox) sans animated artist
32+
bg = fig.canvas.copy_from_bbox(fig.bbox)
33+
34+
# draw the animated artist, this uses a cached renderer
35+
ax.draw_artist(ln)
36+
# show the result to the screen, this pushes the updated RGBA buffer from the
37+
# renderer to the GUI framework so you can see it
38+
39+
for j in range(2):
40+
# reset the background back in the canvas state, screen unchanged
41+
fig.canvas.restore_region(bg)
42+
# update the artist, neither the canvas state nor the screen have changed
43+
ln.set_ydata(np.sin(x + (j / 100) * np.pi))
44+
# re-render the artist, updating the canvas state, but not the screen
45+
ax.draw_artist(ln)
46+
# copy the image to the GUI state, but screen might not be changed yet
47+
fig.canvas.blit(fig.bbox)
48+
# flush any pending GUI events, re-painting the screen if needed
49+
fig.canvas.flush_events()
50+

tests/test_blitting_class.py

Lines changed: 112 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
import matplotlib.pyplot as plt
2+
import numpy as np
3+
import matplotlib
4+
matplotlib.use('pygame')
5+
6+
class BlitManager:
7+
def __init__(self, canvas, animated_artists=()):
8+
"""
9+
Parameters
10+
----------
11+
canvas : FigureCanvasAgg
12+
The canvas to work with, this only works for sub-classes of the Agg
13+
canvas which have the `~FigureCanvasAgg.copy_from_bbox` and
14+
`~FigureCanvasAgg.restore_region` methods.
15+
16+
animated_artists : Iterable[Artist]
17+
List of the artists to manage
18+
"""
19+
self.canvas = canvas
20+
self._bg = None
21+
self._artists = []
22+
23+
for a in animated_artists:
24+
self.add_artist(a)
25+
# grab the background on every draw
26+
self.cid = canvas.mpl_connect("draw_event", self.on_draw)
27+
28+
def on_draw(self, event):
29+
"""Callback to register with 'draw_event'."""
30+
cv = self.canvas
31+
if event is not None:
32+
if event.canvas != cv:
33+
raise RuntimeError
34+
self._bg = cv.copy_from_bbox(cv.figure.bbox)
35+
self._draw_animated()
36+
37+
def add_artist(self, art):
38+
"""
39+
Add an artist to be managed.
40+
41+
Parameters
42+
----------
43+
art : Artist
44+
45+
The artist to be added. Will be set to 'animated' (just
46+
to be safe). *art* must be in the figure associated with
47+
the canvas this class is managing.
48+
49+
"""
50+
if art.figure != self.canvas.figure:
51+
raise RuntimeError
52+
art.set_animated(True)
53+
self._artists.append(art)
54+
55+
def _draw_animated(self):
56+
"""Draw all of the animated artists."""
57+
fig = self.canvas.figure
58+
for a in self._artists:
59+
fig.draw_artist(a)
60+
61+
def update(self):
62+
"""Update the screen with animated artists."""
63+
cv = self.canvas
64+
fig = cv.figure
65+
# paranoia in case we missed the draw event,
66+
if self._bg is None:
67+
self.on_draw(None)
68+
else:
69+
# restore the background
70+
cv.restore_region(self._bg)
71+
# draw all of the animated artists
72+
self._draw_animated()
73+
# update the GUI state
74+
cv.blit(fig.bbox)
75+
# let the GUI event loop process anything it has to do
76+
cv.flush_events()
77+
78+
79+
def test_blitting_class():
80+
"""
81+
Test the BlitManager class by creating a simple animated plot.
82+
"""
83+
# create some data
84+
x = np.linspace(0, 2 * np.pi, 100)
85+
# make a new figure
86+
fig, ax = plt.subplots()
87+
# add a line
88+
(ln,) = ax.plot(x, np.sin(x), animated=True)
89+
# add a frame number
90+
fr_number = ax.annotate(
91+
"0",
92+
(0, 1),
93+
xycoords="axes fraction",
94+
xytext=(10, -10),
95+
textcoords="offset points",
96+
ha="left",
97+
va="top",
98+
animated=True,
99+
)
100+
bm = BlitManager(fig.canvas, [ln, fr_number])
101+
# make sure our window is on the screen and drawn
102+
plt.show(block=False)
103+
plt.pause(0.1)
104+
105+
for j in range(3):
106+
# update the artists
107+
ln.set_ydata(np.sin(x + (j / 100) * np.pi))
108+
fr_number.set_text("frame: {j}".format(j=j))
109+
# tell the blitting manager to do its thing
110+
bm.update()
111+
# plt.pause(1)
112+
plt.close(fig) # Close the figure after testing

tests/test_gui_window.py

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
"""Simple script to test from https://pygame-gui.readthedocs.io/en/latest/quick_start.html"""
2+
3+
4+
import pygame
5+
import pygame_gui
6+
7+
import matplotlib.pyplot as plt
8+
9+
from pygame_matplotlib.gui_window import UIPlotWindow
10+
11+
12+
def test_gui_window():
13+
14+
pygame.init()
15+
16+
pygame.display.set_caption('Test')
17+
window_surface = pygame.display.set_mode((800, 600))
18+
19+
background = pygame.Surface((800, 600))
20+
background.fill(pygame.Color('#000000'))
21+
22+
manager = pygame_gui.UIManager((800, 600))
23+
24+
fig, axes = plt.subplots(1, 1,)
25+
axes.plot([1,2], [1,2], color='green', label='test')
26+
fig.canvas.draw()
27+
28+
29+
fig2, axes2 = plt.subplots(1, 1,)
30+
axes2.plot([1,2], [1,2], color='blue', label='test')
31+
fig2.canvas.draw()
32+
33+
34+
plot_window = UIPlotWindow(
35+
rect=pygame.Rect((350, 275), (300, 200)),
36+
manager=manager,
37+
figuresurface=fig,
38+
resizable=True
39+
)
40+
41+
42+
43+
44+
plot_window2 = UIPlotWindow(
45+
rect=pygame.Rect((350, 275), (200, 200)),
46+
manager=manager,
47+
figuresurface=fig2,
48+
resizable=False
49+
)
50+
51+
52+
clock = pygame.time.Clock()
53+
54+
is_running = True
55+
i = 0
56+
57+
while is_running:
58+
if i > 2:
59+
is_running = False
60+
time_delta = clock.tick(60)/1000.0
61+
for event in pygame.event.get():
62+
if event.type == pygame.QUIT:
63+
is_running = False
64+
65+
66+
manager.process_events(event)
67+
68+
manager.update(time_delta)
69+
70+
# Blitts and draw
71+
window_surface.blit(background, (0, 0))
72+
manager.draw_ui(window_surface)
73+
74+
75+
# print(plot_window2.get_container().get_size())
76+
77+
pygame.display.update()
78+
i += 1

tests/test_save_to_file.py

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import sys
2+
import os
3+
from numpy.ma.core import size
4+
import pygame
5+
6+
import matplotlib
7+
matplotlib.use('pygame')
8+
#matplotlib.use('Qt4Agg')
9+
10+
import matplotlib.pyplot as plt
11+
import matplotlib.figure as fg
12+
13+
import matplotlib.pyplot as plt
14+
15+
16+
17+
def test_save_jpg():
18+
plt.figure()
19+
20+
21+
plt.plot([1,2], [1,2], color='green')
22+
plt.text(1.5, 1.5, '2', size=50)
23+
plt.xlabel('swag')
24+
25+
plt.savefig('images' + os.sep + 'test.jpg')
26+
27+
28+
def test_save_bmp():
29+
plt.figure()
30+
plt.plot([1,2], [1,2], color='green')
31+
plt.text(1.5, 1.5, '2', size=50)
32+
plt.xlabel('swag')
33+
plt.savefig('images' + os.sep + 'test.bmp')

0 commit comments

Comments
 (0)