File size: 12,962 Bytes
45950ff
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
387
388
389
390
391
392
393
394
395
396
"""
The matplotlib plotter implementation for all the primitive tasks (in our case: lines and
dots)
"""
from typing import Any, Callable, Dict, List

import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as p3

import numpy as np

from .core import BasePlotter, BasePlotterTask


class Matplotlib2DPlotter(BasePlotter):
    _fig: plt.figure  # plt figure
    _ax: plt.axis  # plt axis
    # stores artist objects for each task (task name as the key)
    _artist_cache: Dict[str, Any]
    # callables for each task primitives
    _create_impl_callables: Dict[str, Callable]
    _update_impl_callables: Dict[str, Callable]

    def __init__(self, task: "BasePlotterTask") -> None:
        fig, ax = plt.subplots()
        self._fig = fig
        self._ax = ax
        self._artist_cache = {}

        self._create_impl_callables = {
            "Draw2DLines": self._lines_create_impl,
            "Draw2DDots": self._dots_create_impl,
            "Draw2DTrail": self._trail_create_impl,
        }
        self._update_impl_callables = {
            "Draw2DLines": self._lines_update_impl,
            "Draw2DDots": self._dots_update_impl,
            "Draw2DTrail": self._trail_update_impl,
        }
        self._init_lim()
        super().__init__(task)

    @property
    def ax(self):
        return self._ax

    @property
    def fig(self):
        return self._fig

    def show(self):
        plt.show()

    def _min(self, x, y):
        if x is None:
            return y
        if y is None:
            return x
        return min(x, y)

    def _max(self, x, y):
        if x is None:
            return y
        if y is None:
            return x
        return max(x, y)

    def _init_lim(self):
        self._curr_x_min = None
        self._curr_y_min = None
        self._curr_x_max = None
        self._curr_y_max = None

    def _update_lim(self, xs, ys):
        self._curr_x_min = self._min(np.min(xs), self._curr_x_min)
        self._curr_y_min = self._min(np.min(ys), self._curr_y_min)
        self._curr_x_max = self._max(np.max(xs), self._curr_x_max)
        self._curr_y_max = self._max(np.max(ys), self._curr_y_max)

    def _set_lim(self):
        if not (
            self._curr_x_min is None
            or self._curr_x_max is None
            or self._curr_y_min is None
            or self._curr_y_max is None
        ):
            self._ax.set_xlim(self._curr_x_min, self._curr_x_max)
            self._ax.set_ylim(self._curr_y_min, self._curr_y_max)
        self._init_lim()

    @staticmethod
    def _lines_extract_xy_impl(index, lines_task):
        return lines_task[index, :, 0], lines_task[index, :, 1]

    @staticmethod
    def _trail_extract_xy_impl(index, trail_task):
        return (trail_task[index : index + 2, 0], trail_task[index : index + 2, 1])

    def _lines_create_impl(self, lines_task):
        color = lines_task.color
        self._artist_cache[lines_task.task_name] = [
            self._ax.plot(
                *Matplotlib2DPlotter._lines_extract_xy_impl(i, lines_task),
                color=color,
                linewidth=lines_task.line_width,
                alpha=lines_task.alpha
            )[0]
            for i in range(len(lines_task))
        ]

    def _lines_update_impl(self, lines_task):
        lines_artists = self._artist_cache[lines_task.task_name]
        for i in range(len(lines_task)):
            artist = lines_artists[i]
            xs, ys = Matplotlib2DPlotter._lines_extract_xy_impl(i, lines_task)
            artist.set_data(xs, ys)
            if lines_task.influence_lim:
                self._update_lim(xs, ys)

    def _dots_create_impl(self, dots_task):
        color = dots_task.color
        self._artist_cache[dots_task.task_name] = self._ax.plot(
            dots_task[:, 0],
            dots_task[:, 1],
            c=color,
            linestyle="",
            marker=".",
            markersize=dots_task.marker_size,
            alpha=dots_task.alpha,
        )[0]

    def _dots_update_impl(self, dots_task):
        dots_artist = self._artist_cache[dots_task.task_name]
        dots_artist.set_data(dots_task[:, 0], dots_task[:, 1])
        if dots_task.influence_lim:
            self._update_lim(dots_task[:, 0], dots_task[:, 1])

    def _trail_create_impl(self, trail_task):
        color = trail_task.color
        trail_length = len(trail_task) - 1
        self._artist_cache[trail_task.task_name] = [
            self._ax.plot(
                *Matplotlib2DPlotter._trail_extract_xy_impl(i, trail_task),
                color=trail_task.color,
                linewidth=trail_task.line_width,
                alpha=trail_task.alpha * (1.0 - i / (trail_length - 1))
            )[0]
            for i in range(trail_length)
        ]

    def _trail_update_impl(self, trail_task):
        trails_artists = self._artist_cache[trail_task.task_name]
        for i in range(len(trail_task) - 1):
            artist = trails_artists[i]
            xs, ys = Matplotlib2DPlotter._trail_extract_xy_impl(i, trail_task)
            artist.set_data(xs, ys)
            if trail_task.influence_lim:
                self._update_lim(xs, ys)

    def _create_impl(self, task_list):
        for task in task_list:
            self._create_impl_callables[task.task_type](task)
        self._draw()

    def _update_impl(self, task_list):
        for task in task_list:
            self._update_impl_callables[task.task_type](task)
        self._draw()

    def _set_aspect_equal_2d(self, zero_centered=True):
        xlim = self._ax.get_xlim()
        ylim = self._ax.get_ylim()

        if not zero_centered:
            xmean = np.mean(xlim)
            ymean = np.mean(ylim)
        else:
            xmean = 0
            ymean = 0

        plot_radius = max(
            [
                abs(lim - mean_)
                for lims, mean_ in ((xlim, xmean), (ylim, ymean))
                for lim in lims
            ]
        )

        self._ax.set_xlim([xmean - plot_radius, xmean + plot_radius])
        self._ax.set_ylim([ymean - plot_radius, ymean + plot_radius])

    def _draw(self):
        self._set_lim()
        self._set_aspect_equal_2d()
        self._fig.canvas.draw()
        self._fig.canvas.flush_events()
        plt.pause(0.00001)


