Exemple #1
0
    def plotter(self):
        if self.started == 0:
            self.started = 1
            self.firstTime = time()
            self.lastTime = time()
            self.testTime = time()

            self.data = [0]
            self.curve = self.login_widget.sinal.getPlotItem().plot(pen='y')
            self.curve2 = self.login_widget.entrada.getPlotItem().plot(pen='y')
            self.curvefft = self.login_widget.fft.getPlotItem().plot(pen='r')
            self.curveD = self.login_widget.delta.getPlotItem().plot(pen='g')
            self.curveT = self.login_widget.theta.getPlotItem().plot(
                pen={'color': (139, 0, 139)})
            self.curveA = self.login_widget.alfa.getPlotItem().plot(pen='w')
            self.curveB = self.login_widget.beta.getPlotItem().plot(pen='b')
            self.curveD2 = self.login_widget.delta2.getPlotItem().plot(pen='g')
            self.curveT2 = self.login_widget.theta2.getPlotItem().plot(
                pen={'color': (139, 0, 139)})
            self.curveA2 = self.login_widget.alfa2.getPlotItem().plot(pen='w')
            self.Entrada()

            self.timer = QtCore.QTimer()
            self.timer.timeout.connect(self.updater)
            self.timer.start(0)
        else:
            pass
    def update(self, image):

        peaks = maxima.Maxima(image, self.fwhm, self.kernel)
        peaks.find(float(self.main.alphaEdit.text()))
        nMaxima = len(peaks.positions)
        nOverlaps = peaks.overlaps

        if self.ptr < self.npoints:
            self.dataN[self.ptr] = nMaxima
            self.dataOverlaps[self.ptr] = nOverlaps
            self.time[self.ptr] = ptime.time() - self.startTime
            self.curve1.setData(self.time[1:self.ptr + 1],
                                self.dataN[1:self.ptr + 1])
            self.curve2.setData(self.time[1:self.ptr + 1],
                                self.dataOverlaps[1:self.ptr + 1])

        else:
            self.dataN[:-1] = self.dataN[1:]
            self.dataN[-1] = nMaxima
            self.dataOverlaps[:-1] = self.dataOverlaps[1:]
            self.dataOverlaps[-1] = nOverlaps
            self.time[:-1] = self.time[1:]
            self.time[-1] = ptime.time() - self.startTime

            self.curve1.setData(self.time, self.dataN)
            self.curve2.setData(self.time, self.dataOverlaps)

        self.ptr += 1
Exemple #3
0
    def update(self):
        """ Update the data displayed in the graphs
        """
        self.focusSignal = self.focusWidget.ProcessData.focusSignal

        if self.ptr < self.npoints:
            self.data[self.ptr] = self.focusSignal
            self.time[self.ptr] = ptime.time() - self.startTime
            self.focusCurve.setData(self.time[1:self.ptr + 1],
                                    self.data[1:self.ptr + 1])

        else:
            self.data[:-1] = self.data[1:]
            self.data[-1] = self.focusSignal
            self.time[:-1] = self.time[1:]
            self.time[-1] = ptime.time() - self.startTime

            self.focusCurve.setData(self.time, self.data)

        self.ptr += 1

        if self.main is not None:

            if self.recButton.isChecked():
                self.savedDataSignal.append(self.focusSignal)
                self.savedDataTime.append(self.time[-1])

            if self.recButton.isChecked():
                self.analize()
Exemple #4
0
    def move(self, axis, dist):
        """moves the position along the axis specified a distance dist."""
        self.channelsOpen()
        t = self.moveTime
        N = self.moveSamples
        # read initial position for all channels
        texts = [
            getattr(self, ax + "Label").text() for ax in self.activeChannels
        ]
        initPos = [re.findall(r"[-+]?\d*\.\d+|[-+]?\d+", t)[0] for t in texts]
        initPos = np.array(initPos, dtype=float)[:, np.newaxis]
        fullPos = np.repeat(initPos, N, axis=1)

        # make position ramp for moving axis
        ramp = makeRamp(0, dist, N)
        fullPos[self.activeChannels.index(axis)] += ramp

        factors = np.array(
            [convFactors['x'], convFactors['y'], convFactors['z']])[:,
                                                                    np.newaxis]
        fullSignal = fullPos / factors
        toc = ptime.time()

        for i in range(N):
            self.aotask.write(fullSignal[:, i], auto_start=True)
            time.sleep(t / N)

        print("se mueve en", np.round(ptime.time() - toc, 4), "segs")

        # update position text
        newPos = fullPos[self.activeChannels.index(axis)][-1]
        newText = "{}".format(newPos)
        getattr(self, axis + "Label").setText(newText)

        self.paramChanged()
    def update(self, image):

        peaks = maxima.Maxima(image, self.fwhm, self.kernel)
        peaks.find(float(self.main.alphaEdit.text()))
        nMaxima = len(peaks.positions)
        nOverlaps = peaks.overlaps

        if self.ptr < self.npoints:
            self.dataN[self.ptr] = nMaxima
            self.dataOverlaps[self.ptr] = nOverlaps
            self.time[self.ptr] = ptime.time() - self.startTime
            self.curve1.setData(self.time[1:self.ptr + 1],
                                self.dataN[1:self.ptr + 1])
            self.curve2.setData(self.time[1:self.ptr + 1],
                                self.dataOverlaps[1:self.ptr + 1])

        else:
            self.dataN[:-1] = self.dataN[1:]
            self.dataN[-1] = nMaxima
            self.dataOverlaps[:-1] = self.dataOverlaps[1:]
            self.dataOverlaps[-1] = nOverlaps
            self.time[:-1] = self.time[1:]
            self.time[-1] = ptime.time() - self.startTime

            self.curve1.setData(self.time, self.dataN)
            self.curve2.setData(self.time, self.dataOverlaps)

        self.ptr += 1
Exemple #6
0
    def moveto(self, x, y, z):
        """moves the position along the axis to a specified point."""
        self.channelsOpenStep()  # se mueve de a puntos, no rampas.
        t = self.moveTime
        N = self.moveSamples

        # read initial position for all channels
        texts = [
            getattr(self, ax + "Label").text() for ax in self.activeChannels
        ]
        initPos = [re.findall(r"[-+]?\d*\.\d+|[-+]?\d+", t)[0] for t in texts]

        if float(initPos[0]) != x or float(initPos[1]) != y or float(
                initPos[2]) != z:
            rampx = np.linspace(float(initPos[0]), x, N)
            rampy = np.linspace(float(initPos[1]), y, N)
            rampz = np.linspace(float(initPos[2]), z, N)

            tuc = ptime.time()
            for i in range(N):
                self.aotask.write([
                    rampx[i] / convFactors['x'], rampy[i] / convFactors['y'],
                    rampz[i] / convFactors['z']
                ],
                                  auto_start=True)
                time.sleep(t / N)

            print("se mueve todo en", np.round(ptime.time() - tuc, 4), "segs")

            self.xLabel.setText("{}".format(np.around(float(rampx[-1]), 2)))
            self.yLabel.setText("{}".format(np.around(float(rampy[-1]), 2)))
            self.zLabel.setText("{}".format(np.around(float(rampz[-1]), 2)))
        else:
            print("Ya estoy en esas cordenadas")
Exemple #7
0
    def update(self):
        """ Update the data displayed in the graphs
        """
        self.focusSignal = self.focusWidget.ProcessData.focusSignal

        if self.ptr < self.npoints:
            self.data[self.ptr] = self.focusSignal
            self.time[self.ptr] = ptime.time() - self.startTime
            self.focusCurve.setData(self.time[1:self.ptr + 1],
                                    self.data[1:self.ptr + 1])

        else:
            self.data[:-1] = self.data[1:]
            self.data[-1] = self.focusSignal
            self.time[:-1] = self.time[1:]
            self.time[-1] = ptime.time() - self.startTime

            self.focusCurve.setData(self.time, self.data)

        self.ptr += 1

        if self.main is not None:

            if self.recButton.isChecked():
                self.savedDataSignal.append(self.focusSignal)
                self.savedDataTime.append(self.time[-1])

            if self.recButton.isChecked():
                self.analize()
