def create_plot(self):
        self.stream_scroll = pg.PlotWidget(
            title='Stream Monitor',
            labels={'left': 'Channel'},
            axisItems={'bottom': TimeAxisItem(orientation='bottom')}
        )
        self.stream_scroll.setMinimumHeight(200)
        self.stream_scroll.setYRange(-4,4,padding=.01)

        # self.stream_scroll.setXRange(0,100, padding=.01)
        self.stream_scroll.setXRange(timestamp(), timestamp() + 100)

        self.layout = QtGui.QGridLayout()
        self.stream_scroll.plotItem.showGrid(True, True, .5)
        self.layout.addWidget(self.stream_scroll,0,0)

        C=pg.hsvColor(.7,alpha=.5)
        self.pen=pg.mkPen(color=C,width=1)
        self.curve = self.stream_scroll.plot(pen=self.pen)

        C1=pg.hsvColor(.6,alpha=.5)
        self.pen1=pg.mkPen(color=C1,width=1)
        self.curve1 = self.stream_scroll.plot(pen=self.pen1)

        C2=pg.hsvColor(.5,alpha=.5)
        self.pen2=pg.mkPen(color=C2,width=1)
        self.curve2 = self.stream_scroll.plot(pen=self.pen2)

        C3=pg.hsvColor(.4,alpha=.5)
        self.pen3=pg.mkPen(color=C3,width=1)
        self.curve3 = self.stream_scroll.plot(pen=self.pen3)
Example #2
0
    def show_stim(self, x, y, xname, plotwidget):
        if xname == 'Time (sec)':
            Lbrush = pg.mkBrush(pg.hsvColor(0.0, sat=0.4, alpha=0.3))
            Rbrush = pg.mkBrush(pg.hsvColor(0.5, sat=0.4, alpha=0.3))

            for onoff in self.bender.Lonoff:
                leftplot = pg.LinearRegionItem(onoff,
                                               movable=False,
                                               brush=Lbrush)
                plotwidget.addItem(leftplot)
            for onoff in self.bender.Ronoff:
                rightplot = pg.LinearRegionItem(onoff,
                                                movable=False,
                                                brush=Rbrush)
                plotwidget.addItem(rightplot)
        else:
            Lpen = pg.mkPen(color=pg.hsvColor(0.0, sat=0.4), width=4)
            Rpen = pg.mkPen(pg.hsvColor(0.5, sat=0.4), width=4)

            t = self.bender.t
            for onoff in self.bender.Lonoff:
                ison = np.logical_and(t >= onoff[0], t < onoff[1])
                plotwidget.plot(pen=Lpen, clear=False, x=x[ison], y=y[ison])

            for onoff in self.bender.Ronoff:
                ison = np.logical_and(t >= onoff[0], t < onoff[1])
                plotwidget.plot(pen=Rpen, clear=False, x=x[ison], y=y[ison])
Example #3
0
    def set_plotdata(self, name, data_x, data_y):
        self.getFrequnzies(self.INTERVALS)
        if name in self.traces:
            #print(self.frequencies)
            if name == 'frequenciesChart':
                self.getFrequnzies(self.INTERVALS)
                self.bg1.setOpts(height=self.clean(self.frequencies +
                                                   [np.sum(self.frequencies)] +
                                                   [30]))
                #print(self.frequencies)
            elif name == 'colorDiagram':
                pen = pg.mkPen('y', width=3, style=QtCore.Qt.DashLine)
                self.traces[name].setPen(
                    pg.mkPen(color=pg.hsvColor(self.angle / 360,
                                               sat=1,
                                               val=self.brightness[-1][0],
                                               alpha=1.0),
                             width=100))
                self.traces[name].setData(data_x, data_y)
            else:
                self.traces[name].setData(data_x, data_y)

        else:

            if name == 'waveform':
                pen = pg.mkPen(
                    color=pg.hsvColor(0.66, sat=1, val=1.0, alpha=1.0))
                self.traces[name] = self.waveform.plot(pen=pen, width=3)

                self.waveform.setYRange(0, 255, padding=0)

                self.waveform.setXRange(0, 2 * self.CHUNK, padding=0.005)

            if name == 'spectrum':

                self.traces[name] = self.spectrum.plot(pen='m', width=3)

                self.spectrum.setLogMode(x=True, y=True)

                self.spectrum.setYRange(-4, 0, padding=0)

                self.spectrum.setXRange(np.log10(20),
                                        np.log10(self.RATE / 2),
                                        padding=0.005)

            if name == 'frequenciesChart':

                self.traces[name] = self.bg1

            if name == 'colorDiagram':

                self.traces[name] = self.traces[name] = self.colorDiagram.plot(
                    pen='m', width=3)
                self.colorDiagram.setYRange(0, 2, padding=0)

                self.colorDiagram.setXRange(0, 3, padding=0.005)
Example #4
0
    def show_stim(self, x, y, xname, plotwidget):
        if xname == 'Time (sec)':
            br = pg.mkBrush(pg.hsvColor(0.0, sat=0.4, alpha=0.3))

            for onoff in self.bender.actonoff:
                actplot = pg.LinearRegionItem(onoff, movable=False, brush=br)
                plotwidget.addItem(actplot)
        else:
            pen = pg.mkPen(color=pg.hsvColor(0.0, sat=0.4), width=4)

            t = self.bender.t
            for onoff in self.bender.actonoff:
                ison = np.logical_and(t >= onoff[0], t < onoff[1])
                plotwidget.plot(pen=pen, clear=False, x=x[ison], y=y[ison])
Example #5
0
    def update(self):

        self.X= np.append(self.X,self.index+1)
        self.index=self.index+1
        print self.X
        if self.index<20:
            self.Y= np.append(self.Y,0)
        elif self.index>60:
            self.Y= np.append(self.Y,0)
        else:
            self.Y= np.append(self.Y,(self.index+1-20)*(self.index+1-20)*1.00/1000)
        #for x in self.X:
        #    print x
        print self.Y
        
        t1=time.clock()
        points=100 #number of data points
        X=np.arange(points)
        #print np.sin(np.arange(points))
        Y=np.sin(np.arange(points)*3*np.pi+time.time())
        #print np.arange(points)
        #print np.arange(points)/points*3*np.pi+time.time()
        #Y=np.sin(np.arange(points)/points*3*np.pi+time.time())
        #print Y
        C=pyqtgraph.hsvColor(time.time()/5%1,alpha=.5)
        pen=pyqtgraph.mkPen(color=C,width=5)
        self.grPlot.plot(self.X,self.Y,pen=pen,clear=True)
        print("update took %.02f ms"%((time.clock()-t1)*1000))
        time.sleep(0.5)
        if self.chkMore.isChecked():
            QtCore.QTimer.singleShot(1, self.update) # QUICKLY repeat
Example #6
0
File: Qacam.py Project: hgao1/qacam
 def recordScan(self, data):
     self.data.append([val for tup in data for val in tup])
     x, y = data[1]
     amp, phi = data[2]
     hue = (phi / 360. + 1.) % 1.
     brush = pg.mkBrush(color=pg.hsvColor(hue))
     self.traceItem.addPoints([x], [y], brush=brush)