class Matplotlib3DPlotter(BasePlotter):
    _fig: plt.figure  # plt figure
    _ax: p3.Axes3D  # plt 3d axis
    # stores artist objects for each task (task name as the key)
    _artist_cache: Dict[str, Any]
    # callables for each task primitives
    _create_impl_callables: Dict[str, Callable]
    _update_impl_callables: Dict[str, Callable]

    def __init__(self, task: "BasePlotterTask") -> None:
        self._fig = plt.figure()
        self._ax = p3.Axes3D(self._fig)
        self._artist_cache = {}

        self._create_impl_callables = {
            "Draw3DLines": self._lines_create_impl,
            "Draw3DDots": self._dots_create_impl,
            "Draw3DTrail": self._trail_create_impl,
        }
        self._update_impl_callables = {
            "Draw3DLines": self._lines_update_impl,
            "Draw3DDots": self._dots_update_impl,
            "Draw3DTrail": self._trail_update_impl,
        }
        self._init_lim()
        super().__init__(task)

    @property
    def ax(self):
        return self._ax

    @property
    def fig(self):
        return self._fig

    def show(self):
        plt.show()

    def _min(self, x, y):
        if x is None:
            return y
        if y is None:
            return x
        return min(x, y)

    def _max(self, x, y):
        if x is None:
            return y
        if y is None:
            return x
        return max(x, y)

    def _init_lim(self):
        self._curr_x_min = None
        self._curr_y_min = None
        self._curr_z_min = None
        self._curr_x_max = None
        self._curr_y_max = None
        self._curr_z_max = None

    def _update_lim(self, xs, ys, zs):
        self._curr_x_min = self._min(np.min(xs), self._curr_x_min)
        self._curr_y_min = self._min(np.min(ys), self._curr_y_min)
        self._curr_z_min = self._min(np.min(zs), self._curr_z_min)
        self._curr_x_max = self._max(np.max(xs), self._curr_x_max)
        self._curr_y_max = self._max(np.max(ys), self._curr_y_max)
        self._curr_z_max = self._max(np.max(zs), self._curr_z_max)

    def _set_lim(self):
        if not (
            self._curr_x_min is None
            or self._curr_x_max is None
            or self._curr_y_min is None
            or self._curr_y_max is None
            or self._curr_z_min is None
            or self._curr_z_max is None
        ):
            self._ax.set_xlim3d(self._curr_x_min, self._curr_x_max)
            self._ax.set_ylim3d(self._curr_y_min, self._curr_y_max)
            self._ax.set_zlim3d(self._curr_z_min, self._curr_z_max)
        self._init_lim()

    @staticmethod
    def _lines_extract_xyz_impl(index, lines_task):
        return lines_task[index, :, 0], lines_task[index, :, 1], lines_task[index, :, 2]

    @staticmethod
    def _trail_extract_xyz_impl(index, trail_task):
        return (
            trail_task[index : index + 2, 0],
            trail_task[index : index + 2, 1],
            trail_task[index : index + 2, 2],
        )

    def _lines_create_impl(self, lines_task):
        color = lines_task.color
        self._artist_cache[lines_task.task_name] = [
            self._ax.plot(
                *Matplotlib3DPlotter._lines_extract_xyz_impl(i, lines_task),
                color=color,
                linewidth=lines_task.line_width,
                alpha=lines_task.alpha
            )[0]
            for i in range(len(lines_task))
        ]

    def _lines_update_impl(self, lines_task):
        lines_artists = self._artist_cache[lines_task.task_name]
        for i in range(len(lines_task)):
            artist = lines_artists[i]
            xs, ys, zs = Matplotlib3DPlotter._lines_extract_xyz_impl(i, lines_task)
            artist.set_data(xs, ys)
            artist.set_3d_properties(zs)
            if lines_task.influence_lim:
                self._update_lim(xs, ys, zs)

    def _dots_create_impl(self, dots_task):
        color = dots_task.color
        self._artist_cache[dots_task.task_name] = self._ax.plot(
            dots_task[:, 0],
            dots_task[:, 1],
            dots_task[:, 2],
            c=color,
            linestyle="",
            marker=".",
            markersize=dots_task.marker_size,
            alpha=dots_task.alpha,
        )[0]

    def _dots_update_impl(self, dots_task):
        dots_artist = self._artist_cache[dots_task.task_name]
        dots_artist.set_data(dots_task[:, 0], dots_task[:, 1])
        dots_artist.set_3d_properties(dots_task[:, 2])
        if dots_task.influence_lim:
            self._update_lim(dots_task[:, 0], dots_task[:, 1], dots_task[:, 2])

    def _trail_create_impl(self, trail_task):
        color = trail_task.color
        trail_length = len(trail_task) - 1
        self._artist_cache[trail_task.task_name] = [
            self._ax.plot(
                *Matplotlib3DPlotter._trail_extract_xyz_impl(i, trail_task),
                color=trail_task.color,
                linewidth=trail_task.line_width,
                alpha=trail_task.alpha * (1.0 - i / (trail_length - 1))
            )[0]
            for i in range(trail_length)
        ]

    def _trail_update_impl(self, trail_task):
        trails_artists = self._artist_cache[trail_task.task_name]
        for i in range(len(trail_task) - 1):
            artist = trails_artists[i]
            xs, ys, zs = Matplotlib3DPlotter._trail_extract_xyz_impl(i, trail_task)
            artist.set_data(xs, ys)
            artist.set_3d_properties(zs)
            if trail_task.influence_lim:
                self._update_lim(xs, ys, zs)

    def _create_impl(self, task_list):
        for task in task_list:
            self._create_impl_callables[task.task_type](task)
        self._draw()

    def _update_impl(self, task_list):
        for task in task_list:
            self._update_impl_callables[task.task_type](task)
        self._draw()

    def _set_aspect_equal_3d(self):
        xlim = self._ax.get_xlim3d()
        ylim = self._ax.get_ylim3d()
        zlim = self._ax.get_zlim3d()

        xmean = np.mean(xlim)
        ymean = np.mean(ylim)
        zmean = np.mean(zlim)

        plot_radius = max(
            [
                abs(lim - mean_)
                for lims, mean_ in ((xlim, xmean), (ylim, ymean), (zlim, zmean))
                for lim in lims
            ]
        )

        self._ax.set_xlim3d([xmean - plot_radius, xmean + plot_radius])
        self._ax.set_ylim3d([ymean - plot_radius, ymean + plot_radius])
        self._ax.set_zlim3d([zmean - plot_radius, zmean + plot_radius])

    def _draw(self):
        self._set_lim()
        self._set_aspect_equal_3d()
        self._fig.canvas.draw()
        self._fig.canvas.flush_events()
        plt.pause(0.00001)