Exemple #8
0
 def evalKeyState(self):
     # TODO: while loading, arrow keys cause error
     if len(self.keysPressed) == 1:
         key = list(self.keysPressed.keys())[0]
         if key == Qt.Key_Right:
             self.play(20)
             self.jumpFrames(1)
             self.lastPlayTime = ptime.time(
             ) + 0.2  ## 2ms wait before start
             ## This happens *after* jumpFrames, since it might take longer than 2ms
         elif key == Qt.Key_Left:
             self.play(-20)
             self.jumpFrames(-1)
             self.lastPlayTime = ptime.time() + 0.2
         elif key == Qt.Key_Up:
             self.jumpFrames(-self.step)
         elif key == Qt.Key_Down:
             self.jumpFrames(self.step)
         elif key == Qt.Key_PageUp:
             self.play_stop = self.currentIndex - self.step
             self.play(-59)
         elif key == Qt.Key_PageDown:
             self.play_stop = self.currentIndex + self.step
             self.play(59)
     else:
         self.play(0)
Exemple #9
0
    def update(self, delay=0.000):
        
        time0 = time.time()

        time.sleep(delay)
        
        raw_image = self.camera.latest_frame()
        
#        r = raw_image[:, :, 0]
#        g = raw_image[:, :, 1]
#        b = raw_image[:, :, 2]
        
        image = np.sum(raw_image, axis=2)
        
        self.image = image
        
        #  The croppingis done because otherwise the displayed image will be
        #  300 x 1024. It doesn't affect the performance of the system
        
        if self.gui.cropped is False: 
            
            self.gui.img.setImage(self.image, autoLevels=False)
        
        else:

            croppedimg = self.image[0:300, 0:300]
            self.gui.img.setImage(croppedimg, autoLevels=False)
            
        # get mass center
            
        self.massCenter = np.array(ndi.measurements.center_of_mass(image))
        self.focusSignal = self.massCenter[0]
    
        # update of the data displayed in the graph

        if self.ptr < self.npoints:
            self.data[self.ptr] = self.focusSignal
            self.time[self.ptr] = ptime.time() - self.startTime
            
            self.gui.focusCurve.setData(self.time[1:self.ptr + 1],
                                        self.data[1:self.ptr + 1])

        else:
            self.data[:-1] = self.data[1:]
            self.data[-1] = self.focusSignal
            self.time[:-1] = self.time[1:]
            self.time[-1] = ptime.time() - self.startTime

            self.gui.focusCurve.setData(self.time, self.data)

        self.ptr += 1
        
        # update PI
        
        if self.locked:
            self.updatePI()
            self.updateStats()
            
        time1 = time.time()
Exemple #10
0
    def move(self, axis, dist):
        """moves the position along the axis specified a distance dist."""
        self.channelsOpenStep()  # cambiar a movimiento por puntos
        #        t = self.moveTime
        N = self.moveSamples
        # read initial position for all channels
        texts = [
            getattr(self, ax + "Label").text() for ax in self.activeChannels
        ]
        initPos = [re.findall(r"[-+]?\d*\.\d+|[-+]?\d+", t)[0] for t in texts]
        #        initPos = np.array(initPos, dtype=float)[:, np.newaxis]
        #        fullPos = np.repeat(initPos, N, axis=1)

        # make position ramp for moving axis
        #        ramp = np.linspace(0, dist, N)
        #        fullPos[self.activeChannels.index(axis)] += ramp

        #        factors = np.array([convFactors['x'], convFactors['y'],
        #                           convFactors['z']])[:, np.newaxis]
        #        fullSignal = fullPos/factors
        toc = ptime.time()
        rampx = np.linspace(float(initPos[0]), float(initPos[0]), N)
        rampy = np.linspace(float(initPos[1]), float(initPos[1]), N)
        rampz = np.linspace(float(initPos[2]), float(initPos[2]), N)

        if axis == "x":
            rampx = np.linspace(0, dist, N) + float(initPos[0])
        if axis == "y":
            rampy = np.linspace(0, dist, N) + float(initPos[1])
        if axis == "z":
            rampz = np.linspace(0, dist, N) + float(initPos[2])

        for i in range(N):
            self.aotask.write([
                rampx[i] / convFactors['x'], rampy[i] / convFactors['y'],
                rampz[i] / convFactors['z']
            ],
                              auto_start=True)
#            time.sleep(t / N)

        print("se mueve en", np.round(ptime.time() - toc, 4), "segs")

        # update position text
        #        newPos = fullPos[self.activeChannels.index(axis)][-1]
        #        newText = "{}".format(newPos)
        #        getattr(self, axis + "Label").setText(newText)
        self.xLabel.setText("{}".format(np.around(float(rampx[-1]), 2)))
        self.yLabel.setText("{}".format(np.around(float(rampy[-1]), 2)))
        self.zLabel.setText("{}".format(np.around(float(rampz[-1]), 2)))

        self.paramChanged()
        if self.working:
            if self.scanMode.currentText() == "step scan":
                self.channelsOpenStep()

            if self.scanMode.currentText() == "ramp scan" or "otra frec ramp":
                self.channelsOpen()
 def updateSetPointData(self):
     if self.currPoint < self.buffer:
         self.setPointData[self.currPoint] = self.setPointSignal
         self.timeData[self.currPoint] = ptime.time() - self.startTime
     else:
         self.setPointData[:-1] = self.setPointData[1:]
         self.setPointData[-1] = self.setPointSignal
         self.timeData[:-1] = self.timeData[1:]
         self.timeData[-1] = ptime.time() - self.startTime
     self.currPoint += 1