Example #7
0
    def create_new_axis(self, plt, name, ratio=False):
        if name in self.extra_axes.keys():
            QtGui.QMessageBox.about(self, "Error %s" % self.current_selected,
                                        "Limited to one additional axis per plot")

        else:
            new_vb = pg.ViewBox()
            self.extra_axes[name] = new_vb
            plt.showAxis('right')
            plt.scene().addItem(new_vb)
            plt.getAxis('right').linkToView(new_vb)
            new_vb.setXLink(plt)

            def updateViews(plt, new_vb):
                new_vb.setGeometry(plt.vb.sceneBoundingRect())
                new_vb.linkedViewChanged(plt.vb, new_vb.XAxis)

            updateViews(plt, new_vb)
            plt.vb.sigResized.connect(lambda: updateViews(plt, new_vb))

            if ratio:
                self.axis2_curves[name], label = self.plot_ratio_new_axis(new_vb)
            else:
                self.axis2_curves[name], label = self.plot_data_new_axis(new_vb)

            plt.getAxis('right').setLabel(label)
            try:
                self.axis2_curves[name][0].setPen(pg.hsvColor(0.8, sat=1.0, val=0.8, alpha=1.0))
            except IndexError:
                pass
Example #8
0
    def update(self, pos = 0, msg = ""):
        C=pyqtgraph.hsvColor(1)
        pen=pyqtgraph.mkPen(color=C,width=1)
        data = np.zeros(10)

        pos = int(self.video_model.get_pos())
        self.indicator.setData([pos,pos],[self.indicator_min,self.indicator_max]) #= self.plot_item.plot([pos,pos],[self.indicator_min,self.indicator_max],pen=pyqtgraph.mkPen(color=pyqtgraph.hsvColor(2),width=1))
Example #9
0
    def create_new_axis(self, plt, name, ratio=False):
        if name in self.extra_axes.keys():
            QtGui.QMessageBox.about(self, "Error %s" % self.current_selected,
                                        "Limited to one additional axis per plot")

        else:
            new_vb = pg.ViewBox()
            self.extra_axes[name] = new_vb
            plt.showAxis('right')
            plt.scene().addItem(new_vb)
            plt.getAxis('right').linkToView(new_vb)
            new_vb.setXLink(plt)

            def updateViews(plt, new_vb):
                new_vb.setGeometry(plt.vb.sceneBoundingRect())
                new_vb.linkedViewChanged(plt.vb, new_vb.XAxis)

            updateViews(plt, new_vb)
            plt.vb.sigResized.connect(lambda: updateViews(plt, new_vb))

            if ratio:
                self.axis2_curves[name], label = self.plot_ratio_new_axis(new_vb)
            else:
                self.axis2_curves[name], label = self.plot_data_new_axis(new_vb)

            plt.getAxis('right').setLabel(label)
            try:
                self.axis2_curves[name][0].setPen(pg.hsvColor(0.8, sat=1.0, val=0.8, alpha=1.0))
            except IndexError:
                pass
Example #10
0
 def showUpdate(self):
     t = time.clock()
     points = 100  #number of data points
     X = np.arange(points)
     Y = np.sin(np.arange(points) / points * 3 * np.pi + time.time())
     C = pyqtgraph.hsvColor(time.time() / 5 % 1, alpha=.5)
     pen = pyqtgraph.mkPen(color=C, width=5)
     self.AvgPlot.plot(X, Y, pen=pen, clear=True)
Example #11
0
 def update(self):
     t1 = time.clock()
     points = 100  #number of data points
     X = np.arange(points)
     Y = np.sin(np.arange(points) / points * 3 * np.pi + time.time())
     C = pyqtgraph.hsvColor(time.time() / 5 % 1, alpha=.5)
     pen = pyqtgraph.mkPen(color=C, width=2)
     self.plot_ul.plot(X, Y, pen=pen, clear=True)
     print("update took %.02f ms" % ((time.clock() - t1) * 1000))
    def draw_buffer(self):
        self.buff_win = pg.GraphicsLayoutWidget()
        self.buff_win.setWindowTitle('Buffer Status')
        self.buff_win.resize(800, 700)

        self.total_peers = self.number_of_monitors + self.number_of_peers + self.number_of_malicious
        self.p4 = self.buff_win.addPlot()
        self.p4.showGrid(
            x=True, y=True,
            alpha=100)  # To show grid lines across x axis and y axis
        leftaxis = self.p4.getAxis('left')  # get left axis i.e y axis
        leftaxis.setTickSpacing(
            5, 1)  # to set ticks at a interval of 5 and grid lines at 1 space

        # Get different colors using matplotlib library
        if self.total_peers < 8:
            colors = cm.Set2(np.linspace(0, 1, 8))
        elif self.total_peers < 12:
            colors = cm.Set3(np.linspace(0, 1, 12))
        else:
            colors = cm.rainbow(np.linspace(0, 1, self.total_peers + 1))
        self.QColors = [
            pg.hsvColor(color[0], color[1], color[2], color[3])
            for color in colors
        ]  # Create QtColors, each color would represent a peer

        self.Data = [
        ]  # To represent buffer out  i.e outgoing data from buffer
        self.OutData = []  # To represent buffer in i.e incoming data in buffer

        # a single line would reperesent a single color or peer, hence we would not need to pass a list of brushes
        self.lineIN = [None] * self.total_peers
        for ix in range(self.total_peers):
            self.lineIN[ix] = self.p4.plot(pen=(None),
                                           symbolBrush=self.QColors[ix],
                                           name='IN',
                                           symbol='o',
                                           clear=False)
            self.Data.append(set())
            self.OutData.append(set())

        # similiarly one line per peer to represent outgoinf data from buffer
        self.lineOUT = self.p4.plot(pen=(None),
                                    symbolBrush=mkColor('#CCCCCC'),
                                    name='OUT',
                                    symbol='o',
                                    clear=False)
        self.p4.setRange(xRange=[0, self.total_peers],
                         yRange=[0, self.get_buffer_size()])
        self.buff_win.show()  # To actually show create window

        self.buffer_order = {}
        self.buffer_index = 0
        self.buffer_labels = []
        self.lastUpdate = pg.ptime.time()
        self.avgFps = 0.0
Example #13
0
 def update(self):
     t1 = time.clock()
     points = 100  #number of data points
     X = np.arange(points)
     Y = np.sin(np.arange(points) / points * 3 * np.pi + time.time())
     C = pyqtgraph.hsvColor(time.time() / 5 % 1, alpha=.5)
     pen = pyqtgraph.mkPen(color=C, width=5)
     self.AvgPlot.plot(X, Y, pen=pen, clear=True)
     print("update took %.02f ms" % ((time.clock() - t1) * 1000))
     QtCore.QTimer.singleShot(1, self.update)  # QUICKLY repeat
