1
votes

I'm currently writing a python script with pyserial and pyqtgraph that plots data coming in from an accelerometer via the serial port. I append this data to an int array and use it to update the plot. At the moment, my graph width is 500 (I'm only displaying the most recent 500 elements) and I "roll" or "scroll" by appending an element to the end and popping from the start.

data1 = [0] * 500

def update():
  global curve1, data1, x, ser
  if(ser != None): ## serial object. defined via a QPushButton event
    line = ser.readline()
    csv = line.decode().split(',')
    if len(csv) == 2:       
      data1.append(int(csv[1]))
      data1.pop(0)
      xdata1 = np.array(data1[-500:], dtype='int')
      curve1.setData(xdata1)
      x += 1
      curve1.setPos(x, 0)
      app.processEvents()

This update method is called by the QtTimer object to update the plot window

timer = QtCore.QTimer()
timer.timeout.connect(update)
timer.start(0)

This way I avoid an array that keeps growing and also avoid copying values by shifting the elements left. My plot however is inconsistent and occasionally lags (When I move the sensor, the plot reacts seconds later). Is this due to me rolling my data inefficiently?

2

2 Answers

4
votes

To have a O(1) update procedure, you can do it yourself with a double array buffer :

size=4
buffersize=2*size
buffer=np.zeros(buffersize+1,int) # one more room  for keep trace on beginning of buffer.
sensor=iter(range(1,10**5)) # emulation

def update():
    i=buffer[buffersize] # to avoid global variable i
    buffer[i]=buffer[i+size]=next(sensor) # double copy.
    buffer[buffersize]=i=(i+1)%size
    print(i,buffer[:buffersize],buffer[i:i+size])
    # In real life : curve1.SetData(buffer[i:i+size])

Since buffer[i:i+size] is just a view, it will take no time to update curve1.

Run :

>>> for k in range(6): update()

1 [1 0 0 0 1 0 0 0] [0 0 0 1]
2 [1 2 0 0 1 2 0 0] [0 0 1 2]
3 [1 2 3 0 1 2 3 0] [0 1 2 3]
0 [1 2 3 4 1 2 3 4] [1 2 3 4]
1 [5 2 3 4 5 2 3 4] [2 3 4 5]
2 [5 6 3 4 5 6 3 4] [3 4 5 6]
....
1
votes

Here's a good reference for this kind of FIFO functionality: Queues in Python

To summarise from that link:

Consider using collections.deque for this behaviour, as lists are slow.