0

I am trying to update plot with new data points. But the problem i am having is it is slow. I am using draw_now may be that is the problem as per this stack question: why is plotting with Matplotlib so slow?

I tried that approaches mentioned in that question and i still have same problems.

I recieve data from accelerometer and i take that data to update my plots.

from pyqtgraph.Qt import QtCore, QtGui
import threading
import pyqtgraph as pg 
import socket
import psutil
import time 
import struct 
import sys 
import collections 
import os
import PySimpleGUI as sg
import easygui 
import matplotlib.pyplot as plt 
from mpl_toolkits 
import mplot3d


BufferLength = 500 marker_size = 14

driver_name = 'sss.exe'


def get_pid_and_kill(process_name):
    for proc in psutil.process_iter():
        if proc.name() == process_name:
            p = psutil.Process(proc.pid)
            p.terminate()
            print("Process " + process_name + " terminated") def run_the_driver(driver_exe_name):
    from subprocess import Popen
    get_pid_and_kill(driver_exe_name.split("/")[-1])
    get_pid_and_kill(driver_exe_name.split("\\")[-1])
    get_pid_and_kill("cmd.exe")
    Popen([driver_exe_name])
    time.sleep(3)

def create_tcp_ip_socket():

    HOST = '145.0.0.1'
    PORT = 7060

    try:
        socket_connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        socket_connection.settimeout(3)
        socket_connection.connect((HOST, PORT))
        socket_connection.settimeout(1)
        print("Socket Successfully created")
    except socket.error as err:
        raise SystemExit("Socket creation failed with error %s" % err)


def open_exit_button():
    even_name = 'kill the driver'
    layout = [[sg.Button(even_name, button_color=('white', 'springgreen4'))]]

    window = sg.Window('Configurations', layout)
    while True:  # Event Loop
        event, values = window.read(timeout=10)

        if event == sg.WIN_CLOSED or event == even_name:
            if 0 == visualize_recorded_msg:
                get_pid_and_kill(driver_name.split(("/"))[-1])
                get_pid_and_kill(driver_name.split(("\\"))[-1])
            os._exit(1)
            break

    window.close()