Example #14
0
    def plot_hypnogram(self):
        use_data = self.dataloader.PRED
        sleep_level = ['W', 'N1', 'N2', 'N3', 'REM']
        calib = self.status['calib']
        brush = pg.mkBrush(pg.hsvColor(0.6, 1, 0.3, 0.3))
        lin_space = np.array(
            (np.arange(self.dataloader.PRED.shape[0]),
            np.arange(self.dataloader.PRED.shape[0])+1))
        lin_space = lin_space.transpose().reshape(-1)
        # label_temp = np.array((self.dataloader.LABEL, self.dataloader.LABEL))
        # label_temp = label_temp.transpose().reshape(-1)
        pred_temp = np.array((use_data, use_data))
        pred_temp = pred_temp.transpose().reshape(-1)
        hypno_temp = np.array((self.user_annotation_record,
            self.user_annotation_record))
        hypno_temp = hypno_temp.transpose().reshape(-1)
        ticks = [[(v, '{}'.format(
            self.time_format([23, 0, 0 + int(v*30)]))) for v in (np.arange(
            self.dataloader.PRED.shape[0])[0::50])]]
        y_ticks = [[(v, '{}'.format(
            sleep_level[v])) for v in np.arange(0, 5)]]
        y_ticks[0].append((-1, 'Not scored'))
        self.hypnogram_ax.clear()
        self.hypnogram_ax.setBackground('w')

        self.hypnogram_ax.setYRange(-1, 5)
        self.hypnogram_ax.setXRange(0, self.dataloader.PRED.shape[0])
        self.hypnogram_ax.plot(lin_space, pred_temp,
            pen=pg.mkPen(color='b', width=POINTFIVE))
        self.hypnogram_ax.plot(lin_space, hypno_temp,
            pen=pg.mkPen(color='r', width=POINTFIVE))
        # self.hypnogram_ax.plot(lin_space, label_temp,
        #     pen=pg.mkPen(color='g', width=0.5))
        stem1 = pg.PlotDataItem(x=np.ones(5)*(self.status['counter']), 
            y=np.linspace(-1, 6, 5))
        stem2 = pg.PlotDataItem(x=np.ones(5)*(self.status['counter'] + 1), 
            y=np.linspace(-1, 6, 5))
        fbtwn = pg.FillBetweenItem(stem1, stem2, brush=brush)
        self.hypnogram_ax.addItem(fbtwn)

        x_axis = self.hypnogram_ax.getAxis('bottom')
        y_axis = self.hypnogram_ax.getAxis('left')
        x_axis.setTicks(ticks)
        y_axis.setTicks(y_ticks)
        self.annotate.info_pred_label.setText('Annotate as {}'.format(
            sleep_level[int(self.dataloader.PRED[self.status['counter']])]))
        self.annotate.reannotate_label.setText('Reannotate')
        self.hypnogram_ax.setTitle(
                'Model Prediction: {}, Epoch: {}/{}'
                .format(sleep_level[int(
                            self.dataloader.PRED[self.status['counter']])],
                        self.status['counter'] + 1,
                        len(self.dataloader.PRED)
                        )
                )
 def __init__(self, tau=5):
     self.axis = pg.PlotWidget(title="Event triggered",
                               labels={
                                   'left': 'Volts',
                                   'bottom': 'Time (seconds)'
                               })
     self.axis.addLegend(offset=(-10, 10))
     self.prev_plot = self.axis.plot(pen=pg.mkPen(
         pg.hsvColor(0.6, sat=0, alpha=0.3)),
                                     name='latest')
     self.ave_plot = self.axis.plot(pen=pg.mkPen(pg.hsvColor(0.6)),
                                    name='average')
     self.axis.addItem(
         pg.InfiniteLine(pos=0,
                         angle=90,
                         pen=pg.mkPen(style=QtCore.Qt.DotLine)))
     self.axis.setXRange(triggered_dur[0], triggered_dur[1], padding=0)
     self.alpha = 1 - np.exp(
         -1. / tau
     )  # Learning rate for update of average trace, tau is time constant.
Example #16
0
 def update(self):
     t1=time.clock()
     points=100 #number of data points
     X=np.arange(points)
     Y=np.sin(np.arange(points)/points*3*np.pi+time.time())
     C=pyqtgraph.hsvColor(time.time()/5%1,alpha=.5)
     pen=pyqtgraph.mkPen(color=C,width=10)
     self.grPlot.plot(X,Y,pen=pen,clear=True)
     print("update took %.02f ms"%((time.clock()-t1)*1000))
     if self.chkMore.isChecked():
         QtCore.QTimer.singleShot(1, self.update) # QUICKLY repeat
Example #17
0
    def plot_data(self, plt, curves=None):
        checked = self.model.checked_dict
        if curves is None:
            curves = []

        for folder in checked.keys():
            current_df = self.model.data[folder]

            for key in checked[folder].keys():
                if key in self.model.vr_headers[folder]:
                    for sweep in checked[folder][key]:
                        x = current_df['voltage recording']['Time'][sweep]
                        y = current_df['voltage recording'][key][sweep]
                        curve = plt.plot(x, y, pen=pg.hsvColor(0.0, sat=0.0, val=0.5, alpha=0.08))
                        curves.append(curve)

                elif key in self.model.ls_headers[folder]:
                    for sweep in checked[folder][key]:
                        x = current_df['linescan'][key + ' Time'][sweep]
                        y = current_df['linescan'][key][sweep]
                        curve = plt.plot(x, y, pen=pg.hsvColor(0.0, sat=0.0, val=0.5, alpha=0.08))
                        curves.append(curve)

                channel = list(checked[folder])[0]
                if folder in self.model.ls_headers.keys():
                    if channel in self.model.ls_headers[folder]:
                        plt.setLabel('left', channel)
                        plt.setLabel('bottom', 'Time (s)')
                else:
                    if channel == 'Primary':
                        label = channel + ' (' + current_df['file attributes']['File1']['primary']['unit'] + ')'
                    elif key == 'Secondary':
                        label = channel + ' (' + current_df['file attributes']['File1']['secondary']['unit'] + ')'
                    else:
                        label = channel + ' (V)'
                    plt.setLabel('left', label)
                    plt.setLabel('bottom', 'Time (s)')

            plt.autoRange()

        return curves
Example #18
0
    def plot_data(self, plt, curves=None):
        checked = self.model.checked_dict
        if curves is None:
            curves = []

        for folder in checked.keys():
            current_df = self.model.data[folder]

            for key in checked[folder].keys():
                if key in self.model.vr_headers[folder]:
                    for sweep in checked[folder][key]:
                        x = current_df['voltage recording']['Time'][sweep]
                        y = current_df['voltage recording'][key][sweep]
                        curve = plt.plot(x, y, pen=pg.hsvColor(0.0, sat=0.0, val=0.5, alpha=0.08))
                        curves.append(curve)

                elif key in self.model.ls_headers[folder]:
                    for sweep in checked[folder][key]:
                        x = current_df['linescan'][key + ' Time'][sweep]
                        y = current_df['linescan'][key][sweep]
                        curve = plt.plot(x, y, pen=pg.hsvColor(0.0, sat=0.0, val=0.5, alpha=0.08))
                        curves.append(curve)

                channel = list(checked[folder])[0]
                if folder in self.model.ls_headers.keys():
                    if channel in self.model.ls_headers[folder]:
                        plt.setLabel('left', channel)
                        plt.setLabel('bottom', 'Time (s)')
                else:
                    if channel == 'Primary':
                        label = channel + ' (' + current_df['file attributes']['File1']['primary']['unit'] + ')'
                    elif key == 'Secondary':
                        label = channel + ' (' + current_df['file attributes']['File1']['secondary']['unit'] + ')'
                    else:
                        label = channel + ' (V)'
                    plt.setLabel('left', label)
                    plt.setLabel('bottom', 'Time (s)')

            plt.autoRange()

        return curves