Exemple #12
0
    def linea(self):
        Pasoy = (self.dy * self.pixelSize / convFactors['y'])
        self.citask.stop()
        if self.step == 1:
            APD = np.zeros(self.Napd)
            tic = ptime.time()
            APD = np.zeros((len(self.cuentas), self.Napd))
            for i in range(self.numberofPixels):
                tec = ptime.time()
                self.aotask.write([
                    self.barridox[(i + 1) * (-1)**self.dy],
                    self.barridoy[(i + 1)] + Pasoy, self.barridoz[i]
                ],
                                  auto_start=True)
                tac = ptime.time()
                APD[i] = self.citask.read(
                    number_of_samples_per_channel=self.Napd)
                #                self.ditask.wait_until_done()
                toc = ptime.time()
                #                aux = 0
                #                for c in range(self.Napd-1):
                #                    if APD[c] < APD[c+1]:
                #                        aux = aux + 1
                #                    self.cuentas[i] = aux + np.random.rand(1)[0]
                self.cuentas[i] = APD[i][-1] - APD[i - 1][-1]

        else:  # Para hacerlo de 2 en 2

            tic = ptime.time()
            APD = np.zeros((len(self.cuentas), self.Napd))
            for i in range(2 * self.numberofPixels):
                tec = ptime.time()
                self.aotask.write([
                    self.barridox[i], self.barridoy[i] + Pasoy,
                    self.barridoz[i]
                ],
                                  auto_start=True)
                tac = ptime.time()
                APD[i] = self.citask.read(
                    number_of_samples_per_channel=self.Napd)
                #            self.ditask.wait_until_done()
                toc = ptime.time()
                #                aux = 0
                #                for c in range(self.Napd-1):
                #                    if APD[c] < APD[c+1]:
                #                        aux = aux + 1
                #                    self.cuentas[i] = aux + np.random.rand(1)[0]
                self.cuentas[i] = APD[i][-1] - APD[i - 1][-1]

        print("\n", "ditask posta", np.round(toc - tac, 5), "pixeltime = ",
              self.pixelTime)
        print("data posta", np.round(ptime.time() - tic, 5), "linetime = ",
              self.linetime)
        print(np.round(ptime.time() - tec, 5))
        print(self.Napd, "Napd")  # , len(APD), "APD\n")
    def update_graph(self):

        if self.live:
            try:
                temp = self.liv.decode_frame_analog()
            except OSError:
                print("Error")
                self.stop_stream()
                # self.live_back()

        for j in range(8):
            if self.live:
                r = temp[j] * (5 / 1023)
            else:
                r = self.datacollect[self.i, j + 1] * 10**(-2)

            self.channels[j][self.m].append(r)
            t = np.arange(start=0,
                          stop=0.004 * len(self.channels[j][self.m]),
                          step=0.004)
            self.curve[j][self.m].setData(x=t[0:len(self.channels[j][self.m])],
                                          y=self.channels[j][self.m])
            if len(self.channels[j][self.m]) > self.MAX_DATA_SIZE:
                self.channels[j][self.m] = self.channels[j][
                    self.m][self.WINDOW_SIZE:]
        if self.m == 0:
            self.i += 1
            if self.i == len(self.datacollect):
                self.stop_stream()
                print("end")

        self.counter += 1

        ctime = time() - self.start_time

        if self.fp == 0:
            self.fp = self.counter / ctime
        if ctime > self.x:
            self.fp = self.counter / ctime
            #print(self.counter , ctime)
            self.counter = 0
            self.start_time = time()

        if self.live:
            self.fps.setText('%0.2f fps' % self.fp)
        else:
            self.fps_2.setText('%0.2f fps' % self.fp)
        '''
 def timera(self):
     if self.timer.isActive(): self.timer.stop()
     self.start_time = time()
     self.x = 0.5  # displays the frame rate every 1 second
     self.counter = 0
     self.timer.timeout.connect(self.update_graph)
     self.timer.start(1)
 def __init__(self, num_microbits=3):
     logging.info('started main.py')
     if num_microbits > 3:
         system_exit('max num_microbits is 3')
     mb_thread = threading.Thread(target=ReadMicrobits)
     mb_thread.start()
     self.app = QtGui.QApplication([])
     win = pg.GraphicsWindow()
     win.setWindowTitle('Microbit accelerometer data')
     p0 = win.addPlot()
     win.nextRow()
     p1 = win.addPlot()
     win.nextRow()
     p2 = win.addPlot()
     for plot in [p0, p1, p2]:
         plot.setYRange(0,3000)
     self.text = pg.TextItem('text', anchor=(0,3))
     p2.addItem(self.text)
     self.curve0 = p0.plot()
     self.curve1 = p1.plot()
     self.curve2 = p2.plot()
     self.index = 0
     self.last_time = time()
     self.freq = None
     self.freq_list = np.zeros(FREQ_AVG)
     self.mb_dict = self.create_mb_dict(num_microbits)
     dispatcher.connect(self.dispatcher_receive_data,
         sender='read_microbits', signal='plot_data')
    def __init__(self, *args, **kwargs): #, source, destination, fps, size, gui, serial

        if 'logger' in kwargs:
            self.logger = kwargs['logger']
        if 'app' in kwargs:
            self.app = kwargs['app']

        QtGui.QMainWindow.__init__(self)    
#        mw = QtGui.QMainWindow()
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.resize(800,800)
        self.show()
        
        self.vb = pg.ViewBox()
        self.ui.graphicsView.setCentralItem(self.vb)
        self.vb.setAspectLocked()
        self.img = pg.ImageItem()
        self.vb.addItem(self.img)
        self.vb.setRange(QtCore.QRectF(0, 0, 512, 512))
#        self.img.setPxMode(True)
        
        self.logger.info('%s starting spotter', self)
        self.spotter = Spotter(*args, **kwargs)    
        self.spotter.gui_grabber.displayTarget = self.img
        self.logger.info('%s spotter instantiated', self)

        self.lastTime = ptime.time()
        self.fps = None

        # main window refresh timer
#        self.timer = QtCore.QTimer()
#        self.timer.timeout.connect(self.update)
#        self.timer.start(0)
        self.update()
Exemple #17
0
    def stepLine(self):
        tic = ptime.time()
        APD = np.zeros((self.Napd + 1))

        for i in range(self.numberofPixels):
            #            tec = ptime.time()
            self.citask.stop()
            self.aotask.stop()

            self.aotask.write(
                [
                    self.allstepsx[(i + 1)],  # *(-1)**self.dy
                    self.allstepsy[(i + 1)] +
                    (self.dy * self.pixelSize / convFactors['y']),
                    self.allstepsz[i]
                ],
                auto_start=True)

            self.aotask.wait_until_done()

            #            tac = ptime.time()
            APD[:] = self.citask.read(1 + self.Napd)
            self.citask.wait_until_done()
            #            toc = ptime.time()

            self.citask.stop()
            self.aotask.stop()
            #            self.cuentas[i] = aux + np.random.rand(1)[0]
            self.image[i, self.numberofPixels - 1 -
                       self.dy] = APD[-1] - APD[0]  # *(-1)**self.dy
Exemple #18
0
    def update(self):
        if not self.parent.data_queue.empty():
            reading = [self.parent.data_queue.get()]
            for i in range(0, len(reading)):
                for j in range(self.bytesToIgnore, len(reading[0]), 2):
                    twosComp = reading[i][j] + (reading[i][j + 1] << 8)
                    # convert twos compliment
                    if (twosComp & 0x8000 == 0x8000):
                        count = -1 * ((~twosComp & 0x7FFF) + 1)
                    else:
                        count = twosComp

                    self.dataToPlot[(j - self.bytesToIgnore) / 2].append(
                        float(5 * count / 32768))

            # RIP giant list comprehension
            # [[self.dataToPlot[(j-16)/2].append(float(5*count/32768)) for i in range(0,len(reading))] for j in range(16,len(reading[0]),2)]

            if len(self.dataToPlot[0]) >= self.nSamples:
                self.count += 1
                for i in range(self.nPlots):
                    self.curves[i].setData(self.dataToPlot[i])
                self.ptr += self.nPlots
                now = time()
                self.x = np.linspace(self.lastTime, now, 500)
                dt = now - self.lastTime
                self.lastTime = now
                if self.fps is None:
                    self.fps = 1.0 / dt
                else:
                    s = np.clip(dt * 3., 0, 1)
                    self.fps = self.fps * (1 - s) + (1.0 / dt) * s
                self.parent.ui.daqPlot.setTitle('%0.2f fps' % self.fps)
                self.dataToPlot = [[] for i in range(self.nPlots)]
Exemple #19
0
def update(): # Update preview image (and get image from camera)
    global preview_img_rgb, warped_img_rgb, updateTime, fps, ROI, mousePoint
    select.select((cap,), (), ())
    image_data = cap.read_and_queue()
    frame = cv2.imdecode(np.frombuffer(image_data, dtype=np.uint8), cv2.IMREAD_COLOR)
    frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    frame_rgb = cv2.rotate(frame_rgb, cv2.ROTATE_90_CLOCKWISE)
    ## Display RAW image on Dock 1
    preview_img_rgb.setImage(frame_rgb, levels=(0, frame_rgb.max()))
    
    ## Get ROI position
    ROI_points_raw = ROI.getState()['points']
    ROI_points = []
    for point in ROI_points_raw:
        ROI_points.append([int(point[1]), int(point[0])]) # Convert Qt coordinate system to pixel coordinate system
    ## Transform from Image to World coordinate
    maxWidth, maxHeight = 540, 540
    dst_points = np.array([[0, 0], [maxWidth - 1, 0], [maxWidth - 1, maxHeight - 1], [0, maxHeight - 1]], dtype = "float32")
    HM, status = cv2.findHomography(np.asarray(ROI_points), dst_points) # get HM(Homography Matrix)
    warped_img = cv2.warpPerspective(frame_rgb, HM, (maxWidth, maxHeight))
    ## Display Warped image on Dock 2
    warped_img = cv2.rotate(warped_img, cv2.ROTATE_90_CLOCKWISE)
    warped_img_rgb.setImage(warped_img)
    ## Update label of pixel coordinate of crosshair on Dock 2
    if mousePoint is not None:
        label_pixel.setText("<span style='font-size: 24pt'>Pixel coordinate: <span style='color: red'>x=%0.1f, y=%0.1f</span></span>" % (mousePoint.x(), mousePoint.y()))
        label_image.setText("<span style='font-size: 24pt'>Image coordinate: <span style='color: green'>x=%0.1f, y=%0.1f</span></span>" % ((mousePoint.x()-540/2)/540*workspace_Xmax, (mousePoint.y()-540/2)/540*workspace_Ymax))

    
    
    QtCore.QTimer.singleShot(1, update) # Update UI
    now = ptime.time()
    fps2 = 1.0 / (now-updateTime)
    updateTime = now
    fps = fps * 0.9 + fps2 * 0.1
Exemple #20
0
def update():
	global curve, data, ptr, p, lastTime, fps, lr
	p.clear()
	p_imu2.clear()
	socks = dict(poller.poll(0))
	if m_sockets[0] in socks and socks[m_sockets[0]]==zmq.POLLIN:
		data['imu1'] = data['imu1'].append(get_data_imu(m_sockets[0]))
	if m_sockets[1] in socks and socks[m_sockets[1]]==zmq.POLLIN:
		data['imu2'] = data['imu2'].append(get_data_imu(m_sockets[1]))
	if m_sockets[2] in socks and socks[m_sockets[2]]==zmq.POLLIN:
		data['pressure'] = data['pressure'].append(get_data_pressure(m_sockets[2]))

	curve = pg.PlotCurveItem(data['imu1']['az'].as_matrix(),pen="r")
	curve_imu2 = pg.PlotCurveItem(data['imu2']['az'].as_matrix(),pen="r")
	p.addItem(curve)
	p_imu2.addItem(curve_imu2)
	p.addItem(lr)
	p_imu2.addItem(lr2)
	ptr += 1
	now = time()
	dt = now - lastTime
	lastTime = now
	if fps is None:
		fps = 1.0/dt
	else:
		s = np.clip(dt*3., 0, 1)
		fps = fps * (1-s) + (1.0/dt) * s
		p.setTitle('%0.2f fps' % fps)
Exemple #21
0
 def updateData(self):
     #self.envEnergy()
     self.Producer()
     self.Consumer()
     self.Decomposer()
     #self.envEnergy()
     self.envEnergy(
     )  # add more envEnergy() to diffuse the energy the dead life left
     self.mergeData()
     self.updatePopulation()
     #img.setImage(self.envdata1)
     ##tft
     for i in self.mixenv:
         for j in i:
             if j[3] > 255:
                 print('orz: ', j)
                 print('PRODBIT: ', PRODBIT)
     #print(self.mixenv) ##tft
     img.setImage(self.mixenv)
     #for testing the speed of the program
     global updatect
     updatect += 1
     if updatect > 100:
         now = ptime.time()
         print('Run time: ', now - updatetime)
         app.timer.stop()
Exemple #22
0
def update():
    global p,img, cnt, chart, chartSize, updateTime, fps, logdata, fptr, buf,darks, flatField, seq_count,plot1,plot2
    Tacq = p.param('Tacq').value()
    x = buf.coincidences(Tacq, CoincidenceWindow)
    y = buf.singles(Tacq)
    cnt += 1 
    print "Herald Singles: ", y[0]
    print "Signal Singles: ", y[1]
    print "Coincidences: ", x[0,1]
    efficiency_herald = x[0,1]/float(y[1])
    efficiency_signal = x[0,1]/float(y[0])
    efficiency_sum = x[0,1]/(0.5*(y[0] + y[1]))
    efficiency_geo = x[0,1]/((y[0]*y[1])**0.5)
    print "Efficiency_herald: ", efficiency_herald
    print "Efficiency_signal: ", efficiency_signal
    print "Efficiency_sum: ", efficiency_sum
    print "Efficiency_geo: ", efficiency_geo
    print "\n"
    image = np.zeros(64)
    image = np.reshape(x[0:8,8::],(1,64))
    if p.param('Use Darkfield').value():
      imageCorrected = image-darks[8,:]
    else:
      imageCorrected = image
    if p.param('Use Flatfield').value():
      imageCorrected = imageCorrected/flatField
    
    displayimage = np.reshape(imageCorrected,(8,8))[::-1,:].T # This works

    level=(p.param('min').value(), p.param('max').value() )
    img.setImage(displayimage,autoLevels=False,levels=level)
    now = ptime.time()
    fps2 = 1.0 / (now-updateTime)
    updateTime = now
    fps = fps * 0.9 + fps2 * 0.1
    if p.param('Plot row').value()>0:
      row = p.param('Plot row').value()-1
      idx = np.arange(8) + row*8
#      curve1.setData(image[0,idx])
      curve1.setData(getChart(x,y,cnt)[0,:])
#      curve1.setData(np.log10(imageCorrected[0,idx]))
    if p.param('Plot col').value()>0:
      col = p.param('Plot col').value()-1
      idx = np.arange(8)*8 + col 
      curve2.setData(getChart(x,y,cnt)[1,:])
#      curve2.setData(image[0,idx])
    #print logdata
    if logdata==True:
      print 'logging data'
      fptr.write('%f '%Tacq) 
      image.tofile(fptr,sep=' ')
      fptr.write('\n')
      fptr.flush() 
    #print "%0.1f fps" % fps

    if p.param('Save Sequence').value():
      print "saving image"
      fname = sequencepath + '/' + basename + '%05d.png'%seq_count
      img.save(fname) 
      seq_count = seq_count + 1
Exemple #23
0
 def setValue(self, value):
     now = time()
     self.values.append((now, value))
     cutoff = now - self.averageTime
     while len(self.values) > 0 and self.values[0][0] < cutoff:
         self.values.pop(0)
     self.update()
Exemple #24
0
 def update_monitor(self, timestamp_start, timestamp_stop, readout_error, scan_parameters, n_hits, n_events):
     self.timestamp_label.setText("Data Timestamp\n%s" % time.asctime(time.localtime(timestamp_stop)))
     self.scan_parameter_label.setText(
         "Scan Parameters\n%s"
         % ", ".join("%s: %s" % (str(key), str(val)) for key, val in scan_parameters.iteritems())
     )
     now = ptime.time()
     recent_total_hits = n_hits
     recent_total_events = n_events
     self.plot_delay = self.plot_delay * 0.9 + (now - timestamp_stop) * 0.1
     self.plot_delay_label.setText(
         "Plot Delay\n%s"
         % (
             (time.strftime("%H:%M:%S", time.gmtime(self.plot_delay)))
             if abs(self.plot_delay) > 5
             else "%1.2f ms" % (self.plot_delay * 1.0e3)
         )
     )
     recent_fps = 1.0 / (now - self.updateTime)  # calculate FPS
     recent_hps = (recent_total_hits - self.total_hits) / (now - self.updateTime)
     recent_eps = (recent_total_events - self.total_events) / (now - self.updateTime)
     self.updateTime = now
     self.total_hits = recent_total_hits
     self.total_events = recent_total_events
     self.fps = self.fps * 0.7 + recent_fps * 0.3
     self.hps = self.hps + (recent_hps - self.hps) * 0.3 / self.fps
     self.eps = self.eps + (recent_eps - self.eps) * 0.3 / self.fps
     self.update_rate(self.fps, self.hps, recent_total_hits, self.eps, recent_total_events)
 def getTime(self):
     if self.main.enabled:
         self.ptr = 0
         self.dataN = np.zeros(self.npoints, dtype=np.int)
         self.dataOverlaps = np.zeros(self.npoints, dtype=np.int)
         self.time = np.zeros(self.npoints)
         self.startTime = ptime.time()
Exemple #26
0
    def reset(self):

        self.xData = np.zeros(self.npoints)
        self.yData = np.zeros(self.npoints)
        self.time = np.zeros(self.npoints)
        self.ptr = 0
        self.startTime = ptime.time()
 def handle_data(self, data):
     def update_rate(fps, hps, recent_total_hits, eps, recent_total_events):
         self.rate_label.setText("Readout Rate\n%d Hz" % fps)
         if self.spin_box.value() == 0:  # show number of hits, all hits are integrated
             self.hit_rate_label.setText("Total Hits\n%d" % int(recent_total_hits))
         else:
             self.hit_rate_label.setText("Hit Rate\n%d Hz" % int(hps))
         if self.spin_box.value() == 0:  # show number of events
             self.event_rate_label.setText("Total Events\n%d" % int(recent_total_events))
         else:
             self.event_rate_label.setText("Event Rate\n%d Hz" % int(eps))
     if 'meta_data' not in data:
         self.occupancy_img.setImage(data['occupancy'][:, :, 0], autoDownsample=True)
         self.tot_plot.setData(x=np.linspace(-0.5, 15.5, 17), y=data['tot_hist'], fillLevel=0, brush=(0, 0, 255, 150))
         self.tdc_plot.setData(x=np.linspace(-0.5, 4096.5, 4097), y=data['tdc_counters'], fillLevel=0, brush=(0, 0, 255, 150))
         self.event_status_plot.setData(x=np.linspace(-0.5, 15.5, 17), y=data['error_counters'], stepMode=True, fillLevel=0, brush=(0, 0, 255, 150))
         self.service_record_plot.setData(x=np.linspace(-0.5, 31.5, 33), y=data['service_records_counters'], stepMode=True, fillLevel=0, brush=(0, 0, 255, 150))
         self.trigger_status_plot.setData(x=np.linspace(-0.5, 7.5, 9), y=data['trigger_error_counters'], stepMode=True, fillLevel=0, brush=(0, 0, 255, 150))
         self.hit_timing_plot.setData(x=np.linspace(-0.5, 15.5, 17), y=data['rel_bcid_hist'][:16], stepMode=True, fillLevel=0, brush=(0, 0, 255, 150))
     else:
         update_rate(data['meta_data']['fps'], data['meta_data']['hps'], data['meta_data']['total_hits'], data['meta_data']['eps'], data['meta_data']['total_events'])
         self.timestamp_label.setText("Data Timestamp\n%s" % time.asctime(time.localtime(data['meta_data']['timestamp_stop'])))
         self.scan_parameter_label.setText("Scan Parameters\n%s" % ', '.join('%s: %s' % (str(key), str(val)) for key, val in data['meta_data']['scan_parameters'].iteritems()))
         now = ptime.time()
         self.plot_delay = self.plot_delay * 0.9 + (now - data['meta_data']['timestamp_stop']) * 0.1
         self.plot_delay_label.setText("Plot Delay\n%s" % 'not realtime' if abs(self.plot_delay) > 5 else "%1.2f ms" % (self.plot_delay * 1.e3))
Exemple #28
0
 def updateData(self):
     #self.envEnergy()
     self.Producer()
     self.Consumer()
     self.Decomposer()
     #self.envEnergy()
     self.envEnergy() # add more envEnergy() to diffuse the energy the dead life left
     self.mergeData()
     self.updatePopulation()
     #img.setImage(self.envdata1)
     ##tft
     for i in self.mixenv:
         for j in i:
             if j[3] > 255:
                 print('orz: ', j)
                 print('PRODBIT: ',PRODBIT)
     #print(self.mixenv) ##tft
     img.setImage(self.mixenv)
     #for testing the speed of the program
     global updatect
     updatect += 1
     if updatect > 100:
         now = ptime.time()
         print('Run time: ', now - updatetime)
         app.timer.stop()
def updateData():
    #global img, data, i, updateTime
    global img, arr_data, i, updateTime

    all_1 = arr_data.all()[1]
    all_2 = arr_data.all()[2]
    flex_slice_2d = arr_data[i:i + 1, 0:all_1, 0:all_2]

    np_slice = flex_slice_2d.as_numpy_array()
    img_np = np.zeros([all_1, all_2], dtype=np.double)
    img_np[:, :] = np_slice[0:1, :, :]

    img.setImage(np.transpose(img_np), levels=(-3, 500))

    i += 1
    if i >= arr_data.all()[0]:
        i = 0

    QtCore.QTimer.singleShot(1, updateData)
    now = ptime.time()

    dif_time = updateTime - now
    updateTime = now

    print "dif_time =", dif_time
Exemple #30
0
 def update_monitor(self, timestamp_start, timestamp_stop, readout_error, scan_parameters, n_hits, n_events):
     self.timestamp_label.setText("Data Timestamp\n%s" % time.asctime(time.localtime(timestamp_stop)))
     self.scan_parameter_label.setText("Scan Parameters\n%s" % ', '.join('%s: %s' % (str(key), str(val)) for key, val in scan_parameters.iteritems()))
     now = ptime.time()
     recent_total_hits = n_hits
     recent_total_events = n_events
     self.plot_delay = self.plot_delay * 0.9 + (now - timestamp_stop) * 0.1
     self.plot_delay_label.setText("Plot Delay\n%s" % ((time.strftime('%H:%M:%S', time.gmtime(self.plot_delay))) if self.plot_delay > 5 else "%1.2f ms" % (self.plot_delay * 1.e3)))
     recent_fps = 1.0 / (now - self.updateTime)  # calculate FPS
     recent_hps = (recent_total_hits - self.total_hits) / (now - self.updateTime)
     recent_eps = (recent_total_events - self.total_events) / (now - self.updateTime)
     self.updateTime = now
     self.total_hits = recent_total_hits
     self.total_events = recent_total_events
     self.fps = self.fps * 0.7 + recent_fps * 0.3
     self.hps = self.hps + (recent_hps - self.hps) * 0.3 / self.fps
     self.eps = self.eps + (recent_eps - self.eps) * 0.3 / self.fps
     self.rate_label.setText("Readout Rate\n%d Hz" % self.fps)
     if self.spin_box.value() == 0:  # show number of hits, all hits are integrated
         self.hit_rate_label.setText("Total Hits\n%d" % int(recent_total_hits))
     else:
         self.hit_rate_label.setText("Hit Rate\n%d Hz" % int(self.hps))
     if self.spin_box.value() == 0:  # show number of events
         self.event_rate_label.setText("Total Events\n%d" % int(recent_total_events))
     else:
         self.event_rate_label.setText("Event Rate\n%d Hz" % int(self.eps))
Exemple #31
0
 def handle_data(self, data):
     if 'meta_data' not in data:  # Histograms
         self.occupancy_img.setImage(data['occupancy'][:, :],
                                     autoDownsample=True)
         self.tot_plot.setData(x=np.linspace(-0.5, 15.5, 17),
                               y=data['tot_hist'],
                               fillLevel=0,
                               brush=(0, 0, 255, 150))
         self.hist_hit_count.setData(x=np.linspace(-0.5, 100.5, 101),
                                     y=data['hist_hit_count'][:100],
                                     stepMode=True,
                                     fillLevel=0,
                                     brush=(0, 0, 255, 150))
     else:  # Meta data
         self._update_rate(data['meta_data']['fps'],
                           data['meta_data']['hps'],
                           data['meta_data']['total_hits'],
                           data['meta_data']['eps'],
                           data['meta_data']['total_events'])
         self.timestamp_label.setText("Data Timestamp\n%s" % time.asctime(
             time.localtime(data['meta_data']['timestamp_stop'])))
         self.scan_parameter_label.setText("Parameter ID\n%d" %
                                           data['meta_data']['scan_par_id'])
         now = ptime.time()
         self.plot_delay = self.plot_delay * 0.9 + (
             now - data['meta_data']['timestamp_stop']) * 0.1
         self.plot_delay_label.setText(
             "Plot Delay\n%s" % 'not realtime' if abs(self.plot_delay) > 5
             else "Plot Delay\n%1.2f ms" % (self.plot_delay * 1.e3))
 def update_monitor(self, timestamp_start, timestamp_stop, readout_error,
                    scan_parameters, n_hits, n_events):
     self.timestamp_label.setText(
         "Data Timestamp\n%s" %
         time.asctime(time.localtime(timestamp_stop)))
     self.scan_parameter_label.setText(
         "Scan Parameters\n%s" %
         ', '.join('%s: %s' % (str(key), str(val))
                   for key, val in scan_parameters.iteritems()))
     now = ptime.time()
     recent_total_hits = n_hits
     recent_total_events = n_events
     self.plot_delay = self.plot_delay * 0.9 + (now - timestamp_stop) * 0.1
     self.plot_delay_label.setText(
         "Plot Delay\n%s" %
         ((time.strftime('%H:%M:%S', time.gmtime(self.plot_delay)))
          if abs(self.plot_delay) > 5 else "%1.2f ms" %
          (self.plot_delay * 1.e3)))
     recent_fps = 1.0 / (now - self.updateTime)  # calculate FPS
     recent_hps = (recent_total_hits - self.total_hits) / (now -
                                                           self.updateTime)
     recent_eps = (recent_total_events -
                   self.total_events) / (now - self.updateTime)
     self.updateTime = now
     self.total_hits = recent_total_hits
     self.total_events = recent_total_events
     self.fps = self.fps * 0.7 + recent_fps * 0.3
     self.hps = self.hps + (recent_hps - self.hps) * 0.3 / self.fps
     self.eps = self.eps + (recent_eps - self.eps) * 0.3 / self.fps
     self.update_rate(self.fps, self.hps, recent_total_hits, self.eps,
                      recent_total_events)
Exemple #33
0
def update():
    global ui, ptr, lastTime, fps, LUT, img
    if ui.lutCheck.isChecked():
        useLut = LUT
    else:
        useLut = None

    if ui.scaleCheck.isChecked():
        if ui.rgbLevelsCheck.isChecked():
            useScale = [
                [ui.minSpin1.value(), ui.maxSpin1.value()], 
                [ui.minSpin2.value(), ui.maxSpin2.value()], 
                [ui.minSpin3.value(), ui.maxSpin3.value()]]
        else:
            useScale = [ui.minSpin1.value(), ui.maxSpin1.value()]
    else:
        useScale = None

    if ui.rawRadio.isChecked():
        ui.rawImg.setImage(data[ptr%data.shape[0]], lut=useLut, levels=useScale)
    else:
        img.setImage(data[ptr%data.shape[0]], autoLevels=False, levels=useScale, lut=useLut)
        #img.setImage(data[ptr%data.shape[0]], autoRange=False)
        
    ptr += 1
    now = ptime.time()
    dt = now - lastTime
    lastTime = now
    if fps is None:
        fps = 1.0/dt
    else:
        s = np.clip(dt*3., 0, 1)
        fps = fps * (1-s) + (1.0/dt) * s
    ui.fpsLabel.setText('%0.2f fps' % fps)
    app.processEvents()  ## force complete redraw for every plot
Exemple #34
0
    def __init__(self, focusWidget, main=None, *args, **kwargs):

        super().__init__(*args, **kwargs)

        self.focusWidget = focusWidget
        self.main = main
        self.analize = self.focusWidget.analizeFocus
        self.focusDataBox = self.focusWidget.focusDataBox
        self.savedDataSignal = []
        self.savedDataTime = []
        self.savedDataPosition = []

        self.setWindowTitle('Focus')
        self.setAntialiasing(True)

        self.npoints = 40
        self.data = np.zeros(self.npoints)
        self.ptr = 0

        # Graph without a fixed range
        self.statistics = pg.LabelItem(justify='right')
        self.addItem(self.statistics)
        self.statistics.setText('---')
        self.plot = self.addPlot(row=1, col=0)
        self.plot.setLabels(bottom=('Time', 's'),
                            left=('Laser position', 'px'))
        self.plot.showGrid(x=True, y=True)
        self.focusCurve = self.plot.plot(pen='y')

        self.time = np.zeros(self.npoints)
        self.startTime = ptime.time()

        if self.main is not None:
            self.recButton = self.main.recButton
Exemple #35
0
 def resetData(self):
     """Set all data points to zero, useful if going from very large values
     to very small values"""
     self.data = np.zeros(self.npoints)
     self.time = np.zeros(self.npoints)
     self.startTime = ptime.time()
     self.ptr = 0
def update():
    global ptr, lastTime, fps
    mode = param['mode']
    if mode == 'newItem':
        mkItem()
    elif mode == 'reuseItem':
        item.setData(**getData())
    elif mode == 'panZoom':
        item.viewTransformChanged()
        item.update()
    elif mode == 'hover':
        pts = item.points()
        old = pts[(ptr - 1) % len(pts)]
        new = pts[ptr % len(pts)]
        item.pointsAt(new.pos())
        old.resetBrush(
        )  # reset old's brush before setting new's to better simulate hovering
        new.setBrush(hoverBrush)

    ptr += 1
    now = time()
    dt = now - lastTime
    lastTime = now
    if fps is None:
        fps = 1.0 / dt
    else:
        s = np.clip(dt * 3., 0, 1)
        fps = fps * (1 - s) + (1.0 / dt) * s
    p.setTitle('%0.2f fps' % fps)
    p.repaint()
Exemple #37
0
 def mouseMoveEvent(self, ev):
     self.sigMouseMoved.emit(ev.scenePos())
     
     ## First allow QGraphicsScene to deliver hoverEnter/Move/ExitEvents
     QtGui.QGraphicsScene.mouseMoveEvent(self, ev)
     
     ## Next deliver our own HoverEvents
     self.sendHoverEvents(ev)
     
     if int(ev.buttons()) != 0:  ## button is pressed; send mouseMoveEvents and mouseDragEvents
         QtGui.QGraphicsScene.mouseMoveEvent(self, ev)
         if self.mouseGrabberItem() is None:
             now = ptime.time()
             init = False
             ## keep track of which buttons are involved in dragging
             for btn in [QtCore.Qt.LeftButton, QtCore.Qt.MidButton, QtCore.Qt.RightButton]:
                 if int(ev.buttons() & btn) == 0:
                     continue
                 if int(btn) not in self.dragButtons:  ## see if we've dragged far enough yet
                     cev = [e for e in self.clickEvents if int(e.button()) == int(btn)][0]
                     dist = Point(ev.screenPos() - cev.screenPos())
                     if dist.length() < self._moveDistance and now - cev.time() < 0.5:
                         continue
                     init = init or (len(self.dragButtons) == 0)  ## If this is the first button to be dragged, then init=True
                     self.dragButtons.append(int(btn))
                     
             ## If we have dragged buttons, deliver a drag event
             if len(self.dragButtons) > 0:
                 if self.sendDragEvent(ev, init=init):
                     ev.accept()
Exemple #38
0
    def __init__(self, parent=None):
        # initialization of the superclass
        super(VideoMainWindow, self).__init__(parent)
        # setup the GUI
        self.setupUi(self)
        # Use a file dialog to choose tiff stack
        file, mask = QFileDialog.getOpenFileName(self, 'Open a .tif/.tiff stack')
        # Read image data
        self.img = volread(file)
        # Transpose second and third axes (y, x) to correct orientation (x, y)
        self.img = np.transpose(self.img, (0, 2, 1))
        # for i in range(0, len(self.img)):
        #     self.img[i] = self.img[i].T

        # connect the signals with the slots
        # self.actionLoad.triggered.connect(self.open_tiff)
        # self.actionClose.triggered.connect(self.close)
        # self.actionTIFF.triggered.connect(self.open_tiff)
        # self.actionFolder.triggered.connect(self.open_folder)
        # self.actionStart_ImageProcess.triggered.connect(self.image_process)

        self.ptr = 0
        self.lastTime = ptime.time()
        self.fps = None

        # self.start()

        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.update)
        self.timer.start(0)
Exemple #39
0
 def getTime(self):
     if self.main.enabled:
         self.ptr = 0
         self.dataN = np.zeros(self.npoints, dtype=np.int)
         self.dataOverlaps = np.zeros(self.npoints, dtype=np.int)
         self.time = np.zeros(self.npoints)
         self.startTime = ptime.time()
Exemple #40
0
def capture():
    global i, updateTime, fps, bCaptureContinuous
    #camimg=cam.get_image()
    #arr=pygame.surfarray.pixels3d(camimg)
    ## Display the data
    frame=cam.get_frame_bw()
    #img.setImage(arr[:,:,:])
    #arr=np.random.normal(size=(640,480))**2
    main.updateFrame(frame)
    crp.updateFrame(main.subFrame)
    #img.setImage(frame)
    #print("maj: {}, min: {}".format(outD['major_axis'], outD['minor_axis']))
    #img2.setImage(outD['frame'])
    #updateFit()


    
    if bCaptureContinuous:
        QtCore.QTimer.singleShot(1, capture)
        now = ptime.time()
        fps2 = 1.0 / (now-updateTime)
        updateTime = now
        fps = fps * 0.9 + fps2 * 0.1
    
    print("%0.1f fps" % fps)
Exemple #41
0
 def setValue(self, value):
     now = time()
     self.values.append((now, value))
     cutoff = now - self.averageTime
     while len(self.values) > 0 and self.values[0][0] < cutoff:
         self.values.pop(0)
     self.update()
def update():
    global curve, data, ptr, p, lastTime, fps
    p.clear()
    if ui.randCheck.isChecked():
        size = sizeArray
        brush = brushArray
    else:
        size = ui.sizeSpin.value()
        brush = 'b'
    curve = pg.ScatterPlotItem(x=data[ptr % 50],
                               y=data[(ptr + 1) % 50],
                               pen='w',
                               brush=brush,
                               size=size,
                               pxMode=ui.pixelModeCheck.isChecked())
    p.addItem(curve)
    ptr += 1
    now = time()
    dt = now - lastTime
    lastTime = now
    if fps is None:
        fps = 1.0 / dt
    else:
        s = np.clip(dt * 3., 0, 1)
        fps = fps * (1 - s) + (1.0 / dt) * s
    p.setTitle('%0.2f fps' % fps)
    p.repaint()
Exemple #43
0
    def handle_data_if_active(self, data):
        # look for TLU data in data stream
        if 'tlu' in data:
            # fill plots
            for key in data['tlu']:
                # if array not full, plot data only up to current array_index, 'indices' is keyword
                if data['indices'][key] < data['tlu'][key].shape[1]:
                    # set the plot data to the corresponding arrays where only the the values up to self.array_index are plotted
                    self.plots[key].setData(
                        data['tlu'][key][0][:data['indices'][key]],
                        data['tlu'][key][1][:data['indices'][key]],
                        autoDownsample=True)

                # if array full, plot entire array
                elif data['indices'][key] >= data['tlu'][key].shape[1]:
                    # set the plot data to the corresponding arrays
                    self.plots[key].setData(data['tlu'][key][0],
                                            data['tlu'][key][1],
                                            autoDownsample=True)

        # set timestamp, plot delay and readour rate
        self.rate_label.setText("Readout Rate\n%d Hz" % data['fps'])
        self.timestamp_label.setText(
            "Data Timestamp\n%s" %
            time.asctime(time.localtime(data['timestamp_stop'])))
        now = ptime.time()
        self.plot_delay = self.plot_delay * 0.9 + (
            now - data['timestamp_stop']) * 0.1
        self.plot_delay_label.setText(
            "Plot Delay\n%s" %
            'not realtime' if abs(self.plot_delay) > 5 else "%1.2f ms" %
            (self.plot_delay * 1.e3))
Exemple #44
0
def update():
    global curve, data, ptr, p, lastTime, fps

    byte = str(ser.readline().strip())
    #print(byte)

    try:
        if (byte[2] == '*'):

            data = (ser.readline().strip())
            #print("printing dat...")
            #print(data)
            #print(data[2])

            split_data = data.decode('ascii').split(',')
            #print(split_data)
            split_data = list(map(float, split_data[:-1]))

            curve.setData((split_data))
    except:
        pass

    ptr += 1
    now = time()
    dt = now - lastTime
    lastTime = now
    if fps is None:
        fps = 1.0 / dt
    else:
        s = np.clip(dt * 3., 0, 1)
        fps = fps * (1 - s) + (1.0 / dt) * s
    p.setTitle('%0.2f fps' % fps)
    app.processEvents()  ## force complete redraw for every plot
 def movie_play(self):
     self.play = True
     print('loading image sequence')
     self.load_image_sequence()
 
     print('playing movie')
     self.updateTime = ptime.time()
     self.updateData()
 def movie_pause(self):
     if self.play is True:
         self.play = False
         print('pause movie')
     elif self.play is False:
         self.play = True
         print('playing movie')
         self.updateTime = ptime.time()
         self.updateData()
Exemple #47
0
def update():
    global p,img, updateTime, fps, logdata, fptr, buf,darks, flatField, seq_count, plot1, plot2, cnt, runTime
    Tacq = p.param('Tacq').value()
    to = time.time()
#    x = buf.coincidences(Tacq, CoincidenceWindow)
    x = buf.coincidences(Tacq, CoincidenceWindow, delays)
    tf = time.time()
    runTime += tf - to
    cnt += 1
    meanRunTime = runTime/cnt
#    print "Mean Run Time: ", meanRunTime
    image = np.zeros(64)
    image = np.reshape(x[0:8,8::],(1,64))
#    print image
#    print "Total Counts: ", np.sum(image)
    if p.param('Use Darkfield').value():
      imageCorrected = image-darks[8,:]
    else:
      imageCorrected = image
    if p.param('Use Flatfield').value():
      imageCorrected = imageCorrected/flatField
    
    #displayimage = np.reshape(imageCorrected,(8,8))[::-1,:].T # This works
    displayimage = np.reshape(imageCorrected,(8,8))[::-1,::-1].T

    level=(p.param('min').value(), p.param('max').value() )
    img.setImage(displayimage,autoLevels=False,levels=level)
    now = ptime.time()
    fps2 = 1.0 / (now-updateTime)
    updateTime = now
    fps = fps * 0.9 + fps2 * 0.1
    if p.param('Plot row').value()>0:
      row = p.param('Plot row').value()-1
      idx = np.arange(8) + row*8
#      curve1.setData(image[0,idx])
#      curve1.setData(imageCorrected[0,idx]+0.001)
#      curve1.setData(np.log10(imageCorrected[0,idx]))
    if p.param('Plot col').value()>0:
      col = p.param('Plot col').value()-1
      idx = np.arange(8)*8 + col 
#      curve2.setData(imageCorrected[0,idx]+0.001)
#      curve2.setData(image[0,idx])
    #print logdata
    if logdata==True:
      print 'logging data'
      fptr.write('%f '%Tacq) 
      image.tofile(fptr,sep=' ')
      fptr.write('\n')
      fptr.flush() 
    #print "%0.1f fps" % fps

    if p.param('Save Sequence').value():
      print "saving image"
      fname = sequencepath + '/' + basename + '%05d.png'%seq_count
      img.save(fname) 
      seq_count = seq_count + 1
Exemple #48
0
 def __init__(self, pressEvent, double=False):
     self.accepted = False
     self.currentItem = None
     self._double = double
     self._scenePos = pressEvent.scenePos()
     self._screenPos = pressEvent.screenPos()
     self._button = pressEvent.button()
     self._buttons = pressEvent.buttons()
     self._modifiers = pressEvent.modifiers()
     self._time = ptime.time()
 def __init__(self, r,c):
     self.view = win.addViewBox(row=r, col=c)
     self.view.setAspectLocked(True)
     self.img = pg.ImageItem(border='k')
     self.view.addItem(self.img)
     self.view.setRange(QtCore.QRectF(0, 0, 600, 600))
     self.data = np.random.normal(size=(15, 600, 600), loc=1024, scale=64).astype(np.uint16)
     self.i = 0
     self.updateTime = ptime.time()
     self.fps = 0
Exemple #50
0
 def play(self, rate):
     #print "play:", rate
     self.playRate = rate
     if rate == 0:
         self.playTimer.stop()
         return
         
     self.lastPlayTime = ptime.time()
     if not self.playTimer.isActive():
         self.playTimer.start(16)
Exemple #51
0
    def reset(self):
        self.data = np.zeros(self.npoints)
        self.time = np.zeros(self.npoints)
        self.ptr = 0
        self.startTime = ptime.time()

        self.focusWidget.n = 1
        self.focusWidget.max_dev = 0
        self.focusWidget.mean = self.focusWidget.ProcessData.focusSignal
        self.focusWidget.std = 0
Exemple #52
0
 def timeElapsed(self):
     now = time()
     dt = now - self.lastTime
     self.lastTime = now
     if self.fps is None:
         self.fps = 1.0/dt
     else:
         s = np.clip(dt*3., 0, 1)
         self.fps = self.fps * (1-s) + (1.0/dt) * s
     self.p.setTitle('%0.2f fps' % self.fps)
Exemple #53
0
 def play(self, rate):
     """Begin automatically stepping frames forward at the given rate (in fps).
     This can also be accessed by pressing the spacebar."""
     #print "play:", rate
     self.playRate = rate
     if rate == 0:
         self.playTimer.stop()
         return
         
     self.lastPlayTime = ptime.time()
     if not self.playTimer.isActive():
         self.playTimer.start(16)
Exemple #54
0
 def __init__(self, socket_addr):
     super(OnlineMonitorApplication, self).__init__()
     self.setup_plots()
     self.add_widgets()
     self.fps = 0
     self.eps = 0  # events per second
     self.total_events = 0
     self.total_readouts = 0
     self.last_total_events = 0
     self.updateTime = ptime.time()
     self.setup_data_worker_and_start(socket_addr)
     self.cpu_load = max(psutil.cpu_percent(percpu=True))
Exemple #55
0
 def update_monitor(self):
     now = ptime.time()
     recent_eps = (self.total_events - self.last_total_events) / (now - self.updateTime)
     self.last_total_events = self.total_events
     self.updateTime = now
     self.eps = self.eps * 0.98 + recent_eps * 0.02
     if self.spin_box.value() == 0:  # show number of events
         self.event_rate_label.setText("Total Events\n%d" % int(self.total_events))
     else:
         self.event_rate_label.setText("Event Rate\n%d Hz" % int(self.eps))
         
     self.total_events_label.setText("Total Events\n%d" % int(self.total_events))
Exemple #56
0
 def __init__(self, socket_addr):
     super(OnlineMonitorApplication, self).__init__()
     self.setup_plots()
     self.add_widgets()
     self.fps = 0  # data frames per second
     self.hps = 0  # hits per second
     self.eps = 0  # events per second
     self.plot_delay = 0
     self.updateTime = ptime.time()
     self.total_hits = 0
     self.total_events = 0
     self.setup_data_worker_and_start(socket_addr)
Exemple #57
0
def updateData():
    global img, data, i, updateTime, fps

    ## Display the data
    img.setImage(data[i])
    i = (i+1) % data.shape[0]

    QtCore.QTimer.singleShot(1, updateData)
    now = ptime.time()
    fps2 = 1.0 / (now-updateTime)
    updateTime = now
    fps = fps * 0.9 + fps2 * 0.1
Exemple #58
0
 def __init__(self,app):
     self.app = app
     pg.setConfigOptions(antialias=True)        
     self.win = pg.GraphicsWindow(title="Basic plotting examples")
     self.win.resize(800,800)
     self.win.setWindowTitle('SmartPolyTech Beacon System')
     
     self.p = self.win.addPlot(title='RSSI graph')
     self.graphView = self.win.addViewBox(row=1,col=0)
     #self.graphView.setLimits(xMin=-5, xMax=5, yMin = -5, yMax=5)
     self.graphView.setAspectLocked()
     self.graphView.setRange(rect=QtCore.QRectF(-6,6,12,-12))
    
     box = QtGui.QGraphicsRectItem(-10, 5, 20, -10)
     box.setPen(pg.mkPen("w"))
     box.setBrush(pg.mkBrush(None))
     self.graphView.addItem(box)
     self.graphView.show()
     self.graph = pg.GraphItem()
     self.graphView.addItem(self.graph)
     
     self.bufferLength = 20
     self.p.setRange(QtCore.QRectF(0, 0, self.bufferLength, 100)) 
     self.p.setLabel('bottom', 'Samples')
     self.p.setLabel('left', 'Signal Strength')
     self.p.setAutoVisible(y=True)
     
     #cross hair
     try:
         dev_id = 0
         self.sock = bluez.hci_open_dev(dev_id)
         print "ble thread started"
     except:
         print "error accessing bluetooth device..."
         sys.exit(1)
     
     #Variables
     self.lastTime = time()
     self.fps = None
     
     #Timers
     self.timerBluetooth = QtCore.QTimer()
     self.timerBluetooth.timeout.connect(self.updateBluetooth)
     self.timerBluetooth.start(300)       
     
     self.timer = QtCore.QTimer()
     self.timer.timeout.connect(self.compute)
     self.timer.start(100)
    
     #self.p.scene().sigMouseMoved.connect(self.mouseMoved)
     
     self.signalList = {}
     self.curveList = {}
Exemple #59
0
 def evalKeyState(self):
     if len(self.keysPressed) == 1:
         key = self.keysPressed.keys()[0]
         if key == QtCore.Qt.Key_Right:
             self.play(20)
             self.jumpFrames(1)
             self.lastPlayTime = ptime.time() + 0.2  ## 2ms wait before start
                                                     ## This happens *after* jumpFrames, since it might take longer than 2ms
         elif key == QtCore.Qt.Key_Left:
             self.play(-20)
             self.jumpFrames(-1)
             self.lastPlayTime = ptime.time() + 0.2
         elif key == QtCore.Qt.Key_Up:
             self.play(-100)
         elif key == QtCore.Qt.Key_Down:
             self.play(100)
         elif key == QtCore.Qt.Key_PageUp:
             self.play(-1000)
         elif key == QtCore.Qt.Key_PageDown:
             self.play(1000)
     else:
         self.play(0)
Exemple #60
0
 def timeout(self):
     now = ptime.time()
     dt = now - self.lastPlayTime
     if dt < 0:
         return
     n = int(self.playRate * dt)
     #print n, dt
     if n != 0:
         #print n, dt, self.lastPlayTime
         self.lastPlayTime += (float(n)/self.playRate)
         if self.currentIndex+n > self.image.shape[0]:
             self.play(0)
         self.jumpFrames(n)