반응형

본 글은 다음 글에 이어 나오는 글이다.

[PYTHON] matplotlib.animation 빠르게 그리기 : blitting, https://stella47.tistory.com/449

[PyQt5] 새 창을 띄워서 matplotlib.animation으로 실시간 그래프 그리기, https://stella47.tistory.com/445

 

 

고치다 말았는데, plt.subplot의 용법을 보면 할 수 있을 거 같다.

fig, (ax1, ax2) = plt.subplot(1,2) 

이런 식이다.

더보기를 누르면 코드를 볼 수 있다.

더보기
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
import sys
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtWidgets import QPushButton, QLabel, QComboBox
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QVBoxLayout
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.backend_bases import FigureCanvasBase
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
 
from pubsub import pub
import multiprocessing as mp
import time
import math
 
from stop_watch import StopWatch
 
QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)
 
class FigureBase(QWidget):
    def __init__(self):
        super().__init__()
        
        # Default Figure Setting
        self._time_scale = 10
        self._change_fig = False
 
        pub.subscribe(self._cb_figure_cmd_rx, "figure_cmd_rx")
        pub.subscribe(self._cb_figure_data_rx, "figure_data_rx")
        # To check running time
        self._stop_watch_draw = StopWatch()
        self._stop_watch_module = StopWatch()
        
        self._init_draw()
        self._init_UI()
 
        self._timer_freq = 20
        self._timer = QTimer(self)
        self._timer.start()
        self._timer.setInterval(int(1000/self._timer_freq))
        self._timer.timeout.connect(self.update)
 
        self.setGeometry(310,300,400,600)
        self.show()
 
    def __del__(self):
        plt.close()
 
    # override figure close event from QWidget
    def closeEvent(self, event):
        plt.close()
        self.close()
 
    def _init_UI(self):
        vbox = QVBoxLayout()
        vbox.addWidget(self._toolbar)
        vbox.addWidget(self._canvas)
        self.setLayout(vbox)
        self.setGeometry(400,300,400,600)
 
    def _init_draw(self):
        # sub-class will store data at this lists
        self._number_of_figures = 3
        self._time = list()
        self._data = list()
        self._data.append(list([]))
        self._data.append(list([]))
        self._data.append(list([]))
        self._data.append(list([]))
        self._fig = plt.Figure()
        self._canvas = self._fig.canvas
        self._toolbar = NavigationToolbar(self._canvas, self)
 
        # Figure Settings
        cfg = list()
        cfg.append(list([0]))
        cfg.append(list([]))
        cfg.append(list([]))
        # make figure list
        self._plots = list()
        
        # Figure Loop
        for fig_idx in range(0self._number_of_figures):
            self._plots.append({"FIGURE":self._fig.add_subplot(self._number_of_figures,1,fig_idx+1)})
            self._plots[fig_idx]['INDEX'= cfg[fig_idx]
 
        self._update_figure_configuration()
        self._set_initial_background()
 
    # have some changes about figure setting, 
    def _update_figure_configuration(self):
        for fig_idx in range(0self._number_of_figures):
            self._plots[fig_idx]['FIGURE'].clear()
            self._plots[fig_idx]['LINES'= list()
            # Line Loop
            for line_idx in range(len(self._plots[fig_idx]['INDEX'])):
                (line, ) = self._plots[fig_idx]['FIGURE'].plot([0,0], [0,0], animated=True)
                self._plots[fig_idx]['LINES'].append(line)
 
    # set background for blit
    def _set_initial_background(self):
        for fig_idx in range(0self._number_of_figures):
            self._plots[fig_idx]['FIGURE'].set_xlim(0,self._time_scale)
            self._plots[fig_idx]['FIGURE'].set_ylim(-2.02.0)
        self.bg = self._fig.canvas.copy_from_bbox(self._fig.bbox)
        self._fig.canvas.blit(self._fig.bbox)
 
    def update(self):
        self._before_drawing()
 
        self._draw_plots()
 
        self._stop_watch_module.click()
        pub.sendMessage("draw_dt",msgData=self._stop_watch_module.get_dt())
 
    # 그리기 전에 아무거나 계산
    def _before_drawing(self):
        self._stop_watch_module.click()
        pub.sendMessage("draw_dt",msgData=self._stop_watch_module.get_dt())
 
        # Check configure changes
        if(self._change_fig == True):
            self._update_figure_configuration()
            
        x = self._stop_watch_draw.get_time_since()
        self._time.append(x)
        self._data[0].append(math.sin(x))
        self._data[1].append(math.cos(x))
        self._data[2].append(math.sin(x/2)*2.0)
        self._data[3].append(math.cos(x/2)*2.0)
 
    def _blit_wrapper_for_draw(func):
        def wrapper(self*args, **kwargs):
            self._fig.canvas.restore_region(self.bg)
            func(self*args, **kwargs)
            self._fig.canvas.blit(self._fig.bbox)
            self._fig.canvas.flush_events()
        return wrapper
        
    @_blit_wrapper_for_draw
    def _draw_plots(self):
        min_idx = self._find_x_lim()
        for item in self._plots:
            item['FIGURE'].clear()
            item['FIGURE'].grid()
            # Put each data @ sub-class
            for idx in item['INDEX']:
                item['LINES'].set_xdata(self._time)
                item['LINES'].set_ydata(self._data[idx])
                item['FIGURE'].draw_artist(item['LINES'])
            if(len(self._time) >= 2):
                item['FIGURE'].set_xlim(self._time[-1]-self._time_scale, self._time[-1])
 
    def _cb_figure_cmd_rx(self, msgData):
        # print(msgData)
        figure  = msgData['FIGURE']
        idx     = msgData['INDEX']
        cmd     = msgData['COMMAND']
        if(cmd == 'ADD'):
            if(idx not in self._plots[figure]['INDEX']):
                self._plots[figure]['INDEX'].append(idx)
                self._change_fig = True
        else# REMOVE
            if(idx in self._plots[figure]['INDEX']):
                self._plots[figure]['INDEX'].remove(idx)
                self._change_fig = True
        print(self._plots)
        # pass
 
    def _cb_figure_data_rx(self):
        pass
 
    # 보여줄 크기에 맞는 인덱스를 찾는다.
    def _find_x_lim(self):
        min_idx = 0
        for idx in range(len(self._time)):
            if(self._time[-1- self._time[-idx-1> self._time_scale):
                min_idx = idx+1
                break
        return min_idx
    
    def pause(self):
        # stop 은 멈추는데
        # start 가 아예 새로 시작함
        # self.ani.event_source.stop()
        self.ani.pause()
 
    def resume(self):
        # start나 resume이랑 다를 바 없이 다 지우고 시작한다.
        # self.ani.event_source.start()
        self.ani.resume()
 
    def close(self):
        self.ani.event_source.stop() # 애니메이션 정지
        # self._timer.stop() # 데이터 업데이트 정지
        # plt.close() # 이거 해봤자 창이 안꺼짐.
        super().close() # 이걸 해야 위젯이 꺼진다.
        
class Tester(QMainWindow):
 
    def __init__(self):
        super().__init__()
        self._widget = None  # No external window yet.
 
        self.cb = list()
        cb = QComboBox(self)
        cb.setGeometry(10909030)
        cb.addItem("Fig.1")
        cb.addItem("Fig.2")
        cb.addItem("Fig.3")
        self.cb.append(cb)
        cb = QComboBox(self)
        cb.setGeometry(110909030)
        cb.addItem("data.1")
        cb.addItem("data.2")
        cb.addItem("data.3")
        cb.addItem("data.4")
        self.cb.append(cb)
 
        self.button = list()
        button = self._get_button('Create', parent=self, geo=[10109030],  callback=self._create_plot)
        self.button.append(button)
        button = self._get_button('Close',  parent=self, geo=[10509030],  callback=self._close_plot)
        self.button.append(button)
        button = self._get_button('Pause',  parent=self, geo=[110109030], callback=self._pause_plot)
        self.button.append(button)
        button = self._get_button('Resume', parent=self, geo=[110509030], callback=self._resume_plot)
        self.button.append(button)
        button = self._get_button('Add',    parent=self, geo=[101309030], callback=self._add_plot)
        self.button.append(button)
        button = self._get_button('Remove', parent=self, geo=[1101309030], callback=self._remove_plot)
        self.button.append(button)
 
        self.label = QLabel("dt :   ms"self)
        self.label.setGeometry(1017012030)
        font = self.label.font()
        font.setPointSize(10)
        self.label.setFont(font)
 
        pub.subscribe(self._cb_dt, 'draw_dt')
        self.dt = 0
 
        self.setGeometry(100,300,210,200)
        self.show()
 
    def _create_plot(self):
        if self._widget is not None:
            if (self._widget.isVisible() == False): # 우측 상단 X으로 끄면 visible이 False가 된다.
                self._close_plot()
            else:
                return
        self._widget = FigureBase() # 아무튼 초기화 했으니 켠다.
        # proc = mp.Process(target=self._widget.animate, )
        # proc.start()
        # proc.join()
 
    def _pause_plot(self):
        if self._widget is not None:
            self._widget.pause()
 
    def _resume_plot(self):
        if self._widget is not None:
            self._widget.resume()
 
    def _close_plot(self):
        if self._widget is not None:
            self._widget.close()
            self._widget.__del__()
            self._widget = None
 
    def _add_plot(self):
        pub.sendMessage("figure_cmd_rx", msgData={"FIGURE":self.cb[0].currentIndex(), "INDEX":self.cb[1].currentIndex(), "COMMAND":"ADD"})
        # print("Add {} to {}".format(self.cb[1].currentText(), self.cb[0].currentText()))
 
    def _remove_plot(self):
        pub.sendMessage("figure_cmd_rx", msgData={"FIGURE":self.cb[0].currentIndex(), "INDEX":self.cb[1].currentIndex(), "COMMAND":"REMOVE"})
        # print("Remove {} to {}".format(self.cb[1].currentText(), self.cb[0].currentText()))
 
    def _get_button(self, name, parent, geo, callback=None):
        button = QPushButton(name, parent)
        button.setGeometry(geo[0],geo[1],geo[2],geo[3])
        if(callback != None): button.clicked.connect(callback)
        return button
 
    def _cb_dt(self, msgData):
        self.dt = msgData
        self.label.setText("dt : {:10.3f} ms".format(self.dt))
        
if __name__ == "__main__":
 
    print('support_blit : ', FigureCanvasBase.supports_blit)
    app = QApplication(sys.argv)
    tester = Tester()
    app.exec()
cs

 

위에 코드는 QWidget을 이용한 코드인데 너무 느리다.

아래는 native Matplotlib와 blit을 이용해서 고속 드로잉을 했다.

대충 1프레임을 그리는데 4ms가 소모된다.

더보기를 누르면 코드를 볼 수 있다.

더보기
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
import sys
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtWidgets import QPushButton, QLabel, QComboBox
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QVBoxLayout
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.backend_bases import FigureCanvasBase
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
 
from pubsub import pub
import numpy as np
 
from stop_watch import StopWatch
 
QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)
 
class FigureMaker():
    def __init__(self):
        self._ys_len = 4
        self._number_of_figure = 3
        self._cfg = list()
        self._cfg.append(list([0,1,2]))
        self._cfg.append(list([0]))
        self._cfg.append(list([1]))
 
        self._idx = 0
 
        self._stop_watch_module = StopWatch()
        self._first_gen = True
        self._do_draw = True
        self._fig = None
        self._bg = None
        
 
        self._init_data()
        self._init_figure()
        self._change_fig = True
        self._init_plot()
        # self._init_plot_data()
        # self._init_background()
        self._update_before_drawing()
        pub.subscribe(self._cb_figure_cmd_rx, "figure_cmd_rx")
 
    def _init_data(self):
        self._time = list()
        self._data = list()
        self._time.append(0)
        for i in range(0,self._ys_len):
            data = {"NAME":"data{}".format(i), "DATA":list()}
            self._data.append(data)
            self._data[i]['DATA'].append(0)
 
    def _init_figure(self):
        fig = plt.figure(num=1)
        axs = list()
        for i in range(self._number_of_figure):
            subplot_num = self._number_of_figure * 100 + i + 11
            ax = fig.add_subplot(subplot_num)
            axs.append(ax)
        # fig, axs = plt.subplots(nrows=self._number_of_figure, ncols=1)
        if(self._first_gen == True):
            fig.set_figwidth(6)
            fig.set_figheight(8)
            self._first_gen = False
        fig.tight_layout()
        self._fig = fig
        self._axs = axs
        self.cid = self._fig.canvas.mpl_connect("draw_event"self.update_draw)
        # self.cid = self._fig.canvas.mpl_connect("resize_event", self.update_draw)
 
    def _init_plot(self):
        self._figures = list()
        for ax_idx, ax in enumerate(self._axs):
            figure = {"AX":ax, "LINE":dict(), "LEGEND":list()}
            for data_idx in self._cfg[ax_idx]:
                figure['LINE'][data_idx] = None
            self._figures.append(figure)
 
    def _init_plot_data(self):
        # Plot Initialization
        for ax_idx in range(len(self._axs)):
            # print('Fig.{} - '.format(ax_idx), figures[ax_idx]['LINE'].keys())
            figure = self._figures[ax_idx]
            figure['LEGEND'= list()
            for data_idx in figure['LINE'].keys():
                (line, ) = figure['AX'].plot(self._time, self._data[data_idx]['DATA'], animated=True)
                figure['LINE'][data_idx] = line
                figure['LEGEND'].append("data.{}".format(data_idx))
            self._fig_config(figure['AX'], figure['LEGEND'])
        plt.show(block=False)
 
    def _init_background(self):
        # Background Image
        self._bg = self._fig.canvas.copy_from_bbox(self._fig.bbox)
        for ax_idx in range(len(self._axs)):
            figure = self._figures[ax_idx]
            for line in figure['LINE'].values():
                figure['AX'].draw_artist(line)
        self._fig.canvas.blit(self._fig.bbox)
 
    def _update_before_drawing(self):
        # Preparing data
        x = 0 
        for j in range(10000):
            x = x + 0.01
            self._time.append(x)
            for i in range(self._ys_len):
                self._data[i]['DATA'].append(float(i+1)*np.sin(x))
                
    def update_draw(self, event):
        """Callback to register with 'draw_event'."""
        cv = self._fig.canvas
        print("Event " , event)
        if event is not None:
            if event.canvas != cv:
                raise RuntimeError
 
        print("Update draw : ", end='')
        if(self._change_fig == True):
            print("Change! ", end='')
            plt.clf()
            # self._change_fig = False
            self._init_figure()
            self._init_plot()
            self._init_plot_data()
            self._init_background()
        print("")
 
        self._bg = cv.copy_from_bbox(cv.figure.bbox)
        self._draw_animated()
 
    def _draw_animated(self):
        j = self._idx
        if(self._do_draw == True):
            self._idx += 10
        # Update figure
        for ax_idx in range(len(self._axs)):
            figure = self._figures[ax_idx]
            ax = figure['AX']
            for data_idx in figure['LINE'].keys():
                line = figure['LINE'][data_idx]
                line.set_xdata(self._time[:j])
                line.set_ydata(self._data[data_idx]['DATA'][:j])
                ax.draw_artist(line)
            ax.set_xlim(self._time[j]-10self._time[j])
            ax.set_ylim(-55)
            ax.set_yticks(np.arange(-55, step=1.0))
 
    def update(self):
        if(self._change_fig == True):
            self.update_draw(None)
            self._fig.canvas.draw_idle()
            self._change_fig = False
 
        # Load background
        cv = self._fig.canvas
        # Drawing
        if self._bg is None:
            self.update_draw(None)
        else:
            # restore the background
            cv.restore_region(self._bg)
            # draw all of the animated
            self._draw_animated()
            # update the GUI state
            cv.blit(self._fig.bbox)
        cv.flush_events()
 
        self._stop_watch_module.click()
        pub.sendMessage("draw_dt",msgData=self._stop_watch_module.get_dt())
 
    def pause(self):
        self._do_draw = False
 
    def resume(self):
        self._do_draw = True
 
    def _refresh_figure(self):
        self._fig.canvas.draw_idle()
 
    def _add_line(self, ax_idx, data_idx):
        print("Add data{} at Fig.{}".format(data_idx, ax_idx))
        # (line, ) = self._figures[ax_idx]['AX'].plot(self._time, self._data[data_idx]['DATA'], animated=True)
        # self._figures[ax_idx]['LINE'][data_idx] = line
 
    def _remove_line(self, ax_idx, data_idx):
        print("Remove data{} at Fig.{}".format(data_idx, ax_idx))
        # del self._figures[ax_idx]['LINE'][data_idx]
        
    def _fig_config(self, ax, legends):
        j = self._idx
        ax.set_xlim(010)
        ax.set_ylim(-5,5)
        ax.grid(True)
        ax.legend(legends,loc='upper right')
        
    def _cb_figure_cmd_rx(self, msgData):
        # print(msgData)
        figure  = msgData['FIGURE']
        idx     = msgData['INDEX']
        cmd     = msgData['COMMAND']
        ax_item = self._figures[figure]
        if(cmd == 'ADD'):
            if(idx not in self._cfg[figure]):
                print("Add "self._cfg[figure], "<- {}".format(idx))
                self._cfg[figure].append(idx)
                self._change_fig = True
        else# REMOVE
            if(idx in self._cfg[figure]):
                print("remove "self._cfg[figure], "<- {}".format(idx))
                self._cfg[figure].remove(idx)
                self._change_fig = True
        print(self._figures)
 
class Tester(QMainWindow):
 
    def __init__(self):
        super().__init__()
        self._widget = None  # No external window yet.
 
        self.cb = list()
        cb = QComboBox(self)
        cb.setGeometry(10909030)
        cb.addItem("Fig.1")
        cb.addItem("Fig.2")
        cb.addItem("Fig.3")
        self.cb.append(cb)
        cb = QComboBox(self)
        cb.setGeometry(110909030)
        cb.addItem("data.1")
        cb.addItem("data.2")
        cb.addItem("data.3")
        cb.addItem("data.4")
        self.cb.append(cb)
 
        self.button = list()
        button = self._get_button('Create', parent=self, geo=[10109030],  callback=self._create_plot)
        self.button.append(button)
        button = self._get_button('Close',  parent=self, geo=[10509030],  callback=self._close_plot)
        self.button.append(button)
        button = self._get_button('Pause',  parent=self, geo=[110109030], callback=self._pause_plot)
        self.button.append(button)
        button = self._get_button('Resume', parent=self, geo=[110509030], callback=self._resume_plot)
        self.button.append(button)
        button = self._get_button('Add',    parent=self, geo=[101309030], callback=self._add_plot)
        self.button.append(button)
        button = self._get_button('Remove', parent=self, geo=[1101309030], callback=self._remove_plot)
        self.button.append(button)
        button = self._get_button('Update', parent=self, geo=[1101709030], callback=self._refresh_plot)
        self.button.append(button)
 
        self.label = QLabel("dt :   ms"self)
        self.label.setGeometry(1017012030)
        font = self.label.font()
        font.setPointSize(10)
        self.label.setFont(font)
 
        pub.subscribe(self._cb_dt, 'draw_dt')
        self.dt = 0
 
        self.setGeometry(100,300,210,200)
        self.show()
 
        self._create_plot()
 
    def _create_plot(self):
        if self._widget is not None:
            if (self._widget.isVisible() == False): # 우측 상단 X으로 끄면 visible이 False가 된다.
                self._close_plot()
            else:
                return
        self._widget = FigureMaker() # 아무튼 초기화 했으니 켠다.
        
        self.timer_freq = 20
        self._timer = QTimer(self)
        self._timer.start()
        self._timer.setInterval(int(1000/self.timer_freq))
        self._timer.timeout.connect(self._widget.update)
        # proc = mp.Process(target=self._widget.animate, )
        # proc.start()
        # proc.join()
 
    def _pause_plot(self):
        print("Pause")
        if self._widget is not None:
            self._widget.pause()
 
    def _resume_plot(self):
        print("resume")
        if self._widget is not None:
            self._widget.resume()
 
    def _close_plot(self):
        if self._widget is not None:
            self._timer.stop()
            del self._widget
            plt.close()
            self._widget = None
 
    def _add_plot(self):
        pub.sendMessage("figure_cmd_rx", msgData={"FIGURE":self.cb[0].currentIndex(), "INDEX":self.cb[1].currentIndex(), "COMMAND":"ADD"})
        # print("Add {} to {}".format(self.cb[1].currentText(), self.cb[0].currentText()))
 
    def _remove_plot(self):
        pub.sendMessage("figure_cmd_rx", msgData={"FIGURE":self.cb[0].currentIndex(), "INDEX":self.cb[1].currentIndex(), "COMMAND":"REMOVE"})
        # print("Remove {} to {}".format(self.cb[1].currentText(), self.cb[0].currentText()))
 
    def _refresh_plot(self):
        if self._widget is not None:
            self._widget._refresh_figure()
 
    def _get_button(self, name, parent, geo, callback=None):
        button = QPushButton(name, parent)
        button.setGeometry(geo[0],geo[1],geo[2],geo[3])
        if(callback != None): button.clicked.connect(callback)
        return button
 
    def _cb_dt(self, msgData):
        self.dt = msgData
        self.label.setText("dt : {:10.3f} ms".format(self.dt))
 
    def closeEvent(self, event):
        self._close_plot()
        self._timer.stop()
        plt.close()
        
if __name__ == "__main__":
 
    app = QApplication(sys.argv)
    tester = Tester()
    app.exec()
cs

 

Figure 구성을 불러오고 저장할 수 있게 해두었다.

하다가 갑자기 한 사이클 당 시간 소모가 급격히 늘어나는 문제가 있었는데,

매번 그릴 때, tight_layout을 해주면 50~100ms 가량 증가하는 것을 확인했다.

그래서 배경을 그릴 때만 실행하도록 해주면 좋다.

더보기를 누르면 코드를 볼 수 있다.

더보기
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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
import sys
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtWidgets import QPushButton, QLabel, QComboBox, QFileDialog, QMessageBox
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QVBoxLayout
 
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.backend_bases import FigureCanvasBase
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
 
from pubsub import pub
import numpy as np
import math
import json
 
from stop_watch import StopWatch
 
QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True)
 
class FigureMaker():
    def __init__(self, number_of_figure = 3):
        self._ys_len = 4
        self._number_of_figure = max(3, number_of_figure)
        self._cfg = list()
        self._cfg.append(list([0,1,2]))
        self._cfg.append(list([0]))
        self._cfg.append(list([1]))
 
        self._idx = 0
 
        self._stop_watch_module = StopWatch()
        self._first_gen = True
        self._do_draw = True
        self._fig = None
        self._bg = None
       
        self._time_scale = 15
        self._change_fig = True
        self._init_data()
        self._init_figure()
        self._init_plot()
        # self._init_plot_data()
        # self._init_background()
        self._update_before_drawing()
        pub.subscribe(self._cb_figure_cmd_rx, "figure_cmd_rx")
 
    def _init_data(self):
        self._time = list()
        self._data = list()
        self._time.append(0)
        for i in range(0,self._ys_len):
            data = {"NAME":"data{}".format(i), "DATA":list()}
            self._data.append(data)
            self._data[i]['DATA'].append(0)
 
    def _init_figure(self):
        fig = plt.figure(num=1)
        axs = list()
        for i in range(self._number_of_figure):
            subplot_num = self._number_of_figure * 100 + i + 11
            ax = fig.add_subplot(subplot_num)
            axs.append(ax)
        # fig, axs = plt.subplots(nrows=self._number_of_figure, ncols=1)
        if(self._first_gen == True):
            fig.set_figwidth(6)
            fig.set_figheight(8)
            self._first_gen = False
        self._fig = fig
        self._axs = axs
        self.cid = self._fig.canvas.mpl_connect("draw_event"self.update_draw)
        self.cid = self._fig.canvas.mpl_connect("resize_event"self.update_draw)
 
    def _init_plot(self):
        self._figures = list()
        for ax_idx, ax in enumerate(self._axs):
            figure = {"AX":ax, "LINE":dict(), "LEGEND":list()}
            for data_idx in self._cfg[ax_idx]:
                figure['LINE'][data_idx] = None
            self._figures.append(figure)
 
    def _init_plot_data(self):
        # Plot Initialization
        for ax_idx in range(len(self._axs)):
            # print('Fig.{} - '.format(ax_idx), figures[ax_idx]['LINE'].keys())
            figure = self._figures[ax_idx]
            figure['LEGEND'= list()
            for data_idx in figure['LINE'].keys():
                (line, ) = figure['AX'].plot(self._time, self._data[data_idx]['DATA'], animated=True)
                figure['LINE'][data_idx] = line
                figure['LEGEND'].append("data.{}".format(data_idx))
            self._fig_config(figure['AX'], figure['LEGEND'])
        plt.show(block=False)
 
    def _init_background(self):
        # Background Image
        self._bg = self._fig.canvas.copy_from_bbox(self._fig.bbox)
        for ax_idx in range(len(self._axs)):
            figure = self._figures[ax_idx]
            for line in figure['LINE'].values():
                figure['AX'].draw_artist(line)
        self._fig.canvas.blit(self._fig.bbox)
 
    def _update_before_drawing(self):
        # Preparing data
        x = 0
        for j in range(10000):
            x = x + 0.01
            self._time.append(x)
            for i in range(self._ys_len):
                self._data[i]['DATA'].append(float(i+1)*np.sin(x))
               
    def update_draw(self, event):
        """Callback to register with 'draw_event'."""
        cv = self._fig.canvas
        # print("Event " , event)
        if event is not None:
            if event.canvas != cv:
                raise RuntimeError
 
        # print("Update draw : ", end='')
        if(self._change_fig == True):
            # print("Change! ", end='')
            plt.clf()
            self._init_figure()
            self._init_plot()
            self._init_plot_data()
            self._init_background()
        # print("")
 
        self._bg = cv.copy_from_bbox(cv.figure.bbox)
        self._draw_animated()
 
    def _draw_animated(self):
        j = self._idx
        if(self._do_draw == True):
            self._idx += 10
        # Update figure
        for ax_idx in range(len(self._axs)):
            figure = self._figures[ax_idx]
            ax = figure['AX']
            for data_idx in figure['LINE'].keys():
                line = figure['LINE'][data_idx]
                line.set_xdata(self._time[:j])
                line.set_ydata(self._data[data_idx]['DATA'][:j])
                ax.draw_artist(line)
            x_min = (self._time[j]-self._time_scale)
            x_max = (self._time[j])
            ax.set_xlim(x_min, x_max)
            ax.set_ylim(-55)
            # ax.set_xticks(np.arange(x_min, x_max, step=1.0))
            # ax.set_yticks(np.arange(-5, 5, step=1.0))
        self._figures[-1]['AX'].set_xlabel('Time [sec]')
 
    def update(self):
        if(self._change_fig == True):
            self.update_draw(None)
            self._fig.canvas.draw_idle()
            self._change_fig = False
            self._fig.tight_layout() # It costs lot of time (almost 0~50ms, totally 4~200ms)
 
        # Load background
        cv = self._fig.canvas
        # Drawing
        if self._bg is None:
            self.update_draw(None)
        else:
            # restore the background
            cv.restore_region(self._bg)
            # draw all of the animated
            self._draw_animated()
            # update the GUI state
            cv.blit(self._fig.bbox)
        cv.flush_events()
 
        self._stop_watch_module.click()
        pub.sendMessage("draw_dt",msgData=self._stop_watch_module.get_dt())
 
    def pause(self):
        self._do_draw = False
 
    def resume(self):
        self._do_draw = True
 
    def _refresh_figure(self):
        self._fig.canvas.draw_idle()
 
    def _add_line(self, ax_idx, data_idx):
        print("Add data{} at Fig.{}".format(data_idx, ax_idx))
        # (line, ) = self._figures[ax_idx]['AX'].plot(self._time, self._data[data_idx]['DATA'], animated=True)
        # self._figures[ax_idx]['LINE'][data_idx] = line
 
    def _remove_line(self, ax_idx, data_idx):
        print("Remove data{} at Fig.{}".format(data_idx, ax_idx))
        # del self._figures[ax_idx]['LINE'][data_idx]
       
    def _fig_config(self, ax, legends):
        j = self._idx
        ax.set_xlim(010)
        ax.set_ylim(-5,5)
        ax.grid(True)
        ax.legend(legends,loc='upper right')
       
    def _cb_figure_cmd_rx(self, msgData):
        # print(msgData)
        figure  = msgData['FIGURE']
        idx     = msgData['INDEX']
        cmd     = msgData['COMMAND']
        ax_item = self._figures[figure]
        if(cmd == 'ADD'):
            if(idx not in self._cfg[figure]):
                print("Add "self._cfg[figure], "<- {}".format(idx))
                self._cfg[figure].append(idx)
                self._change_fig = True
        else# REMOVE
            if(idx in self._cfg[figure]):
                print("remove "self._cfg[figure], "<- {}".format(idx))
                self._cfg[figure].remove(idx)
                self._change_fig = True
        print(self._figures)
 
 
    def get_visible(self):
        print('figure visible 'self._fig.get_visible())
        return self._fig.get_visible()
   
    def add_figure(self):
        self._number_of_figure = max(self._number_of_figure + 11)
        self._cfg.append([0])
        self._change_fig = True
        print("figures : {}".format(self._number_of_figure))
 
    def remove_figure(self):
        self._number_of_figure = max(self._number_of_figure - 11)
        del self._cfg[-1]
        self._change_fig = True
        print("figures : {}".format(self._number_of_figure))
 
    def set_time_scale(self, time_scale):
        self._time_scale = max(10.0, time_scale)
 
    def load_setting(self, number_of_figure, cfg):
        self._cfg = cfg
        self._number_of_figure = number_of_figure
        self._change_fig = True
 
    def save_setting(self):
        return self._number_of_figure, self._cfg
    
 
class Tester(QMainWindow):
 
    def __init__(self):
        super().__init__()
        self._widget = None  # No external window yet.
 
        self.cb = list()
        cb = QComboBox(self)
        cb.setGeometry(10909030)
        cb.addItem("Fig.1")
        cb.addItem("Fig.2")
        cb.addItem("Fig.3")
        self.cb.append(cb)
 
 
        cb = QComboBox(self)
        cb.setGeometry(110909030)
        cb.addItem("data.1")
        cb.addItem("data.2")
        cb.addItem("data.3")
        cb.addItem("data.4")
        self.cb.append(cb)
 
        self.button = list()
        self._button_create     = self._get_button('Create',        parent=self, geo=[10109030],   callback=self._create_plot)
        self._button_close      = self._get_button('Close',         parent=self, geo=[10509030],   callback=self._close_plot)
 
        self._button_pause      = self._get_button('Pause',         parent=self, geo=[110109030],  callback=self._pause_plot)
        self._button_resume     = self._get_button('Resume',        parent=self, geo=[110509030],  callback=self._resume_plot)
 
        self._button_add_line   = self._get_button('Add',           parent=self, geo=[1101309030],  callback=self._add_plot)
        self._button_remove_line= self._get_button('Remove',        parent=self, geo=[1101709030],  callback=self._remove_plot)
 
        self._button_add_fig    = self._get_button('Add Fig',       parent=self, geo=[101309030], callback=self._add_figure)
        self._button_remove_fig = self._get_button('Remove Fig',    parent=self, geo=[101709030], callback=self._remove_figure)
 
        self._button_load_cfg   = self._get_button('Load cfg',      parent=self, geo=102109030], callback=self._load_config)
        self._button_save_cfg   = self._get_button('Save cfg',      parent=self, geo=[1102109030], callback=self._save_config)
 
        self._button_update     = self._get_button('Update',        parent=self, geo=[1102509030], callback=self._refresh_plot)
 
        self.label = QLabel("dt :   ms"self)
        self.label.setGeometry(102509030)
        font = self.label.font()
        font.setPointSize(10)
        self.label.setFont(font)
 
        pub.subscribe(self._cb_dt, 'draw_dt')
        self.dt = 0
 
        self.setGeometry(100,300,210,290)
        self.show()
 
        self._create_plot()
 
    def _exist_widget(func):
        def wrapper(self):
            if self._widget is not None:
                return func(self)
            else:
                QMessageBox.warning(self"Warning""Figure didn\'t exist.")
        return wrapper
 
    def _create_plot(self):
        if self._widget is not None:
            # if (self._widget.get_visible() == False): # 우측 상단 X으로 끄면 visible이 False가 된다.
            self._close_plot()
            # else:
            #     return
        self._widget = FigureMaker() # 아무튼 초기화 했으니 켠다.
       
        self.timer_freq = 20
        self._timer = QTimer(self)
        self._timer.start()
        self._timer.setInterval(int(1000/self.timer_freq))
        self._timer.timeout.connect(self._widget.update)
        # proc = mp.Process(target=self._widget.animate, )
        # proc.start()
        # proc.join()
 
    @_exist_widget
    def _pause_plot(self):
        print("Pause")
        self._widget.pause()
 
    @_exist_widget
    def _resume_plot(self):
        print("resume")
        self._widget.resume()
 
    def _close_plot(self):
        self._timer.stop()
        if self._widget is not None:
            del self._widget
        plt.close()
        self._widget = None
 
    @_exist_widget
    def _add_plot(self):
        pub.sendMessage("figure_cmd_rx", msgData={"FIGURE":self.cb[0].currentIndex(), "INDEX":self.cb[1].currentIndex(), "COMMAND":"ADD"})
        # print("Add {} to {}".format(self.cb[1].currentText(), self.cb[0].currentText()))
 
    @_exist_widget
    def _remove_plot(self):
        pub.sendMessage("figure_cmd_rx", msgData={"FIGURE":self.cb[0].currentIndex(), "INDEX":self.cb[1].currentIndex(), "COMMAND":"REMOVE"})
        # print("Remove {} to {}".format(self.cb[1].currentText(), self.cb[0].currentText()))
 
    @_exist_widget
    def _refresh_plot(self):
        self._widget._refresh_figure()
 
    @_exist_widget
    def _add_figure(self):
            self._widget.add_figure()
            length = self.cb[0].count()
            self.cb[0].addItem("Fig.{}".format(length+1))
 
    @_exist_widget
    def _remove_figure(self):
        self._widget.remove_figure()
        length = self.cb[0].count()
        self.cb[0].removeItem(length)
    
    @_exist_widget
    def _load_config(self):
        file_name = QFileDialog.getOpenFileName(self'Open file''./''json file (*.json)')
 
        print(file_name)
 
        if file_name[0]:
            with open(file_name[0], 'r'as f:
                configs = json.load(f)
                self._widget.load_setting(configs['FIGURES'], configs['cfg'])
                import pprint
                pprint.pprint(configs)
 
    @_exist_widget
    def _save_config(self):
        file_name = QFileDialog.getSaveFileName(self'Save file''./''json file (*.json)')
 
        print(file_name)
 
        figures, cfg = self._widget.save_setting()
        configs = dict()
        configs['FIGURES'= figures
        configs['cfg'= cfg
        if (file_name[0!= ""):
            with open(file_name[0], 'w'as f:
                json.dump(configs, f, ensure_ascii=False, indent=4)
 
    def _get_button(self, name, parent, geo, callback=None):
        button = QPushButton(name, parent)
        button.setGeometry(geo[0],geo[1],geo[2],geo[3])
        if(callback != None): button.clicked.connect(callback)
        return button
 
    def _cb_dt(self, msgData):
        self.dt = msgData
        self.label.setText("dt : {:10.3f} ms".format(self.dt))
 
    def closeEvent(self, event):
        self._close_plot()
        self._timer.stop()
        plt.close()
       
if __name__ == "__main__":
 
    app = QApplication(sys.argv)
    tester = Tester()
    app.exec()
cs

 

위 코드의 결과물은 다음과 같다.

그리기를 20Hz으로 수행하도록 타이머를 걸어두었는데,

50ms 보다 조금 더 큰 54~75 ms를 소모한다.

그리는데 매우 짧은 시간을 소비하는 것이다.

 

 

EOF

728x90

+ Recent posts