Example #19
0
    def update(self, pos=0, msg=""):
        """ Updates the image, setting the colormap"""
        if self.print_indicator and self.indicator and not self.video_model == None:
            C = pyqtgraph.hsvColor(1)
            pen = pyqtgraph.mkPen(color=C, width=1)
            data = np.zeros(10)

            pos = int(
                self.video_model.get_pos(datatype=self.model.get_datatype()))
            self.indicator.setData(
                [pos, pos], [self.indicator_min, self.indicator_max]
            )  #= self.plot_item.plot([pos,pos],[self.indicator_min,self.indicator_max],pen=pyqtgraph.mkPen(color=pyqtgraph.hsvColor(2),width=1))
Example #20
0
 def update(self, pos):
     """ Updates indicator position
         Args:
             pos: Int describing the current position of the indicator
     """
     if self.print_indicator and self.indicator and not self.video_model == None:
         C = pyqtgraph.hsvColor(1)
         pen = pyqtgraph.mkPen(color=C, width=1)
         pos = int(
             self.video_model.get_pos(datatype=self.model.get_datatype()))
         self.indicator.setData([pos, pos],
                                [self.indicator_min, self.indicator_max])
Example #21
0
    def plot_data_new_axis(self, new_vb):
        checked = self.model.checked_dict
        curves = []
        label = ""
        for folder in checked.keys():
            current_df = self.model.data[folder]

            for key in checked[folder].keys():
                if key in self.model.vr_headers[folder]:
                    for sweep in checked[folder][key]:
                        x = current_df['voltage recording']['Time'][sweep]
                        y = current_df['voltage recording'][key][sweep]
                        curve = pg.PlotDataItem(x, y, pen=pg.hsvColor(0.8, sat=1.0, val=0.8, alpha=0.08))
                        new_vb.addItem(curve)

                        curves.append(curve)

                elif key in self.model.ls_headers[folder]:
                    for sweep in checked[folder][key]:
                        x = current_df['linescan'][key + ' Time'][sweep]
                        y = current_df['linescan'][key][sweep]
                        curve = pg.PlotDataItem(x, y, pen=pg.hsvColor(0.8, sat=1.0, val=0.8, alpha=0.08))
                        new_vb.addItem(curve)

                        curves.append(curve)

                channel = list(checked[folder])[0]
                if channel in self.model.ls_headers[folder]:
                    label = channel
                else:
                    if channel == 'Primary':
                        label = channel + ' (' + current_df['file attributes']['File1']['primary']['unit'] + ')'
                    elif key == 'Secondary':
                        label = channel + ' (' + current_df['file attributes']['File1']['secondary']['unit'] + ')'
                    else:
                        label = channel + ' (V)'

        new_vb.autoRange()

        return curves, label
Example #22
0
    def plot_data_new_axis(self, new_vb):
        checked = self.model.checked_dict
        curves = []
        label = ""
        for folder in checked.keys():
            current_df = self.model.data[folder]

            for key in checked[folder].keys():
                if key in self.model.vr_headers[folder]:
                    for sweep in checked[folder][key]:
                        x = current_df['voltage recording']['Time'][sweep]
                        y = current_df['voltage recording'][key][sweep]
                        curve = pg.PlotDataItem(x, y, pen=pg.hsvColor(0.8, sat=1.0, val=0.8, alpha=0.08))
                        new_vb.addItem(curve)

                        curves.append(curve)

                elif key in self.model.ls_headers[folder]:
                    for sweep in checked[folder][key]:
                        x = current_df['linescan'][key + ' Time'][sweep]
                        y = current_df['linescan'][key][sweep]
                        curve = pg.PlotDataItem(x, y, pen=pg.hsvColor(0.8, sat=1.0, val=0.8, alpha=0.08))
                        new_vb.addItem(curve)

                        curves.append(curve)

                channel = list(checked[folder])[0]
                if channel in self.model.ls_headers[folder]:
                    label = channel
                else:
                    if channel == 'Primary':
                        label = channel + ' (' + current_df['file attributes']['File1']['primary']['unit'] + ')'
                    elif key == 'Secondary':
                        label = channel + ' (' + current_df['file attributes']['File1']['secondary']['unit'] + ')'
                    else:
                        label = channel + ' (V)'

        new_vb.autoRange()

        return curves, label
Example #23
0
    def run_analysis(self):
        times_list, freqs_list, indexes_list, unit = self.get_freq_vals()

        if len(times_list) > 0:
            if self.spike_plot_check.isChecked():
                name = "Plot" + str(self.counter)
                title = name + " - Detected spikes"
                plt = self.plotWidget.addPlot(row=self.counter,
                                              col=0,
                                              name=name,
                                              title=title)
                plt.setXLink(self.current_x_link)

                self.curves[name] = self.plot_data(plt)
                self.add_analysis_plot(plt, name)

                for i, curve in enumerate(self.curves[name]):
                    data = curve.getData()
                    x = data[0]
                    y = data[1]
                    plt.plot(x[indexes_list[i]],
                             y[indexes_list[i]],
                             pen=None,
                             symbolBrush=pg.mkColor('r'),
                             symbolPen=pg.mkPen('r'),
                             symbol="d")

            if self.freq_plot_check.isChecked():
                curves = []
                name = "Plot" + str(self.counter)
                title = name + " - Frequency vs. Time"
                plt = self.plotWidget.addPlot(row=self.counter,
                                              col=0,
                                              name=name,
                                              title=title)
                plt.setXLink(self.current_x_link)

                for i in range(len(times_list)):
                    curve = plt.plot(times_list[i],
                                     freqs_list[i],
                                     pen=pg.hsvColor(0.0,
                                                     sat=0.0,
                                                     val=0.5,
                                                     alpha=0.08))
                    curves.append(curve)

                self.curves[name] = curves
                self.add_analysis_plot(plt, name)

                plt.setLabel('left', unit)

        self.analysis_counter += 1
Example #24
0
	def __init__(self, parent=None):
		self.comm = LLCom("/dev/ttyUSB1", self.update)
		pyqtgraph.setConfigOption('background', 'w') #before loading widget
		super(TelemetryApp, self).__init__(parent)
		uic.loadUi('./telemetry.ui', self)
		#Add sliders
		self.sliders=[]
		for i in range(40):
			#~ slide = QtGui.QSlider(self.frame)
			slide = SequenceSlider(self.frame)
			slide.sequence = i	# for reference
			slide.setOrientation(QtCore.Qt.Vertical)
			slide.setObjectName(("verticalSlider_%d" %(i)))
			self.sliders.append(slide)
		for slider in self.sliders:
			#~ slider.valueChanged.connect(self.sliderchange)
			slider.connect(slider,QtCore.SIGNAL("valueChanged(int)"), self,QtCore.SLOT("valueChangedSlot(int)"))
			slider.setMaximum(255)
			slider.setValue(100)
			self.SequenceSliders.addWidget(slider)
		#set grid
