Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 1d74d73

Browse files
committed
start zmq worker implementation
1 parent 72a3f02 commit 1d74d73

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

fastplotlib/utils/_zmq.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
from functools import wraps
2+
3+
import numpy as np
4+
import zmq
5+
6+
from .. import Graphic, Figure
7+
8+
9+
class ZmqWorker:
10+
def __init__(self, address: str = "tcp://127.0.0.1", port_start: int = 5555):
11+
self._address = address
12+
self._port_start = port_start
13+
self._port_iterator = 0
14+
15+
self._context = zmq.Context()
16+
# maps (graphic, feature) -> Socket
17+
self._sockets: dict[(str, str), zmq.Socket] = dict()
18+
19+
self._figures: set[Figure] = set()
20+
21+
def _create_socket(self, graphic: Graphic):
22+
for feature in graphic._features:
23+
subscriber = self._context.socket(zmq.SUB)
24+
subscriber.setsocketopt(zmq.SUBSCRIBE, b"")
25+
subscriber.setsocketopt(zmq.CONFLATE, 1)
26+
27+
subscriber.connect(f"{self._address}:{self._port_start + self._port_iterator}")
28+
29+
self._port_iterator += 1
30+
31+
self._sockets[(graphic, feature)] = subscriber
32+
33+
def _add_figure(self, figure: Figure):
34+
if figure in self._figures:
35+
return
36+
figure.add_animations(self._receive)
37+
38+
def _receive(self, figure: Figure):
39+
"""receive new data and update for all graphics in the given Figure"""
40+
41+
for (graphic, feature), subscriber in self._sockets.items():
42+
if graphic._plot_area.get_figure() is not figure:
43+
continue
44+
try:
45+
new_bytes = subscriber.recv(zmq.NOBLOCK)
46+
except zmq.Again:
47+
pass
48+
else:
49+
current_data = getattr(graphic, feature).value
50+
new_data = np.frombuffer(new_bytes, dtype=current_data.dtype).reshape(current_data.shape)
51+
setattr(graphic, feature, new_data)
52+
53+
def dispatch(self, graphics: list[Graphic] = None):
54+
def decorator(compute_func):
55+
@wraps(compute_func)
56+
def dispatch_compute(*args, **kwargs):
57+
# create socket and subscriber for each graphic
58+
for g in graphics:
59+
self._create_socket(g)
60+
self._add_figure(g._plot_area.get_figure())
61+
62+
return dispatch_compute
63+
return decorator

0 commit comments

Comments
 (0)