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/__init__.py +46 -0
- cogmatplot/api.py +43 -0
- cogmatplot/client.py +151 -0
- cogmatplot/debug_views.py +222 -0
- cogmatplot/images.py +54 -0
- cogmatplot/layout.py +88 -0
- cogmatplot/matplot.py +967 -0
- cogmatplot/mode.py +77 -0
- cogmatplot/place.py +65 -0
- cogmatplot/ply.py +325 -0
- cogmatplot/server.py +124 -0
- cogmatplot/view3.py +353 -0
- cogmatplot/wire.py +93 -0
- cogmatplot-0.1.0.dist-info/METADATA +217 -0
- cogmatplot-0.1.0.dist-info/RECORD +19 -0
- cogmatplot-0.1.0.dist-info/WHEEL +5 -0
- cogmatplot-0.1.0.dist-info/entry_points.txt +2 -0
- cogmatplot-0.1.0.dist-info/licenses/LICENSE +21 -0
- cogmatplot-0.1.0.dist-info/top_level.txt +1 -0
cogmatplot/view3.py
ADDED
|
@@ -0,0 +1,353 @@
|
|
|
1
|
+
"""3D point-cloud views.
|
|
2
|
+
|
|
3
|
+
Pop-out mode uses a PyVista Qt window (orbit, zoom, grid). Inline mode keeps
|
|
4
|
+
the same ``scatter3`` calls and renders a static snapshot, or a matplotlib
|
|
5
|
+
3D scatter when PyVista is not available.
|
|
6
|
+
|
|
7
|
+
Clouds are ``(N, 3)`` xyz. Pass ``colors`` as ``(N, 3)`` rgb, or ``color``
|
|
8
|
+
as one solid color. An object with ``.points`` and ``.colors`` (Open3D) is
|
|
9
|
+
accepted.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from typing import Optional
|
|
15
|
+
|
|
16
|
+
import numpy as np
|
|
17
|
+
|
|
18
|
+
from cogmatplot.layout import gridfig_box
|
|
19
|
+
from cogmatplot.mode import current_mode
|
|
20
|
+
|
|
21
|
+
_VIEWS = {
|
|
22
|
+
"xy": "view_xy",
|
|
23
|
+
"xz": "view_xz",
|
|
24
|
+
"yz": "view_yz",
|
|
25
|
+
"iso": "view_isometric",
|
|
26
|
+
"isometric": "view_isometric",
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def coerce_cloud(points, colors=None):
|
|
31
|
+
"""Return ``(pts Nx3 float, colors or None)``."""
|
|
32
|
+
if hasattr(points, "points"):
|
|
33
|
+
raw = points
|
|
34
|
+
pts = np.asarray(raw.points)
|
|
35
|
+
if colors is None:
|
|
36
|
+
raw_colors = getattr(raw, "colors", None)
|
|
37
|
+
if raw_colors is not None:
|
|
38
|
+
raw_colors = np.asarray(raw_colors)
|
|
39
|
+
if getattr(raw_colors, "size", 0):
|
|
40
|
+
colors = raw_colors
|
|
41
|
+
else:
|
|
42
|
+
pts = np.asarray(points, dtype=float)
|
|
43
|
+
|
|
44
|
+
if pts.ndim != 2:
|
|
45
|
+
raise ValueError("point cloud must have shape (N, 3)")
|
|
46
|
+
if pts.shape[1] != 3 and pts.shape[0] == 3:
|
|
47
|
+
pts = pts.T
|
|
48
|
+
if pts.shape[1] != 3:
|
|
49
|
+
raise ValueError("point cloud must have shape (N, 3)")
|
|
50
|
+
|
|
51
|
+
if colors is not None:
|
|
52
|
+
colors = np.asarray(colors)
|
|
53
|
+
if colors.size == 0:
|
|
54
|
+
colors = None
|
|
55
|
+
elif (
|
|
56
|
+
colors.ndim == 2
|
|
57
|
+
and colors.shape[0] == 3
|
|
58
|
+
and colors.shape[1] == len(pts)
|
|
59
|
+
and colors.shape[1] != 3
|
|
60
|
+
):
|
|
61
|
+
colors = colors.T
|
|
62
|
+
return np.ascontiguousarray(pts, dtype=float), colors
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def add_cloud(plotter, points, color=None, colors=None, point_size=3, cmap=None, **kwargs):
|
|
66
|
+
"""Add one xyz or xyz+rgb cloud to a PyVista plotter."""
|
|
67
|
+
pts, colors = coerce_cloud(points, colors)
|
|
68
|
+
point_size = kwargs.pop("point_size", point_size)
|
|
69
|
+
if colors is None:
|
|
70
|
+
plotter.add_points(pts, color=color or "silver", point_size=point_size, **kwargs)
|
|
71
|
+
return
|
|
72
|
+
col = np.asarray(colors)
|
|
73
|
+
if col.ndim == 2 and col.shape[1] == 3:
|
|
74
|
+
rgb = col.astype(np.float64)
|
|
75
|
+
peak = np.nanmax(rgb) if rgb.size else 0
|
|
76
|
+
if peak > 1.0:
|
|
77
|
+
rgb = rgb / 255.0
|
|
78
|
+
plotter.add_points(pts, scalars=np.ascontiguousarray(rgb), rgb=True, point_size=point_size, **kwargs)
|
|
79
|
+
return
|
|
80
|
+
scalars = np.ascontiguousarray(col).reshape(-1)
|
|
81
|
+
if cmap is None:
|
|
82
|
+
plotter.add_points(pts, scalars=scalars, point_size=point_size, **kwargs)
|
|
83
|
+
else:
|
|
84
|
+
plotter.add_points(pts, scalars=scalars, cmap=cmap, point_size=point_size, **kwargs)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def add_mesh(plotter, points, faces, color=None, colors=None, style="surface", **kwargs):
|
|
88
|
+
"""Draw triangle faces. ``style`` is ``surface``, ``wireframe``, or ``both``."""
|
|
89
|
+
import pyvista as pv
|
|
90
|
+
|
|
91
|
+
pts = np.asarray(points, dtype=float)
|
|
92
|
+
tris = np.asarray(faces, dtype=np.int64)
|
|
93
|
+
if tris.ndim != 2 or tris.shape[1] < 3:
|
|
94
|
+
raise ValueError("faces must have shape (M, 3)")
|
|
95
|
+
tris = tris[:, :3]
|
|
96
|
+
packed = np.hstack([np.full((len(tris), 1), 3, dtype=np.int64), tris]).ravel()
|
|
97
|
+
poly = pv.PolyData(np.ascontiguousarray(pts), packed)
|
|
98
|
+
style = str(style or "surface").lower()
|
|
99
|
+
if style == "wireframe":
|
|
100
|
+
plotter.add_mesh(poly, style="wireframe", color=color or "black", line_width=kwargs.pop("line_width", 2), **kwargs)
|
|
101
|
+
return
|
|
102
|
+
rgb = _vertex_rgb(colors, len(pts))
|
|
103
|
+
show_edges = style in ("both", "shaded+edges", "wire")
|
|
104
|
+
if rgb is not None:
|
|
105
|
+
plotter.add_mesh(poly, scalars=rgb, rgb=True, show_edges=show_edges, edge_color=kwargs.pop("edge_color", "black"), **kwargs)
|
|
106
|
+
return
|
|
107
|
+
plotter.add_mesh(
|
|
108
|
+
poly,
|
|
109
|
+
color=color or "lightsteelblue",
|
|
110
|
+
show_edges=show_edges,
|
|
111
|
+
edge_color=kwargs.pop("edge_color", "black"),
|
|
112
|
+
**kwargs,
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _vertex_rgb(colors, count):
|
|
117
|
+
if colors is None:
|
|
118
|
+
return None
|
|
119
|
+
col = np.asarray(colors)
|
|
120
|
+
if col.ndim != 2 or col.shape[1] != 3 or len(col) != count:
|
|
121
|
+
return None
|
|
122
|
+
rgb = col.astype(np.float64)
|
|
123
|
+
if rgb.size and np.nanmax(rgb) > 1.0:
|
|
124
|
+
rgb = rgb / 255.0
|
|
125
|
+
return np.ascontiguousarray(rgb)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
class Fig3d:
|
|
129
|
+
"""One 3D view. ``.pl`` is the live PyVista plotter in pop-out mode."""
|
|
130
|
+
|
|
131
|
+
def __init__(self, title="Fig3d", show=True, grid_pos=None, off_screen: Optional[bool] = None, on_change=None):
|
|
132
|
+
self.title = title
|
|
133
|
+
self.row = None
|
|
134
|
+
self.col = None
|
|
135
|
+
self._inline = current_mode() == "inline" if off_screen is None else bool(off_screen)
|
|
136
|
+
self._grid_pos = grid_pos
|
|
137
|
+
self._on_change = on_change
|
|
138
|
+
self._layers = []
|
|
139
|
+
self._view = "xy"
|
|
140
|
+
self._grid = True
|
|
141
|
+
self._grid_shown = False
|
|
142
|
+
self._pl = None
|
|
143
|
+
if not self._inline:
|
|
144
|
+
self._open_qt()
|
|
145
|
+
if show:
|
|
146
|
+
self.show()
|
|
147
|
+
|
|
148
|
+
@staticmethod
|
|
149
|
+
def close_all():
|
|
150
|
+
try:
|
|
151
|
+
import pyvista as pv
|
|
152
|
+
|
|
153
|
+
pv.close_all()
|
|
154
|
+
except Exception:
|
|
155
|
+
pass
|
|
156
|
+
|
|
157
|
+
def place_in_grid(self, row, col, nrows, ncols, screen_index=0, margin=0):
|
|
158
|
+
"""Move the pop-out window into a monitor cell.
|
|
159
|
+
|
|
160
|
+
``grid_pos`` is ``(row, col, nrows, ncols, screen_index)``.
|
|
161
|
+
"""
|
|
162
|
+
del margin
|
|
163
|
+
if self._inline or self._pl is None:
|
|
164
|
+
return
|
|
165
|
+
x, y, w, h = gridfig_box(row, col, nrows, ncols, screen_index)
|
|
166
|
+
from cogmatplot.place import place_qt_window
|
|
167
|
+
|
|
168
|
+
place_qt_window(getattr(self._pl, "app_window", None), x, y, w, h)
|
|
169
|
+
|
|
170
|
+
def show(self, grid=True, axes=True):
|
|
171
|
+
if self._inline:
|
|
172
|
+
self._notify()
|
|
173
|
+
return self
|
|
174
|
+
if self._pl is None:
|
|
175
|
+
self._open_qt()
|
|
176
|
+
self._pl.set_background("white")
|
|
177
|
+
if axes:
|
|
178
|
+
self._pl.show_axes()
|
|
179
|
+
if grid:
|
|
180
|
+
self.grid(True)
|
|
181
|
+
self._pl.show()
|
|
182
|
+
if self._grid_pos is not None:
|
|
183
|
+
self.place_in_grid(*self._grid_pos)
|
|
184
|
+
return self
|
|
185
|
+
|
|
186
|
+
def close(self):
|
|
187
|
+
if self._pl is not None:
|
|
188
|
+
try:
|
|
189
|
+
self._pl.close()
|
|
190
|
+
except Exception:
|
|
191
|
+
pass
|
|
192
|
+
self._pl = None
|
|
193
|
+
|
|
194
|
+
def clear(self):
|
|
195
|
+
self._layers = []
|
|
196
|
+
self._grid_shown = False
|
|
197
|
+
if self._pl is not None:
|
|
198
|
+
self._pl.clear()
|
|
199
|
+
self._style_qt()
|
|
200
|
+
self._notify()
|
|
201
|
+
return self
|
|
202
|
+
|
|
203
|
+
@property
|
|
204
|
+
def pl(self):
|
|
205
|
+
if self._pl is None and not self._inline:
|
|
206
|
+
self._open_qt()
|
|
207
|
+
return self._pl
|
|
208
|
+
|
|
209
|
+
@property
|
|
210
|
+
def layers(self):
|
|
211
|
+
return list(self._layers)
|
|
212
|
+
|
|
213
|
+
def scatter3(self, points, color=None, colors=None, point_size=3, cmap=None, hold=True, **kwargs):
|
|
214
|
+
"""Add a cloud. ``hold=False`` replaces clouds already in this view."""
|
|
215
|
+
if not hold:
|
|
216
|
+
self._layers = []
|
|
217
|
+
self._grid_shown = False
|
|
218
|
+
if self._pl is not None:
|
|
219
|
+
self._pl.clear()
|
|
220
|
+
self._style_qt()
|
|
221
|
+
layer = {
|
|
222
|
+
"points": points,
|
|
223
|
+
"color": color,
|
|
224
|
+
"colors": colors,
|
|
225
|
+
"point_size": point_size,
|
|
226
|
+
"cmap": cmap,
|
|
227
|
+
"kwargs": kwargs,
|
|
228
|
+
}
|
|
229
|
+
self._layers.append(layer)
|
|
230
|
+
if self._pl is not None:
|
|
231
|
+
self._draw_layer(self._pl, layer)
|
|
232
|
+
self._notify()
|
|
233
|
+
return self
|
|
234
|
+
|
|
235
|
+
def plot_mesh(self, points, faces, color=None, colors=None, style="surface", hold=True, **kwargs):
|
|
236
|
+
"""Add a triangle mesh. ``style`` is ``surface``, ``wireframe``, or ``both``."""
|
|
237
|
+
if not hold:
|
|
238
|
+
self._layers = []
|
|
239
|
+
self._grid_shown = False
|
|
240
|
+
if self._pl is not None:
|
|
241
|
+
self._pl.clear()
|
|
242
|
+
self._style_qt()
|
|
243
|
+
layer = {
|
|
244
|
+
"kind": "mesh",
|
|
245
|
+
"points": points,
|
|
246
|
+
"faces": faces,
|
|
247
|
+
"color": color,
|
|
248
|
+
"colors": colors,
|
|
249
|
+
"style": style,
|
|
250
|
+
"kwargs": kwargs,
|
|
251
|
+
}
|
|
252
|
+
self._layers.append(layer)
|
|
253
|
+
if self._pl is not None:
|
|
254
|
+
self._draw_layer(self._pl, layer)
|
|
255
|
+
self._notify()
|
|
256
|
+
return self
|
|
257
|
+
|
|
258
|
+
def view(self, which="xy"):
|
|
259
|
+
self._view = which
|
|
260
|
+
if self._pl is not None:
|
|
261
|
+
self._apply_view(self._pl)
|
|
262
|
+
self._notify()
|
|
263
|
+
return self
|
|
264
|
+
|
|
265
|
+
def view_xy(self):
|
|
266
|
+
return self.view("xy")
|
|
267
|
+
|
|
268
|
+
def view_xz(self):
|
|
269
|
+
return self.view("xz")
|
|
270
|
+
|
|
271
|
+
def view_yz(self):
|
|
272
|
+
return self.view("yz")
|
|
273
|
+
|
|
274
|
+
def view_isometric(self):
|
|
275
|
+
return self.view("iso")
|
|
276
|
+
|
|
277
|
+
def grid(self, on=True):
|
|
278
|
+
self._grid = bool(on) and str(on).lower() != "off"
|
|
279
|
+
if self._pl is not None and self._grid and not self._grid_shown:
|
|
280
|
+
self._pl.show_grid()
|
|
281
|
+
self._grid_shown = True
|
|
282
|
+
self._notify()
|
|
283
|
+
return self
|
|
284
|
+
|
|
285
|
+
def show_grid(self):
|
|
286
|
+
return self.grid(True)
|
|
287
|
+
|
|
288
|
+
def snapshot(self, size=(720, 540)):
|
|
289
|
+
"""Render the current clouds to an RGB image."""
|
|
290
|
+
import pyvista as pv
|
|
291
|
+
|
|
292
|
+
plotter = pv.Plotter(off_screen=True, window_size=tuple(size))
|
|
293
|
+
try:
|
|
294
|
+
plotter.set_background("white")
|
|
295
|
+
for layer in self._layers:
|
|
296
|
+
self._draw_layer(plotter, layer)
|
|
297
|
+
plotter.show_axes()
|
|
298
|
+
if self._grid:
|
|
299
|
+
plotter.show_grid()
|
|
300
|
+
self._apply_view(plotter)
|
|
301
|
+
return plotter.screenshot(return_img=True)
|
|
302
|
+
finally:
|
|
303
|
+
plotter.close()
|
|
304
|
+
|
|
305
|
+
def _open_qt(self):
|
|
306
|
+
from pyvistaqt import BackgroundPlotter
|
|
307
|
+
|
|
308
|
+
self._pl = BackgroundPlotter(title=self.title or "Fig3d", auto_update=True)
|
|
309
|
+
if self._grid_pos is not None:
|
|
310
|
+
self.place_in_grid(*self._grid_pos)
|
|
311
|
+
self._style_qt()
|
|
312
|
+
for layer in self._layers:
|
|
313
|
+
self._draw_layer(self._pl, layer)
|
|
314
|
+
|
|
315
|
+
def _style_qt(self):
|
|
316
|
+
if self._pl is None:
|
|
317
|
+
return
|
|
318
|
+
self._pl.set_background("white")
|
|
319
|
+
self._pl.show_axes()
|
|
320
|
+
if self._grid and not self._grid_shown:
|
|
321
|
+
self._pl.show_grid()
|
|
322
|
+
self._grid_shown = True
|
|
323
|
+
self._apply_view(self._pl)
|
|
324
|
+
|
|
325
|
+
def _draw_layer(self, plotter, layer):
|
|
326
|
+
if layer.get("kind") == "mesh":
|
|
327
|
+
add_mesh(
|
|
328
|
+
plotter,
|
|
329
|
+
layer["points"],
|
|
330
|
+
layer["faces"],
|
|
331
|
+
color=layer.get("color"),
|
|
332
|
+
colors=layer.get("colors"),
|
|
333
|
+
style=layer.get("style") or "surface",
|
|
334
|
+
**(layer.get("kwargs") or {}),
|
|
335
|
+
)
|
|
336
|
+
return
|
|
337
|
+
add_cloud(
|
|
338
|
+
plotter,
|
|
339
|
+
layer["points"],
|
|
340
|
+
color=layer["color"],
|
|
341
|
+
colors=layer["colors"],
|
|
342
|
+
point_size=layer["point_size"],
|
|
343
|
+
cmap=layer["cmap"],
|
|
344
|
+
**layer["kwargs"],
|
|
345
|
+
)
|
|
346
|
+
|
|
347
|
+
def _apply_view(self, plotter):
|
|
348
|
+
name = _VIEWS.get(str(self._view).lower(), "view_xy")
|
|
349
|
+
getattr(plotter, name)()
|
|
350
|
+
|
|
351
|
+
def _notify(self):
|
|
352
|
+
if self._on_change is not None:
|
|
353
|
+
self._on_change(self)
|
cogmatplot/wire.py
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
"""Localhost message codec.
|
|
2
|
+
|
|
3
|
+
Command headers are pickled. ndarray payloads travel as raw buffers.
|
|
4
|
+
The server collapses back-to-back image updates for the same cell and keeps
|
|
5
|
+
every other command in order.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import pickle
|
|
11
|
+
import threading
|
|
12
|
+
from typing import List
|
|
13
|
+
|
|
14
|
+
import numpy as np
|
|
15
|
+
|
|
16
|
+
from cogmatplot.api import STREAM_METHODS
|
|
17
|
+
|
|
18
|
+
_TOKEN = "__cog_ndarray__"
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def encode(method: str, args, kwargs) -> List[bytes]:
|
|
22
|
+
buffers: List[bytes] = []
|
|
23
|
+
payload = {
|
|
24
|
+
"method": method,
|
|
25
|
+
"args": _pack(args, buffers),
|
|
26
|
+
"kwargs": _pack(kwargs, buffers),
|
|
27
|
+
}
|
|
28
|
+
frames = [pickle.dumps(payload, protocol=pickle.HIGHEST_PROTOCOL)]
|
|
29
|
+
frames.extend(buffers)
|
|
30
|
+
return frames
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def decode(frames):
|
|
34
|
+
payload = pickle.loads(frames[0])
|
|
35
|
+
buffers = list(frames[1:])
|
|
36
|
+
return payload["method"], _unpack(payload["args"], buffers), _unpack(payload["kwargs"], buffers)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _pack(obj, buffers: List[bytes]):
|
|
40
|
+
if isinstance(obj, np.ndarray):
|
|
41
|
+
arr = np.ascontiguousarray(obj)
|
|
42
|
+
buffers.append(arr.tobytes())
|
|
43
|
+
return {_TOKEN: len(buffers) - 1, "shape": list(arr.shape), "dtype": str(arr.dtype)}
|
|
44
|
+
if isinstance(obj, np.generic):
|
|
45
|
+
return obj.item()
|
|
46
|
+
if isinstance(obj, dict):
|
|
47
|
+
return {str(k): _pack(v, buffers) for k, v in obj.items()}
|
|
48
|
+
if isinstance(obj, tuple):
|
|
49
|
+
return tuple(_pack(v, buffers) for v in obj)
|
|
50
|
+
if isinstance(obj, list):
|
|
51
|
+
return [_pack(v, buffers) for v in obj]
|
|
52
|
+
return obj
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _unpack(obj, buffers):
|
|
56
|
+
if isinstance(obj, dict) and _TOKEN in obj and len(obj) == 3:
|
|
57
|
+
arr = np.frombuffer(buffers[obj[_TOKEN]], dtype=np.dtype(obj["dtype"]))
|
|
58
|
+
return arr.reshape(obj["shape"]).copy()
|
|
59
|
+
if isinstance(obj, dict):
|
|
60
|
+
return {k: _unpack(v, buffers) for k, v in obj.items()}
|
|
61
|
+
if isinstance(obj, tuple):
|
|
62
|
+
return tuple(_unpack(v, buffers) for v in obj)
|
|
63
|
+
if isinstance(obj, list):
|
|
64
|
+
return [_unpack(v, buffers) for v in obj]
|
|
65
|
+
return obj
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class Mailbox:
|
|
69
|
+
"""Ordered commands. Consecutive image updates for one cell collapse."""
|
|
70
|
+
|
|
71
|
+
def __init__(self):
|
|
72
|
+
self._lock = threading.Lock()
|
|
73
|
+
self._queue = []
|
|
74
|
+
|
|
75
|
+
def push(self, method: str, args, kwargs) -> None:
|
|
76
|
+
item = (method, args, kwargs)
|
|
77
|
+
with self._lock:
|
|
78
|
+
if (
|
|
79
|
+
method in STREAM_METHODS
|
|
80
|
+
and len(args) >= 2
|
|
81
|
+
and self._queue
|
|
82
|
+
and self._queue[-1][0] == method
|
|
83
|
+
and tuple(self._queue[-1][1][:2]) == tuple(args[:2])
|
|
84
|
+
):
|
|
85
|
+
self._queue[-1] = item
|
|
86
|
+
return
|
|
87
|
+
self._queue.append(item)
|
|
88
|
+
|
|
89
|
+
def drain(self):
|
|
90
|
+
with self._lock:
|
|
91
|
+
queued = self._queue
|
|
92
|
+
self._queue = []
|
|
93
|
+
return queued
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cogmatplot
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: MATLAB-style 2D and 3D figures, inline or on another monitor
|
|
5
|
+
Author-email: Cogency <mathew@cogency.co.za>
|
|
6
|
+
License: MIT
|
|
7
|
+
Requires-Python: >=3.9
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Requires-Dist: numpy
|
|
11
|
+
Requires-Dist: matplotlib
|
|
12
|
+
Requires-Dist: pyzmq
|
|
13
|
+
Requires-Dist: screeninfo
|
|
14
|
+
Requires-Dist: opencv-python
|
|
15
|
+
Requires-Dist: PyQt5
|
|
16
|
+
Requires-Dist: pyvista
|
|
17
|
+
Requires-Dist: pyvistaqt
|
|
18
|
+
Dynamic: license-file
|
|
19
|
+
|
|
20
|
+
# cogmatplot
|
|
21
|
+
|
|
22
|
+
I often like to work with many types of plots and viewers (and miss the versatility of MATLAB figures) when doing research, so I made this library for Python.
|
|
23
|
+
One grid can hold images, 2D plots, 3D lines, and point clouds. Each tile picks its own viewer: matplotlib, an OpenCV window, or a PyVista 3D view. `FigureManager(rows, cols, mon)` places
|
|
24
|
+
that grid on any monitor; use a different `mon` when you want another screen. Heads up:The library is intended for development and debugging workflows, not end-user applications.
|
|
25
|
+
|
|
26
|
+
Example of 2x2 grid plotted with `inline` backend (from `examples/scene.py`). In `Qt` mode the same four cells are separate windows on the monitor you choose.
|
|
27
|
+
|
|
28
|
+