#		self.SequencePlotter.plotItem.showGrid(True, True, 0.7)
		self.bufferSize = 50
		#data store
		self.blade_data = np.zeros(self.bufferSize)
		self.speed_data = np.zeros(self.bufferSize)
		self.x_data = np.zeros(self.bufferSize)
		self.y_data = np.zeros(self.bufferSize)
		#curves
		self.blade_curve = self.SequencePlotter.plot(pen=pyqtgraph.hsvColor(1.0, sat=1.0, val=1.0, alpha=1.0))
		self.speed_curve = self.SequencePlotter.plot(pen=pyqtgraph.hsvColor(0.3, sat=1.0, val=1.0, alpha=1.0))
		self.x_curve = self.SequencePlotter.plot(pen=pyqtgraph.hsvColor(0.8, sat=1.0, val=0.5, alpha=1.0))
		self.y_curve = self.SequencePlotter.plot(pen=pyqtgraph.hsvColor(0.6, sat=1.0, val=1.0, alpha=1.0))
		#vertical follow line
		self.line = self.SequencePlotter.addLine(x=0)
		#self.SequencePlotter.setRange(xRange=[0, self.bufferSize], yRange=[-50, 50])
		self.SequencePlotter.setMouseEnabled(x=False, y=False)
		self.SequencePlotter.setRange(rect=None, xRange=[0, 40], yRange=[-50, 50], padding=0.0, update=True, disableAutoRange=True)
		self.comm.start()
Example #25
0
    def print_data(self, data):
        """ Prints 1D-Data represented in a numpy array.
            Args:
                data: 1D Numpy Array containing values to be displayed.
        """
        self.print_indicator = True  #As soon as there is data we want to print the indicator upon update
        self.plot_item = self.getPlotItem()

        C = pyqtgraph.hsvColor(1)
        pen = pyqtgraph.mkPen(color=C, width=1)

        X = np.arange(len(data))
        self.indicator_min = int(np.nanmin(data))
        self.indicator_max = int(np.nanmax(data))
        self.main_plot = self.plot_item.plot(X, data, pen=pen, clear=True)

        if self.video_model != None:
            pos = int(
                self.video_model.get_pos(datatype=self.model.get_datatype()))
            self.indicator = self.plot_item.plot(
                [pos, pos], [self.indicator_min, self.indicator_max],
                pen=pyqtgraph.mkPen(color=pyqtgraph.hsvColor(2), width=1))
Example #26
0
 def update(self):
     X = self.X
     t1 = time.clock()
     if self.selection.currentText() == "Sine":
         Y = self.sine()
     elif self.selection.currentText() == "Cosine":
         Y = self.cosine()
     C = pyqtgraph.hsvColor(time.time() / 5 % 1, alpha=.5)
     pen = pyqtgraph.mkPen(color=C, width=5)
     self.plotter.plot(X, Y, pen=pen, clear=True)
     print("Update took %.02f ms" % ((time.clock() - t1) * 1000))
     if self.updatcheckbox.isChecked():
         QtCore.QTimer.singleShot(1, self.update)  # QUICKLY repeat
    def update(self):
        input_live = self.lineEditlive.text()
        a = [int(si.get_live_price(input_live))]

        points = 100  # number of data points
        a.append(int(si.get_live_price(input_live)))
        X = a
        # Y = np.sin(np.arange(points) / points * 3 * np.pi + time.time())
        C = pyqtgraph.hsvColor(time.time() / 5 % 1, alpha=.5)
        pen = pyqtgraph.mkPen(color=C, width=5)
        self.test.plot(X, pen=pen, clear=True)
        # print("update took %.02f ms" % ((time.clock() - t1) * 1000))
        if self.test1.isChecked():
            QtCore.QTimer.singleShot(1, self.update)  # QUICKLY repeat
Example #28
0
    def plot_phaseplot(self):
        curves = []
        x_data, y_data = self.get_phaseplot_vals()

        if len(x_data) > 0:
            name = "Plot" + str(self.counter)
            title = name + " - Phase Plot"
            plt = self.plotWidget.addPlot(row=self.counter, col=0, name=name, title=title)
            for i in range(len(x_data)):
                curve = plt.plot(x_data[i], y_data[i], pen=pg.hsvColor(0.0, sat=0.0, val=0.5, alpha=0.08))
                curves.append(curve)

            self.curves[name] = curves
            self.add_analysis_plot(plt, name)
Example #29
0
def wlPen(wl):
    """Return a pen representing the given wavelength"""
    l1 = 400
    l2 = 700
    hue = np.clip(((l2-l1) - (wl-l1)) * 0.8 / (l2-l1), 0, 0.8)
    val = 1.0
    if wl > 700:
        val = 1.0 * (((700-wl)/700.) + 1)
    elif wl < 400:
        val = wl * 1.0/400.
    #print hue, val
    color = pg.hsvColor(hue, 1.0, val)
    pen = pg.mkPen(color)
    return pen
Example #30
0
def wlPen(wl):
    """Return a pen representing the given wavelength"""
    l1 = 400
    l2 = 700
    hue = np.clip(((l2-l1) - (wl-l1)) * 0.8 / (l2-l1), 0, 0.8)
    val = 1.0
    if wl > 700:
        val = 1.0 * (((700-wl)/700.) + 1)
    elif wl < 400:
        val = wl * 1.0/400.
    #print hue, val
    color = pg.hsvColor(hue, 1.0, val)
    pen = pg.mkPen(color)
    return pen
