-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathruntime_display.py
386 lines (296 loc) · 12.6 KB
/
runtime_display.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
#!/usr/bin/python3
#
#mk
#v0.11
#
# backends
import matplotlib
#print
#print("matplotlib version: "+ str(matplotlib.__version__))
print()
import tkinter as tk
import os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.backends.tkagg as tkagg
#import matplotlib.backends.backend_tkagg as tkagg
#### below this works w/ mpl 3.3.4
from matplotlib.backends.backend_agg import FigureCanvasAgg
#from matplotlib.backends_bases import FigureCanvasAgg
#mk see pygame __init__.py to remove pygame message on library load
import pygame
class Dynamic2DFigure():
def __init__(self,
figsize=(8,8),
edgecolor="black",
rect=[0.1, 0.1, 0.8, 0.8], #for trajectory display
*args, **kwargs):
self.graphs = {}
self.texts = {}
self.fig = plt.Figure(figsize=figsize, edgecolor=edgecolor)
self.ax = self.fig.add_axes(rect)
self.fig.tight_layout()
self.marker_text_offset = 0
if kwargs["title"] is not None:
self.fig.suptitle(kwargs["title"])
self.axis_equal = False
self.invert_xaxis = False
def set_invert_x_axis(self):
self.invert_xaxis = True
def set_axis_equal(self):
self.axis_equal = True
def add_graph(self, name, label="", window_size=10, x0=None, y0=None,
linestyle='-', linewidth=1, marker="", color="k",
markertext=None, marker_text_offset=2):
self.marker_text_offset = marker_text_offset
if x0 is None or y0 is None:
x0 = np.zeros(window_size)
y0 = np.zeros(window_size)
new_graph, = self.ax.plot(x0, y0, label=label,
linestyle=linestyle, linewidth=linewidth,
marker=marker, color=color)
if markertext is not None:
new_text = self.ax.text(x0[-1], y0[-1] + marker_text_offset,
markertext)
else:
new_graph, = self.ax.plot(x0, y0, label=label,
linestyle=linestyle, linewidth=linewidth,
marker=marker, color=color)
if markertext is not None:
new_text = self.ax.text(x0[-1], y0[-1] + marker_text_offset,
markertext)
self.graphs[name] = new_graph
if markertext is not None:
self.texts[name + "_TEXT"] = new_text
def roll(self, name, new_x, new_y):
graph = self.graphs[name]
if graph is not None:
x, y = graph.get_data()
x = np.roll(x, -1)
x[-1] = new_x
y = np.roll(y, -1)
y[-1] = new_y
graph.set_data((x, y))
self.rescale()
if name + "_TEXT" in self.texts:
graph_text = self.texts[name + "_TEXT"]
x = new_x
y = new_y + self.marker_text_offset
graph_text.set_position((x, y))
self.rescale()
def update(self, name, new_x_vec, new_y_vec, new_colour='k'):
graph = self.graphs[name]
if graph is not None:
graph.set_data((np.array(new_x_vec), np.array(new_y_vec)))
graph.set_color(new_colour)
self.rescale()
if name + "_TEXT" in self.texts:
graph_text = self.texts[name + "_TEXT"]
x = new_x_vec[-1]
y = new_y_vec[-1] + self.marker_text_offset
graph_text.set_position((x, y))
self.rescale()
def rescale(self):
xmin = float("inf")
xmax = -1*float("inf")
ymin, ymax = self.ax.get_ylim()
for name, graph in self.graphs.items():
xvals, yvals = graph.get_data()
xmin_data = xvals.min()
xmax_data = xvals.max()
ymin_data = yvals.min()
ymax_data = yvals.max()
xmin_padded = xmin_data-0.05*(xmax_data-xmin_data)
xmax_padded = xmax_data+0.05*(xmax_data-xmin_data)
ymin_padded = ymin_data-0.05*(ymax_data-ymin_data)
ymax_padded = ymax_data+0.05*(ymax_data-ymin_data)
xmin = min(xmin_padded, xmin)
xmax = max(xmax_padded, xmax)
ymin = min(ymin_padded, ymin)
ymax = max(ymax_padded, ymax)
self.ax.set_xlim(xmin, xmax)
self.ax.set_ylim(ymin, ymax)
if self.axis_equal:
self.ax.set_aspect('equal')
if self.invert_xaxis:
self.ax.invert_xaxis()
class DynamicFigure():
def __init__(self, figsize=(3,2),edgecolor="black",*args, **kwargs):
#mk can now pass figsize as arg for these mini display
self.graphs = {}
self.fig = plt.Figure(figsize=figsize, edgecolor=edgecolor)
self.ax = self.fig.add_axes([0.2, 0.2, 0.6, 0.6])
self.fig.tight_layout()
if kwargs["title"] is not None:
self.fig.suptitle(kwargs["title"])
def add_graph(self, name, label="", window_size=10, x0=None, y0=None):
if y0 is None:
x0 = np.zeros(window_size)
y0 = np.zeros(window_size)
new_graph, = self.ax.plot(x0, y0, label=label)
elif x0 is None:
new_graph, = self.ax.plot(y0, label=label)
else:
new_graph, = self.ax.plot(x0, y0, label=label)
self.graphs[name] = new_graph
def roll(self, name, new_x, new_y):
graph = self.graphs[name]
if graph is not None:
x, y = graph.get_data()
x = np.roll(x, -1)
x[-1] = new_x
y = np.roll(y, -1)
y[-1] = new_y
graph.set_data((x, y))
self.rescale()
def rescale(self):
xmin = float("inf")
xmax = -1*float("inf")
ymin, ymax = self.ax.get_ylim()
for name, graph in self.graphs.items():
xvals, yvals = graph.get_data()
xmin_data = xvals.min()
xmax_data = xvals.max()
ymin_data = yvals.min()
ymax_data = yvals.max()
xmin_padded = xmin_data-0.05*(xmax_data-xmin_data)
xmax_padded = xmax_data+0.05*(xmax_data-xmin_data)
ymin_padded = ymin_data-0.05*(ymax_data-ymin_data)
ymax_padded = ymax_data+0.05*(ymax_data-ymin_data)
xmin = min(xmin_padded, xmin)
xmax = max(xmax_padded, xmax)
ymin = min(ymin_padded, ymin)
ymax = max(ymax_padded, ymax)
self.ax.set_xlim(xmin, xmax)
self.ax.set_ylim(ymin, ymax)
class DisplayPanel():
def __init__(self, tk_title=None, orientation=None):
self._default_w = 150
self._default_h = 100
self._graph_w = 0
self._graph_h = 0
self._surf_w = 0
self._surf_h = 0
self._figs = []
self._fcas = {}
self._photos = {}
self._text_id = None
self._empty = True
self._tk_root = tk.Tk()
if tk_title is not None:
self._tk_root.title(tk_title)
# transparent possibly in future self._tk_root.attributes('-alpha', ?)
self._canvas = tk.Canvas(self._tk_root, width=self._default_w, height=self._default_h)
self._canvas.config(bg="#6A6A6A") #gray
self._text_id = self._canvas.create_text(
(self._default_w/2, self._default_h/2),
text="No figures added...")
self._canvas.grid(row=0, column=0)
self._display = None
self._game_frame = None
self._pygame_init = False
self._surfs = []
self._surf_coords = {}
self._orientation = orientation
if (self._orientation is None):
self._orientation='vertical'
def plot_figure(self, fig):
if self._empty:
self._empty = False
self._canvas.delete(self._text_id)
# get width, height of figure that is being added
f_w = fig.get_window_extent().width
f_h = fig.get_window_extent().height
f_w, f_h = int(f_w), int(f_h)
#mk not used?
fca = FigureCanvasAgg(fig) # draw out figure
fca.draw()
f_w, f_h = fca.get_renderer().get_canvas_width_height()
f_w, f_h = int(f_w), int(f_h)
# panel (canvas) dynamically extends frame dimensions
# to fit additional new figures
# portrait mode - vertical panel
# add new figure underneath
if (self._orientation == 'vertical'):
self._graph_h += f_h
self._graph_w = max(self._graph_w, f_w)
# landscape mode - horizontal panel
# add new figure to right side
if (self._orientation == 'horizontal'):
self._graph_h = max(self._graph_h, f_h)
self._graph_w += f_w
# adjust panel size
self._canvas.config(width=self._graph_w, height=self._graph_h)
self._canvas.grid(row=0, column=0)
# create photo object to place on canvas
photo = tk.PhotoImage(master=self._canvas, width=f_w, height=f_h)
# place according to panel orientation also!
#VERTICAL
if (self._orientation == 'vertical'):
self._canvas.create_image(f_w/2, self._graph_h-(f_h/2), image=photo) # anchor="nw")
#HORIZONTAL
if (self._orientation == 'horizontal'):
self._canvas.create_image(self._graph_w-(f_w/2),f_h/2, image=photo)
#mk not used?
tkagg.blit(photo, fca.get_renderer()._renderer, colormode=2)
self._tk_root.update()
self._figs.append(fig)
self._fcas[fig] = fca
self._photos[fig] = photo
def plot_new_figure(self):
fig = plt.Figure(figsize=(3, 2), edgecolor="black")
ax = fig.add_axes([0.2, 0.2, 0.6, 0.6])
fig.tight_layout()
self.plot_figure(fig) #figure added & stored in list
return fig, ax
def plot_new_dynamic_figure(self, title="",**kwargs):
#mk takes args now like 2d version & pass to create call
dyfig = DynamicFigure(title=title,**kwargs)
fig = dyfig.fig
self.plot_figure(fig) #store fig locally in object also
return dyfig
def plot_new_dynamic_2d_figure(self, title="", **kwargs):
dy2dfig = Dynamic2DFigure(title=title, **kwargs)
fig = dy2dfig.fig
self.plot_figure(fig) #store fig locally in object also
return dy2dfig
def refresh_figure(self, fig):
self._fcas[fig].draw()
self._fcas[fig].flush_events()
fig.canvas.draw()
fig.canvas.flush_events()
tkagg.blit(
self._photos[fig],
self._fcas[fig].get_renderer()._renderer,
colormode=2)
self._tk_root.update()
def init_pygame(self):
self._game_frame = tk.Frame(
self._tk_root,
width=self._surf_w,
height=self._surf_h)
self._game_frame.grid(row=0, column=1)
os.environ['SDL_WINDOWID'] = str(self._game_frame.winfo_id())
self._game_frame.update()
pygame.display.init()
def plot_surface(self, surf):
s_w, s_h = surf.get_size()
self._surf_w += s_w
self._surf_h = max(self._surf_h, s_h)
if not self._pygame_init:
self._pygame_init = True
self.init_pygame()
else:
self._game_frame.config(width=self._surf_w, height=self._surf_h)
self._game_frame.grid(row=0, column=1)
self._display = pygame.display.set_mode((self._surf_w, self._surf_h))
self._surfs.append(surf)
self._surf_coords[surf] = (self._surf_w-s_w, 0)
self._display.blits(list(self._surf_coords.items()))
def refresh(self):
for fig in list(self._figs):
self.refresh_figure(fig)
self._tk_root.update()
if not self._display is None:
self._display.blits(list(self._surf_coords.items()))
pygame.display.flip()