cogmatplot 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
cogmatplot/mode.py ADDED
@@ -0,0 +1,77 @@
1
+ """Session display mode.
2
+
3
+ ``qt`` opens interactive windows on a monitor, outside the notebook.
4
+ ``inline`` draws static figures into the interactive viewer.
5
+ Call :func:`use` before creating figures.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import sys
11
+
12
+ _mode = None
13
+
14
+
15
+ def _in_ipython() -> bool:
16
+ try:
17
+ from IPython import get_ipython
18
+ except Exception:
19
+ return False
20
+ return get_ipython() is not None
21
+
22
+
23
+ def use(mode: str = "auto") -> str:
24
+ """Select ``'qt'``, ``'inline'``, or ``'auto'``.
25
+
26
+ ``auto`` is inline inside IPython and Qt otherwise.
27
+ Qt figures are interactive and can be placed on another monitor.
28
+ Inline figures are static: images, axes, 2D plots, 3D lines, and a
29
+ rendered 3D view in the notebook output.
30
+ """
31
+ global _mode
32
+ mode = str(mode).lower()
33
+ if mode == "auto":
34
+ mode = "inline" if _in_ipython() else "qt"
35
+ if mode not in ("inline", "qt"):
36
+ raise ValueError("mode must be 'qt', 'inline', or 'auto'")
37
+
38
+ import matplotlib
39
+
40
+ current = matplotlib.get_backend().lower()
41
+ loaded = "matplotlib.pyplot" in sys.modules
42
+ if mode == "inline":
43
+ if "inline" not in current and current != "agg":
44
+ target = "module://matplotlib_inline.backend_inline" if _in_ipython() else "Agg"
45
+ try:
46
+ matplotlib.use(target, force=loaded)
47
+ except Exception:
48
+ if not loaded:
49
+ matplotlib.use("Agg")
50
+ elif "qt" not in current:
51
+ try:
52
+ matplotlib.use("QtAgg", force=loaded)
53
+ except Exception:
54
+ if not loaded:
55
+ matplotlib.use("QtAgg")
56
+
57
+ _mode = mode
58
+ if loaded or mode == "qt":
59
+ import matplotlib.pyplot as plt
60
+
61
+ if mode == "qt":
62
+ plt.ion()
63
+ else:
64
+ plt.ioff()
65
+ return mode
66
+
67
+
68
+ def current_mode() -> str:
69
+ """Active mode. An explicit :func:`use` wins; otherwise follow the backend."""
70
+ if _mode:
71
+ return _mode
72
+ import matplotlib
73
+
74
+ backend = matplotlib.get_backend().lower()
75
+ if any(name in backend for name in ("qt", "wx", "tk", "gtk", "macosx")):
76
+ return "qt"
77
+ return "inline"
cogmatplot/place.py ADDED
@@ -0,0 +1,65 @@
1
+ """Put Qt and OpenCV windows on the same screen rectangle.
2
+
3
+ Matplotlib places a window with ``move``, which anchors the visible frame,
4
+ title bar included. ``setGeometry`` anchors the client area under the title
5
+ bar, so a PyVista window sits too high. OpenCV's Win32 ``moveWindow`` anchors
6
+ the outer rectangle, which includes a thin invisible border, so that window
7
+ sits a few pixels to the right. These helpers land all three on the frame
8
+ matplotlib uses.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import sys
14
+
15
+
16
+ def place_qt_window(window, x, y, w, h) -> None:
17
+ """Match matplotlib: frame origin at ``(x, y)``, client size ``(w, h)``."""
18
+ if window is None or not hasattr(window, "move"):
19
+ return
20
+ window.move(int(x), int(y))
21
+ if hasattr(window, "resize"):
22
+ window.resize(int(w), int(h))
23
+
24
+
25
+ def place_cv_window(name: str, x, y, w, h) -> None:
26
+ """Move an OpenCV window so its visible frame starts at ``(x, y)``."""
27
+ import cv2
28
+
29
+ x, y, w, h = int(x), int(y), int(w), int(h)
30
+ cv2.resizeWindow(name, max(w, 1), max(h, 1))
31
+ cv2.moveWindow(name, x, y)
32
+ cv2.waitKey(1)
33
+ origin = _cv_visible_origin(name)
34
+ if origin is None:
35
+ return
36
+ dx = origin[0] - x
37
+ dy = origin[1] - y
38
+ if dx or dy:
39
+ cv2.moveWindow(name, x - dx, y - dy)
40
+
41
+
42
+ def _cv_visible_origin(name: str):
43
+ if sys.platform != "win32":
44
+ return None
45
+ import ctypes
46
+ from ctypes import wintypes
47
+
48
+ user32 = ctypes.windll.user32
49
+ user32.FindWindowW.restype = ctypes.c_void_p
50
+ user32.FindWindowW.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p]
51
+ hwnd = user32.FindWindowW(None, name)
52
+ if not hwnd:
53
+ return None
54
+ rect = wintypes.RECT()
55
+ try:
56
+ dwmapi = ctypes.windll.dwmapi
57
+ # DWMWA_EXTENDED_FRAME_BOUNDS: the visible frame, without the invisible border.
58
+ hr = dwmapi.DwmGetWindowAttribute(ctypes.c_void_p(hwnd), 9, ctypes.byref(rect), ctypes.sizeof(rect))
59
+ if hr == 0:
60
+ return int(rect.left), int(rect.top)
61
+ except Exception:
62
+ pass
63
+ if user32.GetWindowRect(ctypes.c_void_p(hwnd), ctypes.byref(rect)):
64
+ return int(rect.left), int(rect.top)
65
+ return None
cogmatplot/ply.py ADDED
@@ -0,0 +1,325 @@
1
+ """Binary PLY loader and a small rectangular-prism sample.
2
+
3
+ Binary little-endian files are read with ``numpy.frombuffer`` after the
4
+ header. That is the fast path: the vertex block is one array, not a Python
5
+ loop. Vertex colors may be ``red/green/blue`` or ``diffuse_red/green/blue``.
6
+ Faces are triangle lists (``property list uchar int vertex_indices``).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass
12
+ from pathlib import Path
13
+ from typing import Optional, Union
14
+
15
+ import numpy as np
16
+
17
+ _SCALAR = {
18
+ "char": "i1",
19
+ "int8": "i1",
20
+ "uchar": "u1",
21
+ "uint8": "u1",
22
+ "short": "<i2",
23
+ "int16": "<i2",
24
+ "ushort": "<u2",
25
+ "uint16": "<u2",
26
+ "int": "<i4",
27
+ "int32": "<i4",
28
+ "uint": "<u4",
29
+ "uint32": "<u4",
30
+ "float": "<f4",
31
+ "float32": "<f4",
32
+ "double": "<f8",
33
+ "float64": "<f8",
34
+ }
35
+
36
+ PathLike = Union[str, Path]
37
+
38
+
39
+ @dataclass
40
+ class Ply:
41
+ """Points are ``(N, 3)``. ``faces`` is ``(M, 3)`` when the file has a mesh."""
42
+
43
+ points: np.ndarray
44
+ colors: Optional[np.ndarray] = None
45
+ normals: Optional[np.ndarray] = None
46
+ faces: Optional[np.ndarray] = None
47
+
48
+
49
+ def load_ply(path: PathLike) -> Ply:
50
+ """Load a PLY file. Binary little-endian is the fast path."""
51
+ data = Path(path).read_bytes()
52
+ header, offset = _split_header(data)
53
+ elements, endian = _parse_header(header)
54
+ buf = data[offset:]
55
+ vertices = None
56
+ faces = None
57
+ cursor = 0
58
+ for element in elements:
59
+ if element["name"] == "vertex":
60
+ vertices, cursor = _read_fixed(buf, cursor, element, endian)
61
+ elif element["name"] == "face":
62
+ faces, cursor = _read_faces(buf, cursor, element, endian)
63
+ else:
64
+ cursor = _skip_element(buf, cursor, element, endian)
65
+ if vertices is None:
66
+ raise ValueError(f"{path} has no vertex element")
67
+ names = vertices.dtype.names
68
+ points = np.column_stack([vertices["x"], vertices["y"], vertices["z"]]).astype(np.float64, copy=False)
69
+ return Ply(points=points, colors=_colors(vertices, names), normals=_normals(vertices, names), faces=faces)
70
+
71
+
72
+ def save_ply(path: PathLike, points, colors=None, normals=None, faces=None) -> None:
73
+ """Write a binary little-endian PLY file."""
74
+ pts = np.asarray(points, dtype="<f4")
75
+ if pts.ndim != 2 or pts.shape[1] != 3:
76
+ raise ValueError("points must have shape (N, 3)")
77
+ cols = None if colors is None else _as_u8(colors, len(pts))
78
+ norms = None if normals is None else np.asarray(normals, dtype="<f4")
79
+ tris = None if faces is None else np.asarray(faces, dtype="<i4")
80
+ lines = ["ply", "format binary_little_endian 1.0", f"element vertex {len(pts)}",
81
+ "property float x", "property float y", "property float z"]
82
+ if cols is not None:
83
+ lines += ["property uchar red", "property uchar green", "property uchar blue"]
84
+ if norms is not None:
85
+ lines += ["property float nx", "property float ny", "property float nz"]
86
+ if tris is not None:
87
+ lines += [f"element face {len(tris)}", "property list uchar int vertex_indices"]
88
+ lines.append("end_header")
89
+ chunks = ["\n".join(lines).encode("ascii") + b"\n"]
90
+ names = [("x", "<f4"), ("y", "<f4"), ("z", "<f4")]
91
+ if cols is not None:
92
+ names += [("red", "u1"), ("green", "u1"), ("blue", "u1")]
93
+ if norms is not None:
94
+ names += [("nx", "<f4"), ("ny", "<f4"), ("nz", "<f4")]
95
+ table = np.empty(len(pts), dtype=names)
96
+ table["x"], table["y"], table["z"] = pts[:, 0], pts[:, 1], pts[:, 2]
97
+ if cols is not None:
98
+ table["red"], table["green"], table["blue"] = cols[:, 0], cols[:, 1], cols[:, 2]
99
+ if norms is not None:
100
+ table["nx"], table["ny"], table["nz"] = norms[:, 0], norms[:, 1], norms[:, 2]
101
+ chunks.append(table.tobytes())
102
+ if tris is not None:
103
+ # One count byte plus three little-endian ints. No struct padding.
104
+ blob = np.empty((len(tris), 13), dtype=np.uint8)
105
+ blob[:, 0] = 3
106
+ blob[:, 1:] = np.ascontiguousarray(tris[:, :3], dtype="<i4").view(np.uint8).reshape(len(tris), 12)
107
+ chunks.append(blob.tobytes())
108
+ Path(path).write_bytes(b"".join(chunks))
109
+
110
+
111
+ def rectangular_prism(size=(200.0, 120.0, 80.0), step=10.0):
112
+ """A box as a colored point cloud and as a 12-triangle mesh.
113
+
114
+ ``size`` is ``(length, width, height)``. ``step`` is the cloud spacing.
115
+ Both results are :class:`Ply` objects. The cloud samples the six faces.
116
+ The mesh is the eight corners and the shaded sides.
117
+ """
118
+ length, width, height = (float(v) for v in size)
119
+ step = float(step)
120
+ corners = np.array([
121
+ [0, 0, 0],
122
+ [length, 0, 0],
123
+ [length, width, 0],
124
+ [0, width, 0],
125
+ [0, 0, height],
126
+ [length, 0, height],
127
+ [length, width, height],
128
+ [0, width, height],
129
+ ], dtype=np.float64)
130
+ # Outward winding, two triangles per side.
131
+ faces = np.array([
132
+ [0, 2, 1], [0, 3, 2],
133
+ [4, 5, 6], [4, 6, 7],
134
+ [0, 1, 5], [0, 5, 4],
135
+ [3, 7, 6], [3, 6, 2],
136
+ [0, 4, 7], [0, 7, 3],
137
+ [1, 2, 6], [1, 6, 5],
138
+ ], dtype=np.int64)
139
+ samples = []
140
+ colors = []
141
+ palette = np.array([
142
+ [180, 80, 70],
143
+ [70, 140, 190],
144
+ [80, 170, 90],
145
+ [200, 160, 60],
146
+ [140, 90, 180],
147
+ [90, 90, 90],
148
+ ], dtype=np.uint8)
149
+ spans = (
150
+ (np.array([0, 0, 0.0]), np.array([length, 0, 0.0]), np.array([0, width, 0.0])),
151
+ (np.array([0, 0, height]), np.array([length, 0, 0.0]), np.array([0, width, 0.0])),
152
+ (np.array([0, 0, 0.0]), np.array([length, 0, 0.0]), np.array([0, 0, height])),
153
+ (np.array([0, width, 0.0]), np.array([length, 0, 0.0]), np.array([0, 0, height])),
154
+ (np.array([0, 0, 0.0]), np.array([0, width, 0.0]), np.array([0, 0, height])),
155
+ (np.array([length, 0, 0.0]), np.array([0, width, 0.0]), np.array([0, 0, height])),
156
+ )
157
+ for (origin, axis_u, axis_v), color in zip(spans, palette):
158
+ nu = max(2, int(round(np.linalg.norm(axis_u) / step)) + 1)
159
+ nv = max(2, int(round(np.linalg.norm(axis_v) / step)) + 1)
160
+ uu, vv = np.meshgrid(np.linspace(0, 1, nu), np.linspace(0, 1, nv), indexing="ij")
161
+ pts = origin + uu[..., None] * axis_u + vv[..., None] * axis_v
162
+ flat = pts.reshape(-1, 3)
163
+ samples.append(flat)
164
+ colors.append(np.broadcast_to(color, (len(flat), 3)).copy())
165
+ cloud = Ply(points=np.vstack(samples), colors=np.vstack(colors))
166
+ mesh = Ply(points=corners, faces=faces)
167
+ return cloud, mesh
168
+
169
+
170
+ def _split_header(data: bytes):
171
+ marker = b"end_header"
172
+ at = data.find(marker)
173
+ if at < 0:
174
+ raise ValueError("PLY header has no end_header")
175
+ end = at + len(marker)
176
+ if data[end:end + 1] == b"\r":
177
+ end += 1
178
+ if data[end:end + 1] == b"\n":
179
+ end += 1
180
+ return data[:at].decode("ascii", errors="replace"), end
181
+
182
+
183
+ def _parse_header(text: str):
184
+ lines = [line.strip() for line in text.splitlines() if line.strip() and not line.startswith("comment")]
185
+ if not lines or lines[0] != "ply":
186
+ raise ValueError("not a PLY file")
187
+ fmt = lines[1]
188
+ if fmt.startswith("format binary_little_endian"):
189
+ endian = "<"
190
+ elif fmt.startswith("format binary_big_endian"):
191
+ endian = ">"
192
+ elif fmt.startswith("format ascii"):
193
+ endian = "ascii"
194
+ else:
195
+ raise ValueError(f"unsupported PLY format: {fmt}")
196
+ elements = []
197
+ current = None
198
+ for line in lines[2:]:
199
+ parts = line.split()
200
+ if parts[0] == "element":
201
+ current = {"name": parts[1], "count": int(parts[2]), "props": []}
202
+ elements.append(current)
203
+ elif parts[0] == "property" and current is not None:
204
+ if parts[1] == "list":
205
+ current["props"].append(("list", _dtype(parts[2], endian), _dtype(parts[3], endian), parts[4]))
206
+ else:
207
+ current["props"].append((parts[2], _dtype(parts[1], endian)))
208
+ return elements, endian
209
+
210
+
211
+ def _dtype(name: str, endian: str) -> str:
212
+ base = _SCALAR[name]
213
+ if endian == ">" and base.startswith("<"):
214
+ return ">" + base[1:]
215
+ if endian == "ascii":
216
+ return base[1:] if base[:1] in "<>" else base
217
+ return base
218
+
219
+
220
+ def _read_fixed(buf, cursor, element, endian):
221
+ if any(prop[0] == "list" for prop in element["props"]):
222
+ raise ValueError(f"{element['name']} has a list property; only face lists are supported")
223
+ count = element["count"]
224
+ if endian == "ascii":
225
+ rows = []
226
+ text = buf[cursor:].decode("ascii")
227
+ lines = text.splitlines()
228
+ for line in lines[:count]:
229
+ rows.append([float(x) for x in line.split()])
230
+ dtype = np.dtype([(name, np.dtype(dt)) for name, dt in element["props"]])
231
+ table = np.empty(count, dtype=dtype)
232
+ raw = np.asarray(rows, dtype=np.float64)
233
+ for i, (name, dt) in enumerate(element["props"]):
234
+ table[name] = raw[:, i].astype(dt)
235
+ consumed = sum(len(line) + 1 for line in lines[:count])
236
+ return table, cursor + consumed
237
+ dtype = np.dtype([(name, np.dtype(dt)) for name, dt in element["props"]])
238
+ nbytes = count * dtype.itemsize
239
+ raw = np.frombuffer(buf, dtype=np.uint8, count=nbytes, offset=cursor).copy()
240
+ table = raw.view(dtype).reshape(count)
241
+ return table, cursor + nbytes
242
+
243
+
244
+ def _read_faces(buf, cursor, element, endian):
245
+ lists = [prop for prop in element["props"] if prop[0] == "list"]
246
+ if len(lists) != 1:
247
+ raise ValueError("face element needs one list property")
248
+ _tag, count_dt, index_dt, _name = lists[0]
249
+ count = element["count"]
250
+ if endian == "ascii":
251
+ text = buf[cursor:].decode("ascii")
252
+ lines = text.splitlines()
253
+ faces = []
254
+ for line in lines[:count]:
255
+ nums = [int(x) for x in line.split()]
256
+ n = nums[0]
257
+ faces.append(nums[1:1 + n])
258
+ width = max(len(face) for face in faces)
259
+ out = np.full((count, width), -1, dtype=np.int64)
260
+ for i, face in enumerate(faces):
261
+ out[i, :len(face)] = face
262
+ consumed = sum(len(line) + 1 for line in lines[:count])
263
+ return out[:, :3] if width >= 3 else out, cursor + consumed
264
+ count_size = np.dtype(count_dt).itemsize
265
+ index_size = np.dtype(index_dt).itemsize
266
+ first = int(np.frombuffer(buf, dtype=np.dtype(count_dt), count=1, offset=cursor)[0])
267
+ stride = count_size + first * index_size
268
+ if cursor + count * stride <= len(buf):
269
+ counts = np.frombuffer(buf, dtype=np.dtype(count_dt), count=count, offset=cursor)
270
+ # Structured view only works when every face has the same vertex count.
271
+ if int(counts[0]) == first and np.all(counts == first):
272
+ raw = np.frombuffer(buf, dtype=np.uint8, count=count * stride, offset=cursor)
273
+ indices = raw.reshape(count, stride)[:, count_size:].copy().view(np.dtype(index_dt))
274
+ indices = indices.reshape(count, first).astype(np.int64, copy=False)
275
+ return indices, cursor + count * stride
276
+ faces = []
277
+ pos = cursor
278
+ for _ in range(count):
279
+ n = int(np.frombuffer(buf, dtype=np.dtype(count_dt), count=1, offset=pos)[0])
280
+ pos += count_size
281
+ idx = np.frombuffer(buf, dtype=np.dtype(index_dt), count=n, offset=pos).astype(np.int64)
282
+ pos += n * index_size
283
+ faces.append(idx)
284
+ width = max(len(face) for face in faces) if faces else 0
285
+ out = np.full((count, max(width, 3)), -1, dtype=np.int64)
286
+ for i, face in enumerate(faces):
287
+ out[i, :len(face)] = face
288
+ return out[:, :3], pos
289
+
290
+
291
+ def _skip_element(buf, cursor, element, endian):
292
+ if endian == "ascii":
293
+ text = buf[cursor:].decode("ascii")
294
+ lines = text.splitlines()
295
+ return cursor + sum(len(line) + 1 for line in lines[:element["count"]])
296
+ if any(prop[0] == "list" for prop in element["props"]):
297
+ _faces, cursor = _read_faces(buf, cursor, element, endian)
298
+ return cursor
299
+ dtype = np.dtype([(name, np.dtype(dt)) for name, dt in element["props"] if name != "list"])
300
+ return cursor + element["count"] * dtype.itemsize
301
+
302
+
303
+ def _colors(table, names):
304
+ if names is None:
305
+ return None
306
+ triples = (("red", "green", "blue"), ("diffuse_red", "diffuse_green", "diffuse_blue"))
307
+ for keys in triples:
308
+ if all(key in names for key in keys):
309
+ return np.column_stack([table[key] for key in keys]).astype(np.uint8, copy=False)
310
+ return None
311
+
312
+
313
+ def _normals(table, names):
314
+ if names is None or not all(key in names for key in ("nx", "ny", "nz")):
315
+ return None
316
+ return np.column_stack([table["nx"], table["ny"], table["nz"]]).astype(np.float64, copy=False)
317
+
318
+
319
+ def _as_u8(colors, n):
320
+ col = np.asarray(colors)
321
+ if col.shape != (n, 3):
322
+ raise ValueError("colors must have shape (N, 3)")
323
+ if col.dtype != np.uint8 and np.nanmax(col) <= 1.0:
324
+ col = col * 255.0
325
+ return np.clip(col, 0, 255).astype(np.uint8)
cogmatplot/server.py ADDED
@@ -0,0 +1,124 @@
1
+ """Figure server.
2
+
3
+ ``python -m cogmatplot.server`` owns the windows. A debugger uses
4
+ ``PlotClient`` or ``FigureManager.connect``. Each public FigureManager
5
+ method is called with the arguments the client sent. Image updates for one
6
+ cell collapse to the latest frame. Key presses are published on ``port + 1``.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import threading
13
+ import time
14
+ import traceback
15
+
16
+ import zmq
17
+
18
+ from cogmatplot.api import METHODS
19
+ from cogmatplot.wire import Mailbox, decode
20
+
21
+
22
+ def run_server(fm, port=5555, stop_event=None, host="127.0.0.1", ready=None):
23
+ ctx = zmq.Context()
24
+ pull = ctx.socket(zmq.PULL)
25
+ pull.setsockopt(zmq.LINGER, 0)
26
+ pull.setsockopt(zmq.RCVHWM, 64)
27
+ pub = ctx.socket(zmq.PUB)
28
+ pub.setsockopt(zmq.LINGER, 0)
29
+ try:
30
+ pull.bind(f"tcp://{host}:{int(port)}")
31
+ pub.bind(f"tcp://{host}:{int(port) + 1}")
32
+ except Exception:
33
+ if ready is not None:
34
+ ready.set()
35
+ pull.close(0)
36
+ pub.close(0)
37
+ ctx.term()
38
+ raise
39
+
40
+ mailbox = Mailbox()
41
+ stopping = stop_event if stop_event is not None else threading.Event()
42
+
43
+ def emit(event):
44
+ try:
45
+ pub.send_json(event, flags=zmq.NOBLOCK)
46
+ except zmq.Again:
47
+ pass
48
+
49
+ fm._on_event = emit
50
+
51
+ def recv_loop():
52
+ while not stopping.is_set():
53
+ if not pull.poll(100):
54
+ continue
55
+ try:
56
+ method, args, kwargs = decode(pull.recv_multipart())
57
+ except Exception:
58
+ traceback.print_exc()
59
+ continue
60
+ if method not in METHODS:
61
+ print(f"cogmatplot server: ignored {method}")
62
+ continue
63
+ mailbox.push(method, args, kwargs)
64
+
65
+ thread = threading.Thread(target=recv_loop, name="cogmatplot-recv", daemon=True)
66
+ thread.start()
67
+ if ready is None:
68
+ print(f"cogmatplot server on tcp://{host}:{port} events on {int(port) + 1}")
69
+ else:
70
+ ready.set()
71
+
72
+ try:
73
+ while not stopping.is_set():
74
+ batch = mailbox.drain()
75
+ for method, args, kwargs in batch:
76
+ try:
77
+ getattr(fm, method)(*args, **kwargs)
78
+ except Exception:
79
+ print(f"cogmatplot server: {method} failed")
80
+ traceback.print_exc()
81
+ if batch or _needs_pump(fm):
82
+ try:
83
+ fm.drawnow()
84
+ except Exception:
85
+ traceback.print_exc()
86
+ time.sleep(0.01)
87
+ except KeyboardInterrupt:
88
+ pass
89
+ finally:
90
+ stopping.set()
91
+ thread.join(timeout=1)
92
+ pull.close(0)
93
+ pub.close(0)
94
+ ctx.term()
95
+
96
+
97
+ def _needs_pump(fm) -> bool:
98
+ if getattr(fm, "mode", None) != "qt":
99
+ return False
100
+ return bool(getattr(fm, "_cells", None)) or getattr(fm, "_inline_fig", None) is not None
101
+
102
+
103
+ def main(raw_args=None):
104
+ if isinstance(raw_args, str):
105
+ raw_args = [part for part in raw_args.split(" ") if part]
106
+ parser = argparse.ArgumentParser(description="cogmatplot figure server")
107
+ parser.add_argument("-p", "--port", type=int, default=5555)
108
+ parser.add_argument("-m", "--monitor", type=int, default=2)
109
+ parser.add_argument("-r", "--rows", type=int, default=2)
110
+ parser.add_argument("-c", "--cols", type=int, default=2)
111
+ parser.add_argument("--host", default="127.0.0.1")
112
+ args = parser.parse_args(raw_args)
113
+
114
+ from cogmatplot.mode import use
115
+
116
+ use("qt")
117
+ from cogmatplot.matplot import FigureManager
118
+
119
+ figure = FigureManager(args.rows, args.cols, mon=args.monitor, pause=False)
120
+ run_server(figure, port=args.port, host=args.host)
121
+
122
+
123
+ if __name__ == "__main__":
124
+ main()