Example #31
0
    def setVoltages(self):
        a = 1.0
        h = a * np.sqrt(3) / 2
        self.electrodeCoordinates = [[-3 * a / 2, 3 * h], [-a / 2, 3 * h],
                                     [a / 2, 3 * h], [3 * a / 2, 3 * h],
                                     [-2 * a, 2 * h], [-a, 2 * h], [0, 2 * h],
                                     [a, 2 * h], [2 * a, 2 * h],
                                     [-5 * a / 2, h], [-3 * a / 2, h],
                                     [-a / 2, h], [a / 2, h], [3 * a / 2, h],
                                     [5 * a / 2, h], [-3 * a, 0], [-2 * a, 0],
                                     [-a, 0], [0, 0], [a, 0], [2 * a, 0],
                                     [3 * a, 0], [-5 * a / 2, -h],
                                     [-3 * a / 2, -h], [-a / 2, -h],
                                     [a / 2, -h], [3 * a / 2, -h],
                                     [5 * a / 2, -h], [-2 * a, -2 * h],
                                     [-a, -2 * h], [0, -2 * h], [a, -2 * h],
                                     [2 * a, -2 * h], [-3 * a / 2, -3 * h],
                                     [-a / 2, -3 * h], [a / 2, -3 * h],
                                     [3 * a / 2, -3 * h]]
        self.electrodeCoordinates = np.array(self.electrodeCoordinates)

        spots = []
        for i in range(0, 37):
            attr_name = 'channel' + str(i)
            self.adDevice.write_attribute(
                attr_name, self.voltageSliders[i].value() / 73.0)
            self.voltageIndicators[i].setText("{:.2f}".format(
                self.voltageSliders[i].value()))
            #spots.append({'pos': self.electrodeCoordinates[i,:], 'data': 1, 'brush':pq.intColor(np.round(self.voltageSliders[i].value())), 'symbol': 'o', 'size': 50})
            spots.append({
                'pos':
                self.electrodeCoordinates[i, :],
                'data':
                1,
                'brush':
                pq.hsvColor(self.voltageSliders[i].value() /
                            (self.maxVoltage * 5.5),
                            sat=1.0,
                            val=1.0,
                            alpha=1.0),
                'symbol':
                'o',
                'size':
                40
            })
            #spots.append({'pos': self.electrodeCoordinates[i,:], 'data': 1, 'brush':self.map.map(self.voltageSliders[i].value(),mode='qcolor'), 'symbol': 'o', 'size': 40})

        self.plot11.addPoints(spots)
Example #32
0
    def setup_range(self):
        self.win = np.hanning(self.bins)
        
        FS = self.sampling_rate

        #num_bars = int(round((self.bins - 1) * (self.hi - self.lo) / FS))
        num_bars = len(np.zeros(self.bins)[self.lo: self.hi])

        #print 'num_bars', num_bars, self.bins * (self.hi - self.lo) / FS

        x = np.linspace(self.lo, self.hi, num_bars)

        self.bars = pg.BarGraphItem(x=x, height=range(num_bars), width=1.0)
        
        self.bars.setOpts(brushes=[pg.hsvColor(float(x) / num_bars) for x in range(num_bars)])
        self.plot.addItem(self.bars)
Example #33
0
 def update(self):
     if(len(ExampleApp.X) > 500):
         ExampleApp.X = ExampleApp.X[len(ExampleApp.X)-499:]
         ExampleApp.Y_x = ExampleApp.Y_x[len(ExampleApp.Y_x)-499:]
     ExampleApp.count = ExampleApp.count + 1
     t1=time.clock()
     data = udp.update()
     print(data)
     ExampleApp.X = np.append(ExampleApp.X,ExampleApp.count)
     ExampleApp.Y_x = np.append(ExampleApp.Y_x,float(data))
     C=pyqtgraph.hsvColor(0,alpha=1)
     pen=pyqtgraph.mkPen(color=C,width=2)
     self.grPlot.plot(ExampleApp.X,ExampleApp.Y_x,pen=pen,clear=True)
     print("update took %.02f ms"%((time.clock()-t1)*1000))
     if self.chkMore.isChecked():
         QtCore.QTimer.singleShot(1, self.update) # QUICKLY repeat
Example #34
0
    def print_data(self, data):
        """ Prints data to dataplot
            Args:
                data: 2d float.64 numpy arrays containing values between 0 and 1
        """
        self.print_indicator = True
        self.imagedata = data
        self.setImage(self.imagedata)

        self.indicator_min = -200
        self.indicator_max = 200

        if self.video_model != None:
            pos = int(self.video_model.get_pos(datatype="motion"))
            self.indicator = self.view.plot(
                [pos, pos], [self.indicator_min, self.indicator_max],
                pen=pyqtgraph.mkPen(color=pyqtgraph.hsvColor(2), width=1))
    def __init__(self, parent=None):
    
        self.port = "/dev/ttyACM0"
        self.baudrate = 19200
        self.parity = serial.PARITY_NONE
        self.stopbits = serial.STOPBITS_ONE
        self.bytesize = serial.EIGHTBITS
        self.timeout = 1
        self.ser = None
        
        #self.connect_to_pump()

        self.port2 = "/dev/ttyUSB0"
        self.baudrate2 = 115200
        self.parity2 = serial.PARITY_NONE
        self.stopbits2 = serial.STOPBITS_ONE
        self.bytesize2 = serial.EIGHTBITS
        self.timeout2 = 0.001
        self.ser2 = None
        
        self.connect_to_datalogger()
        pyqtgraph.setConfigOption('background', 'w') #before loading widget
        super(ExampleApp, self).__init__(parent)
        self.setupUi(self)
        self.startButton.clicked.connect(self.start_test)
        self.stopButton.clicked.connect(self.stop_test)
        self.newButton.clicked.connect(self.new_test)
        self.StartPumpButton.clicked.connect(self.start_pump)
        self.StopPumpButton.clicked.connect(self.stop_pump)
        
        self.pressure_graph.plotItem.showGrid(True, True, 0.7)
        self.force_graph.plotItem.showGrid(True, True, 0.7)
        self.displacement_graph.plotItem.showGrid(True, True, 0.7)
        self.color = pyqtgraph.hsvColor(0.38,0.92,0.47,alpha=.5)
        self.pen = pyqtgraph.mkPen(color=self.color,width=10)
        self.num_points = 100
        self.X = np.arange(self.num_points)
        self.pressure = deque([0.0]*self.num_points)
        self.force = deque([0.0]*self.num_points)
        self.displacement = deque([0.0]*self.num_points)
        self.filename = None
        self.plainTextEdit.appendPlainText('No filename')
        
        self.test = False
        self.pump_running = False
Example #36
0
    def update(self):
        mutex.lock()
        global dataHighSpeed
        tempData = dataHighSpeed.readData()
        mutex.unlock()

        tempData = tempData * (5.0 / 1023.0) - average_Voltage
        self.yBuffer.writeData(tempData)
        C = pyqtgraph.hsvColor(hue=0, sat=0.9, val=1, alpha=0.7)
        pen = pyqtgraph.mkPen(color=C, width=4)
        self.grPlot.plot(self.X[:200],
                         self.yBuffer.theWholeRolledTruth()[:self.bufferSize -
                                                            200 - 1:-1],
                         pen=pen,
                         clear=True)
        QtCore.QTimer.singleShot(
            100, self.update
        )  # DO NOT LOWER THIS OR IT WILL CRASH! THIS IS A MAGIC NUMBER! You can increase it though.
