forked from cytoflow/cytoflow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
matplotlib_backend_remote.py
361 lines (280 loc) · 12.6 KB
/
matplotlib_backend_remote.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
#!/usr/bin/env python3.8
# coding: latin-1
# (c) Massachusetts Institute of Technology 2015-2018
# (c) Brian Teague 2018-2022
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
cytoflowgui.matplotlib_backend_remote
-------------------------------------
A matplotlib backend that renders across a process boundary. This file has
the "remote" canvas -- the Agg renderer into which pyplot.plot() renders.
By default, matplotlib only works in one thread. For a GUI application, this
is a problem because when matplotlib is working (ie, scaling a bunch of data
points) the GUI freezes.
This module implements a matplotlib backend where the plotting done in one
process (ie via pyplot, etc) shows up in a canvas running in another process
(the GUI). The canvas is the interface across the process boundary: a "local"
canvas, which is a GUI widget (in this case a QWidget) and a "remote" canvas
(running in the process where pyplot.plot() etc. are used.) The remote canvas
is a subclass of the Agg renderer; when draw() is called, the remote canvas
pulls the current buffer out of the renderer and pushes it through a pipe
to the local canvas, which draws it on the screen. blit() is implemented
too.
This takes care of one direction of data flow, and would be enough if we were
just plotting. However, we want to use matplotlib widgets as well, which
means there's data flowing from the local canvas to the remote canvas too.
The local canvas is a subclass of FigureCanvasQTAgg, which is itself a
sublcass of QWidget. The local canvas overrides several of the event handlers,
passing the event information to the remote canvas which in turn runs the
matplotlib event handlers.
"""
import threading, logging, sys, traceback
import matplotlib.pyplot
from matplotlib.figure import Figure
#from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg
from matplotlib.backends.backend_agg import FigureCanvasAgg
import numpy as np
# needed for pylab_setup
backend_version = "0.0.3"
from matplotlib.backend_bases import FigureManagerBase
logger = logging.getLogger(__name__)
class Msg(object):
"""
Messages sent between the local and remote canvases.
There is an identical class in `matplotlib_backend_local` because we
don't want these two modules requiring one another
"""
DRAW = "DRAW"
BLIT = "BLIT"
WORKING = "WORKING"
RESIZE_EVENT = "RESIZE"
MOUSE_PRESS_EVENT = "MOUSE_PRESS"
MOUSE_MOVE_EVENT = "MOUSE_MOVE"
MOUSE_RELEASE_EVENT = "MOUSE_RELEASE"
MOUSE_DOUBLE_CLICK_EVENT = "MOUSE_DOUBLE_CLICK"
DPI = "DPI"
PRINT = "PRINT"
def log_exception():
"""Catch and log exceptions (with their tracebacks"""
(exc_type, exc_value, tb) = sys.exc_info()
err_string = traceback.format_exception_only(exc_type, exc_value)[0]
err_loc = traceback.format_tb(tb)[-1]
err_ctx = threading.current_thread().name
logger.debug("Exception in {0}:\n{1}"
.format(err_ctx, "".join( traceback.format_exception(exc_type, exc_value, tb) )))
logger.error("Error: {0}\nLocation: {1}Thread: {2}" \
.format(err_string, err_loc, err_ctx) )
class FigureCanvasAggRemote(FigureCanvasAgg):
"""
The canvas the figure renders into in the remote process (ie, the one
where someone is calling pyplot.plot()
"""
def __init__(self, parent_conn, process_events, plot_lock, figure):
FigureCanvasAgg.__init__(self, figure)
self.parent_conn = parent_conn
self.process_events = process_events
self.plot_lock = plot_lock
self.buffer_lock = threading.Lock()
self.buffer = None
self.buffer_width = None
self.buffer_height = None
self.blit_lock = threading.Lock()
self.blit_buffer = None
self.blit_width = None
self.blit_height = None
self.blit_top = None
self.blit_left = None
self.working = False
self.update_remote = threading.Event()
t = threading.Thread(target = self.listen_for_local,
name = "canvas listen",
args = ())
t.daemon = True
t.start()
t = threading.Thread(target = self.send_to_local,
name = "canvas send",
args=())
t.daemon = True
t.start()
def listen_for_local(self):
"""
The main method for the thread that listens for messages from
the local canvas
"""
while self.parent_conn.poll(None):
try:
(msg, payload) = self.parent_conn.recv()
except EOFError:
return
if msg != Msg.MOUSE_MOVE_EVENT:
logger.debug("FigureCanvasAggRemote.listen_for_local :: {}"
.format(msg, payload))
try:
if msg == Msg.DPI:
dpi = payload
matplotlib.rcParams['figure.dpi'] = dpi
matplotlib.pyplot.clf()
elif msg == Msg.RESIZE_EVENT:
with self.plot_lock:
(winch, hinch) = payload
self.figure.set_size_inches(winch, hinch)
FigureCanvasAgg.resize_event(self)
self.draw()
elif msg == Msg.MOUSE_PRESS_EVENT:
(x, y, button) = payload
if self.process_events.is_set():
with self.plot_lock:
FigureCanvasAgg.button_press_event(self, x, y, button)
elif msg == Msg.MOUSE_DOUBLE_CLICK_EVENT:
(x, y, button) = payload
if self.process_events.is_set():
with self.plot_lock:
FigureCanvasAgg.button_press_event(self, x, y, button, dblclick = True)
elif msg == Msg.MOUSE_RELEASE_EVENT:
(x, y, button) = payload
if self.process_events.is_set():
with self.plot_lock:
FigureCanvasAgg.button_release_event(self, x, y, button)
elif msg == Msg.MOUSE_MOVE_EVENT:
(x, y) = payload
if self.process_events.is_set():
with self.plot_lock:
FigureCanvasAgg.motion_notify_event(self, x, y)
elif msg == Msg.PRINT:
(args, kwargs) = payload
if self.process_events.is_set():
with self.plot_lock:
old_size = self.figure.get_size_inches()
width = kwargs.pop('width')
height = kwargs.pop('height')
self.figure.set_size_inches(width, height)
FigureCanvasAgg.print_figure(self, *args, **kwargs)
self.figure.set_size_inches(old_size[0], old_size[1])
else:
raise RuntimeError("FigureCanvasAggRemote received bad message {}".format(msg))
except Exception:
log_exception()
def send_to_local(self):
"""
The main method for the thread that sends messages to the local canvas
"""
while self.update_remote.wait():
logger.debug("FigureCanvasAggRemote.send_to_local")
self.update_remote.clear()
if self.blit_buffer is not None:
with self.blit_lock:
msg = (Msg.BLIT, (self.blit_buffer,
self.blit_width,
self.blit_height,
self.blit_top,
self.blit_left))
self.parent_conn.send(msg)
self.blit_buffer = None
elif self.buffer is not None:
with self.buffer_lock:
msg = (Msg.DRAW, (self.buffer,
self.buffer_width,
self.buffer_height))
self.parent_conn.send(msg)
self.buffer = None
msg = (Msg.WORKING, self.working)
self.parent_conn.send(msg)
def draw(self, *args, **kwargs): # @UnusedVariable
"""
When the canvas is instructed to draw itself, copy the Agg buffer out
to a numpy array and send it to the local process.
"""
logger.debug("FigureCanvasAggRemote.draw()")
FigureCanvasAgg.draw(self)
with self.buffer_lock:
self.buffer = np.array(self.renderer.buffer_rgba())
self.buffer_width = self.renderer.width
self.buffer_height = self.renderer.height
self.update_remote.set()
def blit(self, bbox=None):
"""
When instructed to blit a bounding box, copy the region in the bounding
box to a numpy array and send it to the local canvas.
"""
# If bbox is None, blit the entire canvas. Otherwise
# blit only the area defined by the bbox.
logger.debug("FigureCanvasAggRemote.blit()")
if bbox is None and self.figure:
logger.info("bbox was none")
return
with self.blit_lock:
l, b, r, t = bbox.extents
w = int(r) - int(l)
h = int(t) - int(b)
t = int(b) + h
l = int(l)
reg = self.copy_from_bbox(bbox)
self.blit_buffer = reg.to_string_argb()
self.blit_width = w
self.blit_height = h
self.blit_top = t
self.blit_left = l
self.update_remote.set()
def set_working(self, working):
self.working = working
self.update_remote.set()
remote_canvas = None
singleton_lock = threading.Lock()
def new_figure_manager(num, *args, **kwargs):
"""
Create a new figure manager instance. This maintains the remote canvas as
a singleton -- else, each new canvas would need a copy of the pipes, locks,
etc.
"""
global remote_canvas
global singleton_lock
logger.debug("mpl_multiprocess_backend.new_figure_manager()")
# get the pipe connection
parent_conn = kwargs.pop('parent_conn')
# and the threading.Event for turning events on and off
process_events = kwargs.pop('process_events')
# and the plot lock
plot_lock = kwargs.pop('plot_lock')
# make a new figure
FigureClass = kwargs.pop('FigureClass', Figure)
new_fig = FigureClass(*args, **kwargs)
with singleton_lock:
# the canvas is a singleton.
if not remote_canvas:
remote_canvas = FigureCanvasAggRemote(parent_conn, process_events, plot_lock, new_fig)
else:
old_fig = remote_canvas.figure
new_fig.set_size_inches(old_fig.get_figwidth(),
old_fig.get_figheight())
remote_canvas.figure = new_fig
new_fig.set_canvas(remote_canvas)
# close the current figure (to keep pyplot happy)
matplotlib.pyplot.close()
return FigureManagerBase(remote_canvas, num)
def draw_if_interactive():
logger.debug("mpl_multiprocess_backend.draw_if_interactive")
remote_canvas.draw()
def show():
logger.debug("mpl_multiprocess_backend.show")
remote_canvas.draw()
# make sure pyplot uses the remote canvas
FigureCanvas = FigureCanvasAggRemote
# we don't need a figure manager with any more than default functionality
FigureManager = FigureManagerBase
# monkey-patch seaborn
def tight_layout(self, *args, **kwargs):
pass
import seaborn.axisgrid # @UnusedImport
seaborn.axisgrid.Grid.tight_layout = tight_layout