class Visualizer(object):

    def __init__(self):
        self.fig = plt.figure()
        self.ax = self.fig.add_subplot(111, projection="3d")
        self.ax.set_title('3D Points')
        self.ax.set_xlabel('X')
        self.ax.set_ylabel('Y')
        self.ax.set_zlabel('Z')
        self.ax.set_xlim(-2.5, 2.5)
        self.ax.set_ylim(0, 3)
        self.ax.set_zlim(-1.5, 1.5)

        self.app = QtGui.QApplication(sys.argv)

        self.view = pg.GraphicsLayoutWidget()
        self.view.setWindowTitle('')

        self.w1 = self.view.addPlot(row=0, col=0, title='Accelerometer 1')
        self.w1.showGrid(x=True, y=True)
        self.w1.addLegend()
        self.w1.setLabel(axis='bottom', text='Time [s]')
        self.w1.setLabel(axis='left', text='')
        self.w1.curve2 = self.w1.plot(name='')
        self.w1.curve3 = self.w1.plot(name='')

        self.w2 = self.view.addPlot(row=1, col=0, title='')
        self.w2.showGrid(x=True, y=True)
        self.w2.addLegend()
        self.w2.setLabel(axis='bottom', text='Time [s]')
        self.w2.setLabel(axis='left', text='')
        self.w2.curve2 = self.w2.plot(name='')
        self.w2.curve3 = self.w2.plot(name='')

        self.w3 = self.view.addPlot(row=2, col=0, title='Average')
        self.w3.showGrid(x=True, y=True)
        self.w3.setLabel(axis='bottom', text='Time [s]')
        self.w3.setLabel(axis='left', text='')
        self.w3.curve1 = self.w3.plot()

        self.w4 = self.view.addPlot(row=3, col=0, title='result ')
        self.w4.showGrid(x=True, y=True)
        self.w4.setLabel(axis='bottom', text='Time [s]')
        self.w4.setLabel(axis='left', text='')
        self.w4.curve1 = self.w4.plot()

        self.a = collections.deque(maxlen=BufferLength)
        self.b = collections.deque(maxlen=BufferLength)
        self.c = collections.deque(maxlen=BufferLength)
        self.d = collections.deque(maxlen=BufferLength)
        self.e = collections.deque(maxlen=BufferLength)
        self.f = collections.deque(maxlen=BufferLength)
        self.pos_x = collections.deque(maxlen=BufferLength)
        self.pos_y = collections.deque(maxlen=BufferLength)
        self.pos_z = collections.deque(maxlen=BufferLength)
        self.pos_x_out = collections.deque(maxlen=BufferLength)
        self.pos_y_out = collections.deque(maxlen=BufferLength)
        self.pos_z_out = collections.deque(maxlen=BufferLength)

        self.view.show()
        self.fig.show()
        self.fig.canvas.draw()

        self.prevFrameCnt = 0
        self.iteration_index = 0
        self.li_det = 0
        self.str_mot = 1

    @staticmethod
    def start():
        if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
            QtGui.QApplication.instance().exec_()

    def message_parser(self, data):
        out1 = struct.unpack("<L", data[0:4])[0]
        out2 = data[4]
        out3 = data[5]
        out4 = data[6]
        out5 = struct.unpack("<h", data[7:9])[0]
        out6 = struct.unpack("<H", data[9:11])[0]
        out7 = struct.unpack("<H", data[11:13])[0]
        out8 = struct.unpack("<H", data[17:19])[0]
        out9 = struct.unpack("<H", data[19:21])[0]
        out10 = struct.unpack("<H", data[19:21])[0]
        out11 = struct.unpack("<H", data[21:23])[0]
        out12 = struct.unpack("<H", data[23:25])[0]

        return [out1, out2, out3, out4, out5, out6, out7, out8, out9,out10, out11, out12]

    def update(self):
        try:
            data = socket_connection.recv(64)
        except socket.timeout as e:
            print(e)
        except (ConnectionResetError, OSError):
            raise SystemExit("server closed")

        output = self.message_parser(data)

        x = output[0]
        y = output[4]
        z = output[5]
        x1 = output[6]
        y1 = output[7]
        z1 = output[8]

        if self.prevFrameCnt == x:
            MovDet = output[1]
            LiDet = output[2]
            MotDet = output[3]

            self.a.append(y)
            self.c.append(z1)
            self.d.append(y1)

            self.w2.curve2.setData(self.c, pen=None, symbol='t', symbolPen=None, symbolSize=marker_size,
                                   symbolBrush=(0, 114, 189))
            self.w2.curve3.setData(self.d, pen=None, symbol='t1', symbolPen=None, symbolSize=marker_size,
                                   symbolBrush=(217, 83, 25))
            self.w3.curve1.setData(self.a, pen=None, symbol='d', symbolPen=None, symbolSize=marker_size,
                                   symbolBrush=('g'))
            self.w4.curve1.setData(self.f, pen=None, symbol='o', symbolPen=None,
                                   symbolSize=marker_size,
                                   symbolBrush=(217, 83, 25))

            if (1 == self.li_det) or (105 == LiDet):
                self.li_det = 1

        else:
            MovDet = output[1]
            LiDet = output[2]
            MotDet = output[3]

            pos_x = output[10]
            pos_y = output[11]
            pos_z = output[12]

            is_in = pos_z 0.5
            is_in = is_in and (pos_z < 0.6)
            is_in = is_in and (pos_x < 0.7)
            is_in = is_in and (pos_x 0.8)
            is_in = is_in and (pos_y 0.7)

            if is_in:
                self.pos_x.append(pos_x)
                self.pos_y.append(pos_x)
                self.pos_z.append(pos_x)
                self.ax.scatter3D(self.pos_x, self.pos_y, self.pos_z, color='green')
                self.fig.canvas.draw_idle() 
            else:
                self.pos_x_out.append(pos_x)
                self.pos_y_out.append(pos_x)
                self.pos_z_out.append(pos_x)
                self.ax.scatter3D(self.pos_x_out, self.pos_y_out, self.pos_z_out, color='green')
                self.fig.canvas.draw_idle()
#

            self.b.append(z1)
            self.d.append(y1)

            self.w1.curve2.setData(self.b, pen=None, symbol='t', symbolPen=None, symbolSize=marker_size,
                                   symbolBrush=(0, 114, 189))
            self.w1.curve3.setData(self.d, pen=None, symbol='t1', symbolPen=None, symbolSize=marker_size,
                                   symbolBrush=(217, 83, 25))
            self.prevFrameCnt = x

        self.view.show()   
          self.fig.show()


    def animation(self):
        timer = QtCore.QTimer()
        timer.timeout.connect(self.update)
        timer.start(1)
        self.start()


def visualization():
    v = Visualizer()
    v.animation()


def main():
    thread = threading.Thread(target=visualization)
    thread.start()
    open_exit_button()


if __name__ == '__main__':
    main()

But problem is if i plot either matplot one or pyqt one it is working fast without any delay in FPS. But when i plot both then plot function is not that quickly updated in pyqt one?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
user12071441
  • 95
  • 1
  • 8

1 Answers1

0

Matplotlib is generally not so ideal for real time plotting based on several answers posted in different questions in stack Why Matplotlib is slow. So it is better to use vispy Vispy for real time plotting.

In my case, plotting with Vispy really solved the problem of updating the plots slow

user12071441
  • 95
  • 1
  • 8