Example #37
0
    def run_analysis(self):
        times_list, freqs_list, indexes_list, unit = self.get_freq_vals()

        if len(times_list) > 0:
            if self.spike_plot_check.isChecked():
                name = "Plot" + str(self.counter)
                title = name + " - Detected spikes"
                plt = self.plotWidget.addPlot(row=self.counter, col=0, name=name, title=title)
                plt.setXLink(self.current_x_link)

                self.curves[name] = self.plot_data(plt)
                self.add_analysis_plot(plt, name)

                for i, curve in enumerate(self.curves[name]):
                    data = curve.getData()
                    x = data[0]
                    y = data[1]
                    plt.plot(
                        x[indexes_list[i]],
                        y[indexes_list[i]],
                        pen=None,
                        symbolBrush=pg.mkColor("r"),
                        symbolPen=pg.mkPen("r"),
                        symbol="d",
                    )

            if self.freq_plot_check.isChecked():
                curves = []
                name = "Plot" + str(self.counter)
                title = name + " - Frequency vs. Time"
                plt = self.plotWidget.addPlot(row=self.counter, col=0, name=name, title=title)
                plt.setXLink(self.current_x_link)

                for i in range(len(times_list)):
                    curve = plt.plot(times_list[i], freqs_list[i], pen=pg.hsvColor(0.0, sat=0.0, val=0.5, alpha=0.08))
                    curves.append(curve)

                self.curves[name] = curves
                self.add_analysis_plot(plt, name)

                plt.setLabel("left", unit)

        self.analysis_counter += 1
Example #38
0
    def average_plots(self):
        choice_index = self.avg_option_dropdown.currentIndex()
        try:
            if any(self.curves[self.current_selected]):
                if choice_index == 0:
                    x_data, y_data = self.get_average_data()
                    self.plot_objects[self.current_selected].clearPlots()
                    curve = self.plot_objects[self.current_selected].plot(x=x_data, y=y_data, pen=pg.mkPen('r'))
                    self.curves[self.current_selected] = [curve, ]

                elif choice_index == 1:
                    self.add_new_plot(average_plot=True)

                elif choice_index == 2:
                    x_data, y_data = self.get_average_data()
                    self.selected_curve[self.current_selected].setPen(pg.hsvColor(0.0, sat=0.0, val=0.5, alpha=0.08))
                    curve = self.plot_objects[self.current_selected].plot(x=x_data, y=y_data, pen=pg.mkPen('r'))
                    self.curves[self.current_selected] = [curve, ]
        except KeyError:
            pass
Example #39
0
    def init(self, lo=0, hi=125, bins=256, yrange=750, ratio=False):
        self.widget = pg.PlotWidget()
        self.widget.setLabel('bottom', 'Frequency', units='Hz')

        self.bars = pg.BarGraphItem()

        self.win = np.hanning(bins)
        self.win = np.blackman(bins)
        #self.win = np.ones(bins)
        self.lo, self.hi = lo, hi
        self.ratio = ratio
        
        FS = self.input.sample_rate

        self.gr_block.set_history(bins)

        #num_bars = int(round((self.bins - 1) * (self.hi - self.lo) / FS))
        # This is total bullshit:
        num_bars = len(np.zeros(bins)[lo: hi])

        x = np.linspace(self.lo, self.hi, num_bars)

        self.bars = pg.BarGraphItem(x=x, height=range(num_bars), width=1.0)
        
        self.bars.setOpts(brushes=[pg.hsvColor(float(x) / num_bars) for x in range(num_bars)])
        self.widget.addItem(self.bars)

        # TODO: Better autoranging features
        #self.plot.enableAutoRange('xy', False)
        
        self.widget.setYRange(0, yrange)
        self.widget.enableAutoRange('y', 0.95)

        self.buffer = np.zeros(bins)

        self.timer = pg.QtCore.QTimer()
        self.timer.timeout.connect(self.updateGUI)
        self.timer.start(10)
            ind_plot[f, c].plot(ind_rec_grand_trace.time_values, ind_rec_grand_trace.data, pen={'color': color, 'width': 2})
            ind_plot[f, c].setLabels(left=('Vm', 'V'))
            ind_plot[f, c].setLabels(bottom=('t', 's'))
            if deconv is True:
                ind_deconv = deconv_train(ind_pass_qc[:2])
                ind_deconv_grand = TraceList(ind_deconv[0]).mean()
                ind_rec_deconv_grand = TraceList(ind_deconv[1]).mean()
                [deconv_ind_plot[f, c].plot(ind.time_values, ind.data, pen=trace_color) for ind in ind_deconv[0]]
                [deconv_ind_plot[f, c].plot(rec.time_values, rec.data, pen=trace_color) for rec in ind_deconv[1]]
                deconv_ind_plot[f, c].plot(ind_deconv_grand.time_values, ind_deconv_grand.data,
                                    pen={'color': color, 'width': 2}, name=("n = %d" % n_synapses))
                deconv_ind_plot[f, c].plot(ind_rec_deconv_grand.time_values, ind_rec_deconv_grand.data,
                                pen={'color': color, 'width': 2})
            summary_plot[c, 0].setLabels(left=('Norm Amp', ''))
            summary_plot[c, 0].setLabels(bottom=('Pulse Number', ''))
            f_color = pg.hsvColor(hue=hue, sat=float(f+0.5)/len(freqs), val=1)
            summary_plot[c, 0].plot(ind_amp_grand/ind_amp_grand[0], name=('  %d Hz' % freq), pen=f_color, symbol=symbols[f],
                                symbolBrush=f_color, symbolPen=None)
            if connection_types[c] not in ind_amp_summary.keys():
                ind_amp_summary[connection_types[c]] = []
                ind_uid[connection_types[c]] = []
            ind_amp_summary[connection_types[c]].append([freq, ind_amp])
            ind_uid[connection_types[c]].append([freq, ind_pass_qc[2]])

    for t, delta in enumerate(rec_t):
        if delta not in recovery_grand.keys():
            print ("%d ms not represented in data set for %s" % (delta, c_type))
            continue
        rec_offsets = pulse_offset_rec[delta]
        rec_pass_qc = train_qc(recovery_grand[delta], rec_offsets, amp=qc_params[1][c], sign=qc_params[0], plot=None)
        n_synapses = len(rec_pass_qc[0])