|
|
29
|
+
|
|
30
|
+
Pick where the figures go:
|
|
31
|
+
|
|
32
|
+
- **Inline** draws static figures in a notebook or interactive window.
|
|
33
|
+
- **Qt** opens interactive windows on a monitor. You can pan, zoom, and orbit.
|
|
34
|
+
- **Server** lets another process send the same calls to those windows.
|
|
35
|
+
|
|
36
|
+
## Install
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
pip install -e .
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
or `pip install -r requirements.txt`. That installs the viewers with the library:
|
|
43
|
+
|
|
44
|
+
| Package | Used for |
|
|
45
|
+
| --- | --- |
|
|
46
|
+
| `numpy`, `matplotlib` | 2D plots, images, and inline figures |
|
|
47
|
+
| `PyQt5` | Pop-out windows on a monitor |
|
|
48
|
+
| `pyvista`, `pyvistaqt` | Interactive 3D points and meshes |
|
|
49
|
+
| `opencv-python` | Fast live image tiles |
|
|
50
|
+
| `screeninfo` | Which monitor a tile lands on |
|
|
51
|
+
| `pyzmq` | The debug server |
|
|
52
|
+
|
|
53
|
+
## Quickstart
|
|
54
|
+
|
|
55
|
+
Call `use` before importing `FigureManager`.
|
|
56
|
+
|
|
57
|
+
### Notebook or interactive window
|
|
58
|
+
|
|
59
|
+
Figures stay in the output. They are not interactive.
|
|
60
|
+
|
|
61
|
+
```python
|
|
62
|
+
import numpy as np
|
|
63
|
+
import cogmatplot
|
|
64
|
+
|
|
65
|
+
cogmatplot.use("inline")
|
|
66
|
+
from cogmatplot import FigureManager
|
|
67
|
+
|
|
68
|
+
x = np.linspace(0, 2 * np.pi, 200)
|
|
69
|
+
image = np.zeros((120, 160, 3), np.uint8)
|
|
70
|
+
image[:, :, 1] = 180
|
|
71
|
+
|
|
72
|
+
fm = FigureManager(1, 2)
|
|
73
|
+
fm.imshow(0, 0, image, title="image")
|
|
74
|
+
fm.plot(0, 1, x, np.sin(x), ".-", label="sin", xlabel="x", ylabel="y")
|
|
75
|
+
fm.drawnow()
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
Open `examples/notebook_inline.ipynb` for the same idea with a 3D line and a point cloud.
|
|
79
|
+
|
|
80
|
+
### Interactive windows on a monitor
|
|
81
|
+
|
|
82
|
+
```python
|
|
83
|
+
%matplotlib qt
|
|
84
|
+
|
|
85
|
+
import cogmatplot
|
|
86
|
+
cogmatplot.use("qt")
|
|
87
|
+
from cogmatplot import FigureManager, closeAll
|
|
88
|
+
|
|
89
|
+
MON = 0 # screen index
|
|
90
|
+
|
|
91
|
+
closeAll()
|
|
92
|
+
fm = FigureManager(1, 2, MON, pause=False)
|
|
93
|
+
fm.plot(0, 0, [0, 1, 2], [0, 1, 0], "o-")
|
|
94
|
+
fm.drawnow()
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
`FigureManager(rows, cols, mon)` places one window in each cell of that screen. `pause=False` updates without a pause after every call. Call `drawnow()` when you want the windows to refresh.
|
|
98
|
+
|
|
99
|
+
See `examples/interactive_qt.py`.
|
|
100
|
+
|
|
101
|
+
## 2D and 3D
|
|
102
|
+
|
|
103
|
+
```python
|
|
104
|
+
fm = FigureManager(2, 2, pause=False)
|
|
105
|
+
|
|
106
|
+
fm.imshow(0, 0, image, title="image")
|
|
107
|
+
fm.hold(0, 0, "on")
|
|
108
|
+
fm.plot(0, 0, poly[:, 0], poly[:, 1], "y-", grid=0)
|
|
109
|
+
fm.axis(0, 0, "off")
|
|
110
|
+
|
|
111
|
+
fm.plot(0, 1, x, y, ".-", label="sin")
|
|
112
|
+
fm.hold(0, 1, "on")
|
|
113
|
+
fm.plot(0, 1, x, y2, "-", label="cos")
|
|
114
|
+
fm.legend(0, 1)
|
|
115
|
+
|
|
116
|
+
fm.plot3(1, 0, x, y, z, "-")
|
|
117
|
+
fm.title(1, 0, "plot3")
|
|
118
|
+
|
|
119
|
+
cloud = fm.figure3(1, 1, title="depth")
|
|
120
|
+
cloud.scatter3(points, colors=rgb, point_size=3) # (N, 3) xyz and (N, 3) rgb
|
|
121
|
+
cloud.scatter3(tag, color="red", point_size=8) # xyz, one color
|
|
122
|
+
cloud.show_grid()
|
|
123
|
+
cloud.view_xy()
|
|
124
|
+
fm.drawnow()
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
`colors` can be `uint8` or float `0–1`. A single `color` such as `"silver"` or `"red"` paints the whole cloud. An object with `.points` and `.colors` (for example an Open3D cloud) is accepted.
|
|
128
|
+
|
|
129
|
+
`hold on` adds another series. The next `plot` without hold updates the current line in place.
|
|
130
|
+
|
|
131
|
+
Names follow MATLAB: `plot`, `plot3`, `imshow`, `imagesc`, `hold`, `axis`, `grid`, `title`, `xlabel`, `ylabel`, `xlim`, `ylim`, `zlim`, `legend`, `colorbar`, `text`, `rectangle`, `clf`, `cla`, `closeAll`, `drawnow`.
|
|
132
|
+
|
|
133
|
+
In-process, `imshow` and `plot` also return the matplotlib axes, so `ax.plot(...)` still works. Over the server, use the `FigureManager` methods above. They do the same thing.
|
|
134
|
+
|
|
135
|
+
## Fast image streams
|
|
136
|
+
|
|
137
|
+
OpenCV windows are the path for live frames. Publish by name, then render once per frame. Nothing is shown until `init_debug_views`.
|
|
138
|
+
|
|
139
|
+
```python
|
|
140
|
+
from cogmatplot.debug_views import init_debug_views, debug_image, render_debug_views
|
|
141
|
+
|
|
142
|
+
init_debug_views(cols=2, monitor=0)
|
|
143
|
+
debug_image("gray", gray)
|
|
144
|
+
debug_image("color", color)
|
|
145
|
+
render_debug_views()
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
`examples/debug_streams.py` is a short loop.
|
|
149
|
+
|
|
150
|
+
You can also put an OpenCV tile in a `FigureManager` cell:
|
|
151
|
+
|
|
152
|
+
```python
|
|
153
|
+
fm.imshow(0, 0, frame, viewer="cv", title="live")
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
In inline mode that same call draws a static image in the output.
|
|
157
|
+
|
|
158
|
+
## PLY point clouds and meshes
|
|
159
|
+
|
|
160
|
+
Binary PLY files load through `numpy` after the header. That is the fast path. A rectangular prism is included as sample data: a colored face cloud and a 12-triangle box.
|
|
161
|
+
|
|
162
|
+
```python
|
|
163
|
+
from pathlib import Path
|
|
164
|
+
from cogmatplot.ply import load_ply
|
|
165
|
+
|
|
166
|
+
data = Path("examples/data")
|
|
167
|
+
cloud = load_ply(data / "prism_cloud.ply")
|
|
168
|
+
x, y, z = cloud.points.T
|
|
169
|
+
fm.plot3(0, 0, x, y, z, ".", colors=cloud.colors, point_size=8)
|
|
170
|
+
|
|
171
|
+
mesh = load_ply(data / "prism_mesh.ply")
|
|
172
|
+
fm.plot_mesh(0, 1, mesh.points, mesh.faces, style="wireframe")
|
|
173
|
+
fm.plot_mesh(1, 0, mesh.points, mesh.faces, style="surface", color="lightsteelblue")
|
|
174
|
+
fm.plot_mesh(1, 1, mesh.points, mesh.faces, style="both", color="lightsteelblue")
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
`load_ply` only reads the file. It returns `.points`, `.colors`, `.normals`, and `.faces`. `plot3` is the MATLAB call: `plot3(x, y, z, '-')` is a 3D line, and `plot3(x, y, z, '.')` is a point cloud. `plot_mesh` draws faces. `style` is `surface` (shaded), `wireframe`, or `both`. `rectangular_prism()` builds the same box in memory, and `save_ply` writes it back out.
|
|
178
|
+
|
|
179
|
+
`examples/ply_prism.py` loads the two sample files.
|
|
180
|
+
|
|
181
|
+
## Server
|
|
182
|
+
|
|
183
|
+
The server owns the windows. A debugger, or any other process, sends the same calls.
|
|
184
|
+
|
|
185
|
+
```bash
|
|
186
|
+
python -m cogmatplot.server -m 0 -r 2 -c 2
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
`-m` is the monitor (default 2), `-r` and `-c` are the grid, `-p` is the port (default 5555). Key presses from the windows are published on the next port.
|
|
190
|
+
|
|
191
|
+
```python
|
|
192
|
+
from cogmatplot import FigureManager
|
|
193
|
+
from scene import draw # examples/scene.py
|
|
194
|
+
|
|
195
|
+
fm = FigureManager.connect("127.0.0.1", 5555)
|
|
196
|
+
fm.reset(2, 2, 0)
|
|
197
|
+
draw(fm)
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
`examples/debug_client.py` is that client. `PlotClient` is the same object `connect` returns. Older names still work: `close_all`, `clf_all`, `inter`, and `box`.
|
|
201
|
+
|
|
202
|
+
## Examples
|
|
203
|
+
|
|
204
|
+
| File | What it shows |
|
|
205
|
+
| --- | --- |
|
|
206
|
+
| `examples/notebook_inline.ipynb` | Static notebook figures |
|
|
207
|
+
| `examples/interactive_qt.py` | Interactive windows on a monitor |
|
|
208
|
+
| `examples/debug_streams.py` | Named OpenCV streams |
|
|
209
|
+
| `examples/debug_client.py` | Plot into the server |
|
|
210
|
+
| `examples/scene.py` | The shared 2×2 scene used above |
|
|
211
|
+
| `examples/ply_prism.py` | PLY point cloud, wireframe, and shaded mesh |
|
|
212
|
+
|
|
213
|
+
## Tests
|
|
214
|
+
|
|
215
|
+
```bash
|
|
216
|
+
python -m unittest discover -s tests
|
|
217
|
+
```
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
cogmatplot/__init__.py,sha256=JLWBA6cYzfoUQ5Tqg6OpHaXht2rMRkTZgQGJqAPVAc8,1202
|
|
2
|
+
cogmatplot/api.py,sha256=PCthp8PXW25Fn7J_SVytcfeYpRuco8EWhLnsu0rNwGE,703
|
|
3
|
+
cogmatplot/client.py,sha256=M_l94c9PTXgwKNJcAsi4vD5F_eKGmMhV7TGXa93UnB8,4663
|
|
4
|
+
cogmatplot/debug_views.py,sha256=pVx6-NNhRaS1UPbhzcNGZ6_zZXKr7YHli_4tcV1cdW8,6717
|
|
5
|
+
cogmatplot/images.py,sha256=74r8xdKh1rg-mWf3cWdOX1dh_6G5K4lcH7VTPnrTafE,1576
|
|
6
|
+
cogmatplot/layout.py,sha256=gm0q4vgmQkwKh9oOnzZeubugjP8dU510TKpA4h-RoJ8,2546
|
|
7
|
+
cogmatplot/matplot.py,sha256=S5Q_pc6myatLMbieGpJz5ate3Z8PkPImcRhPN9xUeqk,29793
|
|
8
|
+
cogmatplot/mode.py,sha256=p2Po5azAJPvilLffiyCpT3Uw9lIPRBJrDYB5_f5V_4I,2164
|
|
9
|
+
cogmatplot/place.py,sha256=lAPcUMtKb-E_IOzR9RrZVHAdPz3Ps-X6S7dp4sTklB8,2169
|
|
10
|
+
cogmatplot/ply.py,sha256=Hm8Bj3_3bXfnEuJ7K5xd6J56N7sMaDYgpHSkBY6zAmQ,12907
|
|
11
|
+
cogmatplot/server.py,sha256=9YzrD4B3y2e-x78Hmoa-Zjo57JPOXeTXpSaWSm58Q-Y,3734
|
|
12
|
+
cogmatplot/view3.py,sha256=WJ-VVAX9M-1abACJ6NCdla7lG4nFZfVdkjQlwVQBfN4,11123
|
|
13
|
+
cogmatplot/wire.py,sha256=zlvIrsjRZNMp1pYzXFqo_G0V9-Ug10z9rtubd6OQm4c,2783
|
|
14
|
+
cogmatplot-0.1.0.dist-info/licenses/LICENSE,sha256=YtB2ttaV284jK6kyEQO8V_fIgXcxm_pYNovr_RLL1_A,1064
|
|
15
|
+
cogmatplot-0.1.0.dist-info/METADATA,sha256=BeXtSYCANsoDtniNeO0bTmCm7_uaKcz_z9I2iMC6EEI,7255
|
|
16
|
+
cogmatplot-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
17
|
+
cogmatplot-0.1.0.dist-info/entry_points.txt,sha256=9yf0OK3awCzrghkPrJsGb92rW6A_vH97GxzPInPjrq4,61
|
|
18
|
+
cogmatplot-0.1.0.dist-info/top_level.txt,sha256=spxZMSpYGU7n1D8Fxwgus5Sr-GKI0W4QQfP_2ZQjARc,11
|
|
19
|
+
cogmatplot-0.1.0.dist-info/RECORD,,
|