Example #41
0
    def plot_ratio_new_axis(self, new_vb):
        checked = self.model.checked_dict

        curves = []
        label = ""

        for folder in checked.keys():
            current_df = self.model.data[folder]

            if self.model.profile_ratio:
                profile_a = self.model.profile_a
                profile_b = self.model.profile_b
                label = profile_a + '/' + profile_b

                try:
                    if len(checked[folder][profile_a]) != len(checked[folder][profile_b]):
                        QtGui.QMessageBox.about(self, "Error",
                                                "Number of selected sweeps must be equal for each profile")
                        return "error"
                    else:
                        for sweep in checked[folder][profile_a]:
                            x = current_df['linescan'][profile_a + ' Time'][sweep]
                            y = current_df['linescan'][profile_a][sweep] / current_df['linescan'][profile_b][sweep]
                            curve = pg.PlotDataItem(x, y, pen=pg.hsvColor(0.0, sat=0.0, val=0.5, alpha=0.08))
                            new_vb.addItem(curve)
                            curves.append(curve)
                except KeyError as e:
                    QtGui.QMessageBox.about(self, "Error", "No sweeps for %s selected" % e)
                    return "error"

            else:
                label = 'F/F0'

                if self.model.f0_from_txt:
                    try:
                        f0 = float(self.model.f0_txt)
                        if self.model.f0_eq1:
                            for key in checked[folder].keys():
                                if key in self.model.ls_headers[folder]:
                                    for sweep in checked[folder][key]:
                                        x = current_df['linescan'][key + ' Time'][sweep]
                                        y = (current_df['linescan'][key][sweep] - f0) / f0
                                        curve = pg.PlotDataItem(x, y, pen=pg.hsvColor(0.0, sat=0.0, val=0.5, alpha=0.08))
                                        new_vb.addItem(curve)
                                        curves.append(curve)
                        else:
                            for key in checked[folder].keys():
                                if key in self.model.ls_headers[folder]:
                                    for sweep in checked[folder][key]:
                                        x = current_df['linescan'][key + ' Time'][sweep]
                                        y = current_df['linescan'][key][sweep] / f0
                                        curve = pg.PlotDataItem(x, y, pen=pg.hsvColor(0.0, sat=0.0, val=0.5, alpha=0.08))
                                        new_vb.addItem(curve)
                                        curves.append(curve)
                    except ValueError:
                        QtGui.QMessageBox.about(self, "Error", "F0 must be a numeric value")
                        return "error"
                else:
                    try:
                        index1 = self.get_marker_vals(self.plot_markers[self.current_selected]["Marker One"],
                                                      get_index=True)
                        index2 = self.get_marker_vals(self.plot_markers[self.current_selected]["Marker Two"],
                                                      get_index=True)

                        if self.model.f0_eq1:
                            for key in checked[folder].keys():
                                if key in self.model.ls_headers[folder]:
                                    for sweep in checked[folder][key]:
                                        if index1 < index2:
                                            f0 = current_df['linescan'][key][sweep][index1:index2].mean()
                                        elif index2 < index1:
                                            f0 = current_df['linescan'][key][sweep][index2:index1].mean()
                                        else:
                                            print(index1, index2)
                                            QtGui.QMessageBox.about(self, "Error", "Baseline region is 0\n"
                                                                    "Set baseline region with markers")
                                            return "error"

                                        x = current_df['linescan'][key + ' Time'][sweep]
                                        y = (current_df['linescan'][key][sweep] - f0) / f0
                                        curve = pg.PlotDataItem(x, y, pen=pg.hsvColor(0.0, sat=0.0, val=0.5, alpha=0.08))
                                        new_vb.addItem(curve)
                                        curves.append(curve)
                        else:
                            for key in checked[folder].keys():
                                if key in self.model.ls_headers[folder]:
                                    for sweep in checked[folder][key]:
                                        if index1 < index2:
                                            f0 = current_df['linescan'][key][sweep][index1:index2].mean()
                                        elif index2 < index1:
                                            f0 = current_df['linescan'][key][sweep][index2:index1].mean()
                                        else:
                                            QtGui.QMessageBox.about(self, "Error", "Baseline region is 0\n"
                                                                    "Set baseline region with markers")
                                            return "error"

                                        x = current_df['linescan'][key + ' Time'][sweep]
                                        y = current_df['linescan'][key][sweep] / f0
                                        curve = pg.PlotDataItem(x, y, pen=pg.hsvColor(0.0, sat=0.0, val=0.5, alpha=0.08))
                                        new_vb.addItem(curve)
                                        curves.append(curve)
                    except KeyError:
                        QtGui.QMessageBox.about(self, "Error", "Add markers to %s to set F0 region"
                                                % self.current_selected)
                        return "error"

        new_vb.autoRange()

        return curves, label
Example #42
0
    def keyPressEvent(self, event):
        key = event.key()

        try:
            all_curves = self.curves[self.current_selected] + self.axis2_curves[self.current_selected]
            selected_index = self.current_curve_index[self.current_selected]

            if key == QtCore.Qt.Key_Up or key == QtCore.Qt.Key_Left:
                try:
                    if selected_index-1 >= 0:
                        new_selected_curve = all_curves[selected_index-1]

                        if new_selected_curve in self.curves[self.current_selected]:
                            new_selected_curve.setPen(pg.mkPen('b'))

                        elif new_selected_curve in self.axis2_curves[self.current_selected]:
                            new_selected_curve.setPen(pg.hsvColor(0.8, sat=1.0, val=0.8, alpha=1.0))

                        if self.selected_curve[self.current_selected] in self.curves[self.current_selected]:
                            self.selected_curve[self.current_selected].setPen(pg.hsvColor(0.0, sat=0.0, val=0.5,
                                                                                          alpha=0.08))

                        elif self.selected_curve[self.current_selected] in self.axis2_curves[self.current_selected]:
                            self.selected_curve[self.current_selected].setPen(pg.hsvColor(0.8, sat=1.0, val=0.8,
                                                                                          alpha=0.08))
                        #if new_selected_curve == self.curves[self.current_selected][-1]:
                            #self.axis2_curves[self.current_selected][0].setPen(pg.hsvColor(0.8, sat=1.0, val=0.8, alpha=1.0))

                        self.selected_curve[self.current_selected] = new_selected_curve
                        self.current_curve_index[self.current_selected] -= 1
                except IndexError:
                    pass

                try:
                    self.update_marker_vals(self.plot_markers[self.current_selected]["Marker One"], "Marker One",
                                            self.plot_marker_labels[self.current_selected]["Label One"])
                    self.update_marker_vals(self.plot_markers[self.current_selected]["Marker Two"], "Marker Two",
                                            self.plot_marker_labels[self.current_selected]["Label Two"])
                except KeyError:
                    pass

            elif key == QtCore.Qt.Key_Down or key == QtCore.Qt.Key_Right:
                try:
                    if selected_index+1 < len(all_curves):
                        new_selected_curve = all_curves[selected_index+1]

                        if new_selected_curve in self.curves[self.current_selected]:
                            new_selected_curve.setPen(pg.mkPen('b'))

                        elif new_selected_curve in self.axis2_curves[self.current_selected]:
                            new_selected_curve.setPen(pg.hsvColor(0.8, sat=1.0, val=0.8, alpha=1.0))

                        if self.selected_curve[self.current_selected] in self.curves[self.current_selected]:
                            self.selected_curve[self.current_selected].setPen(pg.hsvColor(0.0, sat=0.0, val=0.5,
                                                                                      alpha=0.08))

                        elif self.selected_curve[self.current_selected] in self.axis2_curves[self.current_selected]:
                            self.selected_curve[self.current_selected].setPen(pen=pg.hsvColor(0.8, sat=1.0, val=0.8,
                                                                                              alpha=0.08))
                        #if new_selected_curve == self.axis2_curves[self.current_selected][0]:
                            #self.curves[self.current_selected][-1].setPen(pg.mkPen('b'))

                        self.selected_curve[self.current_selected] = new_selected_curve
                        self.current_curve_index[self.current_selected] += 1
                except IndexError:
                    pass

                try:
                    self.update_marker_vals(self.plot_markers[self.current_selected]["Marker One"], "Marker One",
                                            self.plot_marker_labels[self.current_selected]["Label One"])
                    self.update_marker_vals(self.plot_markers[self.current_selected]["Marker Two"], "Marker Two",
                                            self.plot_marker_labels[self.current_selected]["Label Two"])
                except KeyError:
                    pass

        except KeyError:
            pass