Пример #1
0
 def create_marker(self, marker_type, value=None):
     slider = pg.InfiniteLine(pos=0.2,
                              movable=True,
                              label='',
                              labelOpts={
                                  'position': 0.5,
                                  'rotateAxis': (1, 0),
                                  'anchor': (1, 1)
                              })
     slider.sigPositionChangeFinished.connect(
         lambda: self.perform_calculations(save=True))
     if value:
         slider.setValue(value)
     if marker_type == 'notch_rest':
         slider.label = pg.InfLineLabel(slider, text="Dicrotic notch")
         self.plot_ensemble_rest.addItem(slider)
         self.slider_notch_rest = slider
     elif marker_type == 'notch_hyp':
         slider.label = pg.InfLineLabel(slider, text="Dicrotic notch")
         self.plot_ensemble_hyp.addItem(slider)
         self.slider_notch_hyp = slider
     elif marker_type == 'enddiastole_rest':
         slider.label = pg.InfLineLabel(slider, text="End diastole")
         self.plot_ensemble_rest.addItem(slider)
         self.slider_enddiastole_rest = slider
     elif marker_type == 'enddiastole_hyp':
         slider.label = pg.InfLineLabel(slider, text="End diastole")
         self.plot_ensemble_hyp.addItem(slider)
         self.slider_enddiastole_hyp = slider
     else:
         raise ValueError(f"Unknown button type pressed: {marker_type}")
Пример #2
0
    def _setup_plot(self):

        # Get plot item and setup
        self.plt = self.getPlotItem()
        self.plt.setDownsampling(auto=True)
        self.plt.setTitle(
            type(self).
            __name__ if self.daq_device is None else type(self).__name__ +
            ' ' + self.daq_device)
        self.plt.setLabel('left', text='Proton fluence', units='cm^-2')
        self.plt.setLabel('right', text='Neutron fluence', units='cm^-2')
        self.plt.setLabel('bottom', text='Scan row')
        self.plt.getAxis('right').setScale(self.irrad_setup['kappa'])
        self.plt.getAxis('left').enableAutoSIPrefix(False)
        self.plt.getAxis('right').enableAutoSIPrefix(False)
        self.plt.setLimits(xMin=0, xMax=self.irrad_setup['n_rows'], yMin=0)
        self.legend = pg.LegendItem(offset=(80, 80))
        self.legend.setParentItem(self.plt)

        # Histogram of fluence per row
        hist_curve = pg.PlotCurveItem()
        hist_curve.setFillLevel(0.33)
        hist_curve.setBrush(pg.mkBrush(color=_MPL_COLORS[0]))

        # Points at respective row positions
        hist_points = pg.ScatterPlotItem()
        hist_points.setPen(color=_MPL_COLORS[2], style=pg.QtCore.Qt.SolidLine)
        hist_points.setBrush(color=_MPL_COLORS[2])
        hist_points.setSymbol('o')
        hist_points.setSize(10)

        # Errorbars for points; needs to initialized with x, y args, otherwise cnnot be added to PlotItem
        hist_errors = pg.ErrorBarItem(x=np.arange(1),
                                      y=np.arange(1),
                                      beam=0.25)

        # Horizontal line indication the mean fluence over all rows
        mean_curve = pg.InfiniteLine(angle=0)
        mean_curve.setPen(color=_MPL_COLORS[1], width=2)
        self.p_label = pg.InfLineLabel(mean_curve, position=0.2)
        self.n_label = pg.InfLineLabel(mean_curve, position=0.8)

        self.curves = OrderedDict([('hist', hist_curve),
                                   ('hist_points', hist_points),
                                   ('hist_errors', hist_errors),
                                   ('mean', mean_curve)])

        # Show data and legend
        for curve in self.curves:
            self.show_data(curve)
Пример #3
0
    def update_order(self, order: OrderData):
        if order.status in (Status.NOTTRADED, Status.PARTTRADED):
            line = self.order_lines[order.vt_orderid]
            candle_plot = self.get_plot("candle")

            if line not in candle_plot.items:
                candle_plot.addItem(line)

            line.setAngle(0)
            line.label = pg.InfLineLabel(
                line,
                text=
                f'{order.type.value}:{"↑" if order.direction == Direction.LONG else "↓"}{order.volume - order.traded}@{order.price}',
                color='r' if order.direction == Direction.LONG else 'g')
            line.setPen(
                pg.mkPen(color=UP_COLOR
                         if order.direction == Direction.LONG else DOWN_COLOR,
                         width=PEN_WIDTH))
            line.setHoverPen(
                pg.mkPen(color=UP_COLOR
                         if order.direction == Direction.LONG else DOWN_COLOR,
                         width=PEN_WIDTH * 2))
            line.setPos(order.price)

        elif order.status in (Status.ALLTRADED, Status.CANCELLED,
                              Status.REJECTED):
            if order.vt_orderid in self.order_lines:
                line = self.order_lines[order.vt_orderid]
                candle_plot = self.get_plot("candle")
                candle_plot.removeItem(line)
Пример #4
0
    def createPlot(self):
        self.date_axis = CAxisTime(orientation='bottom')
        self.plot = self.plotWidget.addPlot(row=0, col=0)
        self.plot.mouseOver = False
        self.plot.scene().installEventFilter(self)

        nontimeaxisItems = {
            'bottom': self.plot.axes['bottom']['item'],
            'top': self.plot.axes['top']['item'],
            'left': self.plot.axes['left']['item'],
            'right': self.plot.axes['right']['item']
        }
        axisItems = {
            'bottom': self.date_axis,
            'top': self.plot.axes['top']['item'],
            'left': self.plot.axes['left']['item'],
            'right': self.plot.axes['right']['item']
        }
        self.plot.axes = {}
        for k, pos in (('top', (1, 1)), ('bottom', (3, 1)), ('left', (2, 0)),
                       ('right', (2, 2))):
            if k in axisItems:
                axis = axisItems[k]
                axis.linkToView(self.plot.vb)
                self.plot.axes[k] = {'item': axis, 'pos': pos}
                self.plot.layout.removeItem(self.plot.layout.itemAt(*pos))
                self.plot.layout.addItem(axis, *pos)
                axis.setZValue(-1000)
                axis.setFlag(axis.ItemNegativeZStacksBehindParent)
        self.plot.showGrid(x=True, y=True)
        ''' Here we create the two lines that form the crosshairs '''
        self.vLine = pg.InfiniteLine(angle=90,
                                     movable=False,
                                     pen=pg.mkPen('r'))
        self.vLine.setZValue(1000)
        self.hLine = pg.InfiniteLine(angle=0, movable=False, pen=pg.mkPen('r'))
        self.hLine.setZValue(1000)
        ''' this is a lina label for the vertical crosshair line. We modify the horizontal position in the signal functions '''
        self.hvLineText = pg.InfLineLabel(self.vLine,
                                          color='r',
                                          fill=(200, 200, 200, 130))
        self.hvLineText.setZValue(1000)
        self.plot.addItem(self.vLine, ignoreBounds=True)
        self.plot.addItem(self.hLine, ignoreBounds=True)
        self.plot.addItem(self.hvLineText, ignoreBounds=True)
        ''' define some parameters and instantiate the crosshair signals. We change the crosshairs whenever the sigMouseMoved is triggered,
        whilst we must update the vertical axis if the plot autoscales, and also we must also update the horizontal axis if the time changes under the crosshairs'''
        self.vb = self.plot.vb
        self.mousePos = QtCore.QPointF(0.01, 0.01)
        self.proxyMouseMoved = pg.SignalProxy(self.plot.scene().sigMouseMoved,
                                              rateLimit=20,
                                              slot=self.mouseMoved)
        self.proxyAxisChanged = pg.SignalProxy(self.plot.vb.sigYRangeChanged,
                                               rateLimit=20,
                                               slot=self.axisChanged)
        self.proxyTimeChanged = pg.SignalProxy(self.plotUpdated,
                                               rateLimit=20,
                                               slot=self.timeAxisChanged)
        return self.plot
Пример #5
0
 def __init__(self, values, movable, label):
     super(LabelledLinearRegionItem, self).__init__(values=values,
                                                    movable=movable)
     self.label = pg.InfLineLabel(self.lines[1],
                                  label,
                                  position=0.3,
                                  rotateAxis=(1, 0),
                                  anchor=(1, 1))
Пример #6
0
    def xctl_graph_init(self, parent: PlotWidget, xName, data: list):
        self.graph_init(parent, [f'{xName} Duty', '%'], ["Temperature", '°C'])

        pen = pg.mkPen('w', width=0.2, style=QtCore.Qt.DashLine)
        xline = pg.InfiniteLine(pos=0, pen=pen, name="currTemp", angle=270)
        yline = pg.InfiniteLine(pos=0, pen=pen, name=f"curr{xName}", angle=0)

        pg.InfLineLabel(xline,
                        text="{value}°C",
                        position=0.04,
                        rotateAxis=(0, 0))
        pg.InfLineLabel(yline, text="{value}%", position=0, rotateAxis=(0, 0))

        graph = EditableGraph(parent, data=data)

        parent.addItem(graph)
        parent.addItem(xline)
        parent.addItem(yline)
Пример #7
0
    def add_segment(self, onset, offset, region_typeindex, brush=None, pen=None, movable=True, text=None):
        region = SegmentItem((onset, offset), region_typeindex, self.xrange,
                             time_bounds=(onset, offset), brush=brush, pen=pen, movable=movable)
        if text is not None:
            pg.InfLineLabel(region.lines[1], text, position=0.95, rotateAxis=(1,0), anchor=(1, 1))

        self.addItem(region)
        self.old_items.append(region)
        if movable:
            region.sigRegionChangeFinished.connect(self.m.on_region_change_finished)
Пример #8
0
    def add_event(self, xx, event_type, pen, movable=False, text=None):
        if not len(xx):
            return

        for x in xx:
            line = EventItem(x, event_type, self.xrange, movable=True, angle=90, pen=pen)
            if text is not None:
                pg.InfLineLabel(line, text, position=0.95, rotateAxis=(1, 0), anchor=(1, 1))
            line.sigPositionChangeFinished.connect(self.m.on_position_change_finished)
            self.addItem(line)
Пример #9
0
    def resolveConnections(self):
        super().resolveConnections()

        timeplot = self.parent.addons["xy"].plt
        specplot = self.parent.addons["spec"].plt
        df = self.parent.df
        R = pg.LinearRegionItem()
        R.lines[0].label = pg.InfLineLabel(R.lines[0],
                                           text="FFT",
                                           position=.95,
                                           movable=False)
        #R.lines[1].label = pg.InfLineLabel(R.lines[1],text="FFT",position=.95,movable=False)
        R.setZValue(10)
        t0 = df.index[0]
        t1 = df.index[-1]
        dt = t1 - t0
        R.setRegion([t0 + dt / 3, t1 - dt / 3])
        R.sigRegionChanged.connect(self.updateFFTRegion)
        timeplot.addItem(R)
        self.FFTregion = R
        self.FFTregion.setVisible(not self.startHidden)

        R2 = pg.LinearRegionItem()
        R2.lines[0].label = pg.InfLineLabel(R2.lines[0],
                                            text="FFT",
                                            position=.95,
                                            movable=False)
        R2.setZValue(10)
        t0 = df.index[0]
        t1 = df.index[-1]
        dt = t1 - t0
        R2.setRegion([t0 + dt / 3, t1 - dt / 3])
        specplot.addItem(R2)
        self.specregion = R2
        self.specregion.setVisible(not self.startHidden)

        R.sigRegionChanged.connect(self.updateR2)
        R2.sigRegionChanged.connect(self.updateR1)
 def add_wavelength_marker(self):
     self.wavelength_marker = pg.InfiniteLine(
         self.central_wavelength,
         movable=True,
         bounds=[self.wavelengths[0], self.wavelengths[-1]])
     self.ui.a_spectrum_graph.addItem(self.wavelength_marker)
     self.wavelength_marker.sigPositionChangeFinished.connect(
         self.update_kinetics_wavelength)
     self.wavelength_marker_label = pg.InfLineLabel(self.wavelength_marker,
                                                    text='{value:.2f}nm',
                                                    movable=True,
                                                    position=0.9)
     self.update_kinetics_wavelength()
     return
 def add_time_marker(self):
     self.time_marker = pg.InfiniteLine(
         self.times[int(len(self.times) / 2)],
         movable=True,
         bounds=[min(self.times), max(self.times)])
     self.ui.a_kinetics_graph.addItem(self.time_marker)
     self.time_marker.sigPositionChangeFinished.connect(
         self.update_time_pixel)
     self.time_marker_label = pg.InfLineLabel(self.time_marker,
                                              text='{value:.2f}ps',
                                              movable=True,
                                              position=0.9)
     self.update_time_pixel()
     return
Пример #12
0
    def start_clicked(self):

        global data, ECGdata, GSRdata

        #RT variables for simulating streaming
        global RTStreamTIME, RTStreamECG, RTStreamGSR, RTStreamEVENTS

        # Real Time mode
        if self.rtMode.isChecked() == True:
            # The data that will be used to simulate streaming is loaded
            #if ((RTStreamTIME != []) and (RTStreamECG != []) and (RTStreamGSR != []) and (RTStreamEVENTS != [])):
            print('started')
            self.timer = pg.QtCore.QTimer()
            self.timer.timeout.connect(lambda: RTupdate(self))
            self.timer.start(5)

        #Or:
        else:
            # system is on static test mode #
            if ((ECGdata != []) and (GSRdata != [])):
                # both GSR & ECG files has been loaded
                data = [GSRdata, ECGdata]
                p1 = self.modDataView.addPlot(x=times[1],
                                              y=data[1],
                                              pen=(1, 2))
                p2 = pg.PlotCurveItem(x=times[0], y=data[0], pen=(0, 2))
                p1.addItem(p2)
                for i in range(len(blocks)):
                    #     # add the network workeloads predictons of each data block to the graphic view
                    blockStart = blocks[i][0]
                    blockEnd = blocks[i][1]
                    level = predictBlock(GSRdata[blocks[i][0]:blocks[i][1]],
                                         ECGdata[blocks[i][0]:blocks[i][1]])
                    lr = pg.LinearRegionItem(values=[blockStart, blockEnd],
                                             brush=pg.intColor(index=level,
                                                               alpha=50),
                                             movable=False)
                    p1.addItem(lr)
                    label = pg.InfLineLabel(lr.lines[1],
                                            "oveload " + str(level),
                                            position=0.85,
                                            rotateAxis=(1, 0),
                                            anchor=(1, 1))

            else:
                # either GSR or ECG files has not been loaded
                print('error')
    def add_qtn_marker(self, start, stop, label):
        self.brt_qtn_reg.append(
            pg.LinearRegionItem(values=[start, stop], movable=False))

        self.gsr_qtn_reg.append(
            pg.LinearRegionItem(values=[start, stop], movable=False))
        pg.InfLineLabel(self.gsr_qtn_reg[self.num_qtns].lines[1],
                        label,
                        position=0.5,
                        rotateAxis=(1, 0))

        self.hrt_qtn_reg.append(
            pg.LinearRegionItem(values=[start, stop], movable=False))

        self.brt_plot.addItem(self.brt_qtn_reg[self.num_qtns])
        self.gsr_plot.addItem(self.gsr_qtn_reg[self.num_qtns])
        self.hrt_plot.addItem(self.hrt_qtn_reg[self.num_qtns])

        self.num_qtns += 1
Пример #14
0
def detPredBar(parent):
    parent.getPlaytimeChanged = partial(getPlaytimeChanged, parent)

    #window
    #pg.setConfigOption('background','#303030')
    parent.win = pg.GraphicsLayoutWidget(parent=parent)
    parent.win.setGeometry(0, 0,
                           parent.geometry().width() + 2,
                           parent.geometry().height())

    parent.lay = parent.win.addLayout(0, 0)
    parent.lay.setBorder()

    parent.dettime = pg.AxisItem(orientation='bottom')
    parent.dettime.setScale(1 / 3600)
    parent.dettime.setTickSpacing(major=1, minor=1 / 6)
    parent.dettime.setGrid(255)
    parent.dettime.setPen('#A0A0A0')

    parent.predtime = pg.AxisItem(orientation='bottom')
    parent.predtime.setScale(1 / 3600)
    parent.predtime.setTickSpacing(major=1, minor=1 / 6)
    parent.predtime.setGrid(255)
    parent.predtime.setPen('#A0A0A0')

    #DetectPlot
    parent.det = parent.lay.addPlot(1, 1, axisItems={"bottom": parent.dettime})

    parent.det.showAxis('bottom', show=True)
    parent.det.showAxis('left', show=False)

    parent.det.enableAutoRange(axis='y', enable=False)
    parent.det.setMouseEnabled(x=True, y=False)
    parent.det.setLimits(minXRange=30,
                         minYRange=1,
                         xMin=0,
                         xMax=parent.parent.lendy,
                         yMin=0,
                         yMax=1)
    parent.det.plot(parent.parent.detx,
                    parent.parent.detData,
                    stepMode=True,
                    fillLevel=0,
                    brush=(255, 0, 0, 255),
                    pen=pg.mkPen('r'))

    #predictPlot
    parent.pred = parent.lay.addPlot(2,
                                     1,
                                     axisItems={"bottom": parent.predtime})

    parent.pred.showAxis('bottom', show=True)
    parent.pred.showAxis('left', show=False)

    parent.pred.enableAutoRange(axis='y', enable=False)
    parent.pred.setMouseEnabled(x=True, y=False)
    parent.pred.setLimits(minXRange=30,
                          minYRange=1,
                          xMin=0,
                          xMax=parent.parent.lenpy,
                          yMin=0,
                          yMax=1)
    parent.pred.plot(parent.parent.predx,
                     parent.parent.predData,
                     stepMode=True,
                     fillLevel=0,
                     brush=(255, 0, 0, 255),
                     pen=pg.mkPen((0, 150, 0, 255)))

    #Get Viewbox

    parent.detviewbox = parent.det.getViewBox()
    parent.predviewbox = parent.pred.getViewBox()
    parent.detviewbox.frame = parent
    parent.predviewbox.frame = parent

    #Timeline
    dettimeline = pg.InfiniteLine(pen=pg.mkPen('y', width=2),
                                  hoverPen=pg.mkPen('y', width=2),
                                  movable=True)

    parent.detviewbox.timeline = dettimeline
    parent.detviewbox.addItem(dettimeline)

    predtimeline = pg.InfiniteLine(pen=pg.mkPen('y', width=2),
                                   hoverPen=pg.mkPen('y', width=2),
                                   movable=True)

    parent.predviewbox.timeline = predtimeline
    parent.detviewbox.addItem(predtimeline)

    #InfLabel
    pg.InfLineLabel(dettimeline)
    pg.InfLineLabel(predtimeline)
    parent.det.addItem(dettimeline)
    parent.pred.addItem(predtimeline)

    def mouseClickEvent(self, e):
        fre = self.frame.parent.Frequency
        clktime = self.mapSceneToView(e.scenePos()).x()
        self.timeline.setPos(clktime)

        self.frame.parent.playtime = clktime // (1 / fre) * (1 / fre)

    def MoveFinished(self, obj):
        self.frame.parent.playtime = (obj.getXPos() // self.frame.parent.unit
                                      ) / self.frame.parent.Frequency

    parent.detviewbox.mouseClickEvent = partial(mouseClickEvent,
                                                parent.detviewbox)
    parent.predviewbox.mouseClickEvent = partial(mouseClickEvent,
                                                 parent.predviewbox)
    parent.detviewbox.MoveFinished = partial(MoveFinished, parent.detviewbox)
    parent.predviewbox.MoveFinished = partial(MoveFinished, parent.predviewbox)

    predtimeline.sigPositionChangeFinished.connect(
        parent.predviewbox.MoveFinished)
    dettimeline.sigPositionChangeFinished.connect(
        parent.detviewbox.MoveFinished)
Пример #15
0
    def plot(self):
        # Adjust the plot range to the data
        self.afrPlot.setRange(xRange=[x[0], x[-1]])
        self.afrPlot.setLimits(xMin=x[0], xMax=x[-1])
        # ax = self.afrPlot.getAxis('bottom')
        # ax.setStyle(
        #     textFillLimits = [ (0, 0.8), (2, 0.6), (4, 0.4), (6, 0.2)],
        #     autoExpandTextSpace = False)
        # dx = [(value, '{:.0f}'.format(value)) for value in x]
        # ax.setTicks([dx, []])

        self.tpsPlot.setRange(xRange=[x[0], x[-1]])
        self.tpsPlot.setLimits(xMin=x[0], xMax=x[-1])
        self.rangePlot.setRange(xRange=[x[0], x[-1]])
        self.rangePlot.setLimits(xMin=x[0], xMax=x[-1])
        self.region = pg.LinearRegionItem()
        self.region.setZValue(10)
        self.rangePlot.addItem(self.region, ignoreBounds=True)
        # Adjust the range selector

        # Generate curve data
        self.afrPlot.plot(x, yAfr, pen='c', name='AFR')
        self.tpsPlot.plot(x, yTps, pen='m', name='TPS')
        self.rangePlot.plot(x, yAfr, pen='y', name='data')

        # Crosshair
        self.lineAfr = pg.InfiniteLine(movable=True, angle=90)
        self.lineTps = pg.InfiniteLine(movable=True, angle=90)
        self.lineRange = pg.InfiniteLine(movable=True, angle=90)
        self.lineAfr.setPos(x[200])
        self.afrPlot.addItem(self.lineAfr)
        self.tpsPlot.addItem(self.lineTps)
        self.rangePlot.addItem(self.lineRange)
        self.lineRange.setZValue(20)

        self.labelAFR = pg.InfLineLabel(self.lineAfr,
                                        text="Drag",
                                        movable=True,
                                        position=0.5,
                                        color=(200, 200, 100),
                                        fill=(200, 200, 200, 50))

        def afr_line_pos():
            self.linePos = self.lineAfr.getPos()
            self.lineTps.setPos(self.linePos[0])
            self.lineRange.setPos(self.linePos[0])
            self.interpAfr = np.interp(self.linePos[0], x, yAfr)
            self.interpTps = np.interp(self.linePos[0], x, yTps)
            self.interp = [self.interpAfr, self.interpTps]
            #print("%0.2f, %0.2f" %(self.interpAfr, self.interpTps))
            self.labelAFR.setText("AFR: %0.2f\nTPS: %0.2f%%" %
                                  (self.interp[0], self.interp[1]))

        def tps_line_pos():
            self.linePos = self.lineTps.getPos()
            self.lineAfr.setPos(self.linePos[0])
            self.lineRange.setPos(self.linePos[0])

        def range_line_pos():
            self.linePos = self.lineRange.getPos()
            self.lineAfr.setPos(self.linePos[0])
            self.lineTps.setPos(self.linePos[0])

        def update():
            self.region.setZValue(10)
            minX, maxX = self.region.getRegion()
            self.afrPlot.setXRange(minX, maxX, padding=0)
            self.lineAfr.setBounds((minX, maxX))
            self.lineTps.setBounds((minX, maxX))
            self.lineRange.setBounds((minX, maxX))

        self.lineAfr.sigPositionChanged.connect(afr_line_pos)
        self.lineTps.sigPositionChanged.connect(tps_line_pos)
        self.lineRange.sigPositionChanged.connect(range_line_pos)
        self.region.sigRegionChanged.connect(update)

        def updateRegion(window, viewRange):
            self.rgn = viewRange[0]
            self.region.setRegion(self.rgn)

        self.afrPlot.sigRangeChanged.connect(updateRegion)
        self.region.setRegion([x[100], x[-100]])
Пример #16
0
    def overlayView(self, trace_obj, sample_interval, picks):

        # pull in variables from function call
        self.trace_obj = trace_obj
        self.sample_interval = sample_interval
        self.picks = picks

        # create an empty array to store the list of pyqtgraph plot objects
        self.plot_frames = []

        n_aux_plots = 0
        n_geo_plots = 0

        #work out how many AUX and GEO there are
        for i in range(len(self.trace_obj)):
            if self.trace_obj[i].Owner < 0:
                n_aux_plots += 1
            elif self.trace_obj[i].Owner > 0:
                n_geo_plots += 1

        n_geo_plots = int(n_geo_plots / 3)

        #add single aux plots
        for i in range(n_aux_plots):
            plot = self.addPlot(row=i, col=0)
            self.plot_frames.append(plot)

            self.plot_frames[i].clear()

            y = np.array(self.trace_obj[i].Raw_data)
            x = np.arange(0,
                          len(y) * (self.sample_interval / 1000),
                          self.sample_interval / 1000)
            self.plot_frames[i].plot(x, y)

            #left axis stuff decriptors
            owner = owner_translate(self.trace_obj[i].Owner)

            self.plot_frames[i].showAxis('left')
            self.plot_frames[i].getAxis('left').enableAutoSIPrefix(
                enable=False)
            self.plot_frames[i].getAxis('left').setLabel(text=owner,
                                                         units=None)
            self.plot_frames[i].getAxis('left').setStyle(tickLength=0,
                                                         showValues=False)

            #right axis stuff decriptors
            desc = description_translate(self.trace_obj[i].Descriptor)
            self.plot_frames[i].showAxis('right')
            self.plot_frames[i].getAxis('right').enableAutoSIPrefix(
                enable=False)
            self.plot_frames[i].getAxis('right').setLabel(text=desc,
                                                          units=None)
            self.plot_frames[i].getAxis('right').setStyle(tickLength=0,
                                                          showValues=False)

        #add geo overlay plots
        for i in range(n_geo_plots):

            plot = self.addPlot(row=i + n_aux_plots, col=0)
            self.plot_frames.append(plot)

            self.plot_frames[i + n_aux_plots].clear()

            y1 = np.array(self.trace_obj[(i * 3) + 0 + n_aux_plots].Raw_data)
            y2 = np.array(self.trace_obj[(i * 3) + 1 + n_aux_plots].Raw_data)
            y3 = np.array(self.trace_obj[(i * 3) + 2 + n_aux_plots].Raw_data)
            x = np.arange(0,
                          len(y1) * (self.sample_interval / 1000),
                          self.sample_interval / 1000)

            self.plot_frames[i + n_aux_plots].plot(x, y1, pen=(255, 0, 0))
            self.plot_frames[i + n_aux_plots].plot(x, y2, pen=(0, 255, 0))
            self.plot_frames[i + n_aux_plots].plot(x, y3, pen=(0, 0, 255))

            #left axis stuff decriptors
            owner = owner_translate(self.trace_obj[(i * 3) +
                                                   n_aux_plots].Owner)

            self.plot_frames[i + n_aux_plots].showAxis('left')
            self.plot_frames[i +
                             n_aux_plots].getAxis('left').enableAutoSIPrefix(
                                 enable=False)
            self.plot_frames[i + n_aux_plots].getAxis('left').setLabel(
                text=owner, units=None)
            self.plot_frames[i + n_aux_plots].getAxis('left').setStyle(
                tickLength=0, showValues=False)

            #right axis stuff decriptors
            desc = "XYZ"
            self.plot_frames[i + n_aux_plots].showAxis('right')
            self.plot_frames[i +
                             n_aux_plots].getAxis('right').enableAutoSIPrefix(
                                 enable=False)
            self.plot_frames[i + n_aux_plots].getAxis('right').setLabel(
                text=desc, units=None)
            self.plot_frames[i + n_aux_plots].getAxis('right').setStyle(
                tickLength=0, showValues=False)

        #Formatting plots
        for i in range(len(self.plot_frames)):

            # Zero line
            zero_line = pg.InfiniteLine(
                movable=False, angle=0,
                pen=pg.mkColor(0.2))  #add infinte line at zero
            self.plot_frames[i].addItem(zero_line)

            #Time Picks
            if self.picks == True:
                vert_line = pg.InfiniteLine(
                    movable=True, angle=90,
                    pen=pg.mkColor(0.2))  #add infinte line at zero
                self.plot_frames[i].addItem(vert_line)
                vert_label = pg.InfLineLabel(vert_line,
                                             text="{value:0.2f}ms",
                                             position=0.9)

            self.plot_frames[i].enableAutoRange(pg.ViewBox.XYAxes)
            self.plot_frames[i].setMouseEnabled(x=True,
                                                y=False)  #lock vertical scroll
            self.plot_frames[i].hideButtons()  # hide auto scale A button

            #hide axis btoom and left
            self.plot_frames[i].hideAxis('bottom')

            #link all scrolling axis together
            if i > 0:
                self.plot_frames[i].setXLink(self.plot_frames[i - 1])

        # check to allow for an empty plots scenario.
        if len(self.plot_frames) != 0:
            #show axis and label on top plot
            self.plot_frames[0].showAxis('top')
            self.plot_frames[0].getAxis('top').setStyle(showValues=True)

            #show axis on bottom plot
            self.plot_frames[-1].showAxis('bottom')
            self.plot_frames[-1].getAxis('bottom').setStyle(showValues=True)
Пример #17
0
    def __init__(self,
                 plot_item,
                 x_array=None,
                 name='array_slicer_name',
                 slicer_updated_func=lambda: None,
                 initial=[0, 100],
                 s_return_on_deactivated=np.s_[:],
                 brush=QtGui.QColor(0, 255, 0, 70),
                 ZValue=10,
                 font=QtGui.QFont("Times", 12),
                 label_line=1,
                 activated=False):
        """Create a new LinearRegionItem on plot_item.
        
        ====================== ==============================================================
        **Arguments:**
        plot_item              <pyqtgraph.PlotDataItem> (recommended) 
                                or <pyqtgraph.PlotItem>  (does not grab x_array data from plot
                                item: initialize x_array manually
                                or use :func:`set_x_array <self.set_x_array>`)
        x_array                use to initialize x_array if plot_item == <pyqtgraph.PlotItem>.
        name                   <str> 
        slicer_updated_func    gets called when region is updated, alternatively use 
                               :sig:region_changed_signal().
        initial                initial index values [start,stop,step] or [start,stop]
        s_return_on_deactivated  Object returned if RegionSlicer is not activated.
                                 Slicing with np.s_[:] (default) and np.s_[0] gives the full and 
                                 an empty array respectively. Note, <RegionSlicer.slice> always 
                                 returns the last determined slice even if slice is deactivated.
        brush,ZValue,          are passed to the LinearRegionItem
        font,                  passed to the label
        label_line             '0' or '1' for placement of label onto 'left' or 'right'
                               bounding line. 
        activated              <bool> state at initialization
        ====================== ===============================================================
        """
        QtWidgets.QWidget.__init__(self)

        self.name = name

        self.slicer_updated = slicer_updated_func

        from ScopeFoundry.logged_quantity import LQCollection
        self.settings = LQCollection()
        if len(initial) == 2: initial.append(1)
        start, stop, step = initial
        self.start = self.settings.New('start', int, initial=start, vmin=0)
        self.stop = self.settings.New('stop', int, initial=stop, vmin=0)
        self.step = self.settings.New('step', int, initial=step)
        self.activated = self.settings.New('activated',
                                           bool,
                                           initial=activated)
        self.start.add_listener(self.on_change_start_stop)
        self.stop.add_listener(self.on_change_start_stop)
        self.activated.add_listener(self.on_change_activated)

        self.s_return_on_deactivated = s_return_on_deactivated

        if type(plot_item) == pg.PlotDataItem:
            self.plot_data_item = plot_item
            self.plot_data_item.sigPlotChanged.connect(
                self.set_x_array_from_data_item)
            self.parent_plot_item = plot_item.parentItem()
        elif type(plot_item) == pg.PlotItem:
            self.plot_data_item = None
            self.parent_plot_item = plot_item

        self.linear_region_item = pg.LinearRegionItem(brush=brush)
        self.linear_region_item.setZValue(ZValue)
        self.parent_plot_item.addItem(self.linear_region_item)
        self.linear_region_item.sigRegionChangeFinished.connect(
            self.on_change_region)

        self.inf_line_label = pg.InfLineLabel(
            self.linear_region_item.lines[label_line],
            self.name,
            position=0.78,
            anchor=(0.5, 0.5))
        #self.inf_line_label = pg.TextItem(self.name, anchor=(0.5, 0.5))
        self.inf_line_label.setFont(font)
        self.set_label('')

        if x_array == None:  #give it something to work with.
            x_array = np.arange(512)
        self.set_x_array(x_array)
Пример #18
0
def RTupdateSignals(self):

    global DataStream, TimeStream, index, counter_seg, reading_block, RTtime, RTdata, blockPredictions, block_num, time_cleard
    global ECGcurve, ECGcurveClear, GSRcurve, GSRcurveClear, ECG_cleard_data, GSR_cleard_data, cleardPlot, blockStart, blockEnd, p1, m1

    #When we update the plots of the data streaming
    display_jump = 10

    #flag end of streaming data
    # finish = False

    # Insert to RTData array ecg and gsr values from the data stream
    # RTdata[0].append(DataStream[0])
    # if(DataStream[1]!=0):RTdata[1].append(DataStream[1])
    # else: RTdata[1].append(5.96)
    RTdata[0].append(DataStream[0])
    RTdata[1].append(DataStream[1])
    RTtime.append(TimeStream[0])

    if counter_seg == seg_len:  #Finish reading segment
        print('Finish reading segment from block number:', block_num)
        ECGseg = RTdata[0][index - counter_seg + 1:index + 1]
        GSRseg = RTdata[1][index - counter_seg + 1:index + 1]
        seg_times = RTtime[index - counter_seg + 1:index + 1]

        #Clear the seg signals we read
        GSRsegClear = smooth(np.asarray(GSRseg))
        ECGsegClear = clearSignal(ECGseg)

        #Updating the proceesed data arrays for displays later
        ECG_cleard_data.extend(ECGsegClear)
        GSR_cleard_data.extend(GSRsegClear)
        time_cleard.extend(seg_times)

        # #like it was before, but now with the cleared signal
        #segment = [GSRsegClear,ECGsegClear]
        segment = [ECGseg, GSRseg]
        #Predict the segment
        cl_result = predictSeg(segment, seg_times, 'CL')
        st_result = predictSeg(segment, seg_times, 'condition')
        #segment = [RTdata[0][index-counter_seg+1:index+1],RTdata[1][index-counter_seg+1:index+1]]
        print('segment', type(segment))
        #@Real code
        self.lcdNumber.display(cl_result)
        self.progressBar.setValue(cl_result)
        #graphic display of thr segments prediction
        blockPredictions.append(
            cl_result
        )  #Add predict to list of segmentations' predicts in the block
        if st_result == 0:  #no stress
            pixmap = QPixmap('no_stress.png')
            stress_scale = self.stress_level.setPixmap(pixmap)
            self.stress_level.resize(pixmap.width(), pixmap.height())
        elif st_result == 1:  #stress
            pixmap = QPixmap('stress.png')
            stress_scale = self.stress_level.setPixmap(pixmap)
            self.stress_level.resize(pixmap.width(), pixmap.height())
        print('The result for the segment is:', cl_result)  #For check
        print('The condition for the segment is:', st_result)  # For check
        counter_seg = 0  #Reset counter

    # Finish reading block data.
    # Predict the block:
    if DataStream[2] == end_block:
        blockEnd = RTtime[index]
        pixmap = QPixmap('neutral.png')
        stress_scale = self.stress_level.setPixmap(pixmap)
        self.stress_level.resize(pixmap.width(), pixmap.height())
        # OR: add label specify it's end of the block
        print('Finish reading block data. Need to predict the block')
        print(blockStart)
        print("---------")
        print(blockEnd)
        block_predict = int(np.median(blockPredictions))
        print('Predict of the block', block_num, 'is:', block_predict)

        block_num += 1  # count another block

        #@Real code
        print('from RTupdateSignals: Predict is: ', block_predict)  #For check
        #Clear predictions
        blockPredictions.clear()
        #Reset counter
        lr = pg.LinearRegionItem(values=[blockStart, blockEnd],
                                 brush=pg.intColor(index=block_predict,
                                                   alpha=50),
                                 movable=False)
        m1.addItem(lr)
        label = pg.InfLineLabel(lr.lines[1],
                                text=("BLOCK number: ", str(block_num - 1),
                                      " overload " + str(block_predict)),
                                position=(0.85),
                                rotateAxis=(1, 0),
                                anchor=(1, 1))
        counter_seg = 0

        #Or:
        #Do something with predict: on the graph show
        #Display what we predict for the block

    elif DataStream[2] == start_block:  #Starting reading new block's data
        blockStart = RTtime[index]  #TimeStream

        print(blockStart)

        #OR: add label specify it's start of block
        reading_block = 1  #Change flag

    if reading_block == 1:

        #Update the counter_seg
        counter_seg += 1

    #Display plot
    if index % display_jump == 0 and index > 0:
        ECGcurve.setData(np.asarray(RTtime), np.asarray(RTdata[0]))
        GSRcurve.setData(np.asarray(RTtime), np.asarray(RTdata[1]))
        ECGcurveClear.setData(time_cleard, ECG_cleard_data)
        GSRcurveClear.setData(time_cleard, GSR_cleard_data)
        QtGui.QApplication.processEvents()

    if DataStream[2] == end_data:
        print('finish')  #check
        #finish = True

    # Update index
    index += 1
Пример #19
0
    def setup(self):
        
        #self.ui = self.splitter = QtWidgets.QSplitter()
        #self.ui.setLayout(QtWidgets.QVBoxLayout())
        self.ui = self.dockarea = dockarea.DockArea()
        self.imview = pg.ImageView()
        self.imview.getView().invertY(False) # lower left origin
        #self.splitter.addWidget(self.imview)
        self.image_dock = self.dockarea.addDock(name='Image', widget=self.imview)
        self.graph_layout = pg.GraphicsLayoutWidget()
        #self.splitter.addWidget(self.graph_layout)
        self.spec_dock = self.dockarea.addDock(name='Spec Plot', widget=self.graph_layout)

        self.line_pens = ['w', 'r']
        self.spec_plot = self.graph_layout.addPlot()
        self.spec_plot.setLabel('left', 'Intensity', units='counts') 
        self.rect_plotdata = self.spec_plot.plot(y=[0,2,1,3,2],pen=self.line_pens[0])
        self.point_plotdata = self.spec_plot.plot(y=[0,2,1,3,2], pen=self.line_pens[1])
        self.point_plotdata.setZValue(-1)

        #correlation plot
        self.corr_layout = pg.GraphicsLayoutWidget()
        self.corr_plot = self.corr_layout.addPlot()
        self.corr_plotdata = pg.ScatterPlotItem(x=[0,1,2,3,4], y=[0,2,1,3,2], size=17, 
                                        pen=pg.mkPen(None), brush=pg.mkBrush(255, 255, 255, 60))
        self.corr_plot.addItem(self.corr_plotdata)
        
        #self.corr_plotdata = self.corr_plot.scatterPlot( x=[0,1,2,3,4], y=[0,2,1,3,2], size=17, 
        #                                pen=pg.mkPen(None), brush=pg.mkBrush(255, 255, 255, 60))
        self.corr_dock = self.dockarea.addDock(name='correlation', widget=self.corr_layout, 
                              position='below',  relativeTo = self.spec_dock)
        self.spec_dock.raiseDock()
        
        
        # Rectangle ROI
        self.rect_roi = pg.RectROI([20, 20], [20, 20], pen=(0,9))
        self.rect_roi.addTranslateHandle((0.5,0.5))        
        self.imview.getView().addItem(self.rect_roi)        
        self.rect_roi.sigRegionChanged[object].connect(self.on_change_rect_roi)
        
        # Point ROI
        self.circ_roi = pg.CircleROI( (0,0), (2,2) , movable=True, pen=(0,9))
        #self.circ_roi.removeHandle(self.circ_roi.getHandles()[0])
        h = self.circ_roi.addTranslateHandle((0.5,.5))
        h.pen = pg.mkPen('r')
        h.update()
        self.imview.getView().addItem(self.circ_roi)
        self.circ_roi.removeHandle(0)
        self.circ_roi_plotline = pg.PlotCurveItem([0], pen=(0,9))
        self.imview.getView().addItem(self.circ_roi_plotline) 
        self.circ_roi.sigRegionChanged[object].connect(self.on_update_circ_roi)
        
        #font
        font = QtGui.QFont("Times", 12)
        font.setBold(True)
            
        #settings
        self.default_display_image_choices = ['default', 'sum', 'median_map']
        self.settings.New('display_image', str, choices = self.default_display_image_choices, initial = 'sum')    
        self.settings.display_image.add_listener(self.on_change_display_image)    
        
        self.default_x_axis_choices = ['default', 'index']
        self.x_axis = self.settings.New('x_axis', str, choices = self.default_x_axis_choices)
        self.x_axis.add_listener(self.on_change_x_axis)

        self.norm_data = self.settings.New('norm_data', bool, initial = False)
        self.norm_data.add_listener(self.update_display)
        self.settings.New('default_view', bool, initial=True)
        
        self.binning = self.settings.New('binning', int, initial = 1, vmin=1)
        self.binning.add_listener(self.update_display)

        self.spatial_binning = self.settings.New('spatial_binning', int, initial = 1, vmin=1)
        self.spatial_binning.add_listener(self.bin_spatially)

        self.cor_X_data = self.settings.New('cor_X_data', str, choices = self.default_display_image_choices,
                                            initial = 'default')
        self.cor_Y_data = self.settings.New('cor_Y_data', str, choices = self.default_display_image_choices,
                                            initial = 'sum')
        self.cor_X_data.add_listener(self.on_change_corr_settings)
        self.cor_Y_data.add_listener(self.on_change_corr_settings)

        # data slicers
        self.x_slice = np.s_[0:-1]                        
        self.x_slice_LinearRegionItem = pg.LinearRegionItem(brush = QtGui.QColor(0,255,0,70))
        self.x_slice_LinearRegionItem.setZValue(+10)
        self.spec_plot.addItem(self.x_slice_LinearRegionItem)
        self.x_slice_LinearRegionItem.sigRegionChangeFinished.connect(self.on_change_x_slice_LinearRegionItem)
        self.x_slice_InfLineLabel = pg.InfLineLabel(self.x_slice_LinearRegionItem.lines[1], "x_slice", 
                                               position=0.85, anchor=(0.5, 0.5))
        self.x_slice_InfLineLabel.setFont(font)
        self.use_x_slice = self.settings.New('use_x_slice', bool, initial = False)
        self.use_x_slice.add_listener(self.on_change_x_slice)
        
        self.bg_slice = np.s_[0:10]                        
        self.bg_LinearRegionItem = pg.LinearRegionItem(brush = QtGui.QColor(255,255,255,70))
        self.bg_LinearRegionItem.setZValue(+11)
        self.spec_plot.addItem(self.bg_LinearRegionItem)
        self.bg_LinearRegionItem.sigRegionChangeFinished.connect(self.on_change_bg_LinearRegionItem)
        self.bg_InfLineLabel = pg.InfLineLabel(self.bg_LinearRegionItem.lines[0], "bg_subtract", 
                                               position=0.95, rotateAxis = (-1,0), anchor=(0.5, 0.5))
        self.bg_InfLineLabel.setFont(font)
        self.bg_subtract = self.settings.New('bg_subtract', bool, initial = False)
        self.bg_subtract.add_listener(self.on_change_bg_subtract)
        #self.bg_subtract.update_value(False)  
              
        self.show_lines = ['show_circ_line','show_rect_line']
        for x in self.show_lines:
            lq = self.settings.New(x, bool, initial=True)
            lq.add_listener(self.on_change_show_lines)
        
        self.hyperspec_data = None
        self.display_image = None
        self.spec_x_array = None
        
        self.display_images = dict()
        self.spec_x_arrays = dict()        
        
        self.settings_widgets = [] # Hack part 1/2: allows to use settings.New_UI() and have settings defined in scan_specific_setup()
        
        self.scan_specific_setup()
        
        self.add_settings_dock() # Hack part 2/2: Need to generate settings after scan_specific_setup()
    
        self.circ_roi_slice = self.rect_roi_slice = np.s_[:,:]
Пример #20
0
    def update_display(self):
        """Called when we need to update displayed results (from self.parent.result)
        """
        ModelResultView.update_display(self)

        for k in self.plots:
            if self.plot_checks[k].isChecked():
                self.plots[k].setVisible(True)
                self.plots[k].setMaximumHeight(10000)
            else:
                self.plots[k].setVisible(False)
                self.plots[k].setMaximumHeight(0)

        full_result = self.parent.result
        model = full_result.model
        result = full_result.result
        pre_state = full_result.pre_spike_state
        post_state = full_result.post_spike_state
        
        # color events by likelihood
        cmap = pg.ColorMap([0, 1.0], [(0, 0, 0), (255, 0, 0)])
        threshold = 10
        err_colors = cmap.map((threshold - result['likelihood']) / threshold)
        brushes = [pg.mkBrush(c) if np.isfinite(result['likelihood'][i]) else pg.mkBrush(None) for i,c in enumerate(err_colors)]

        # log spike intervals to make visualization a little easier
        compressed_spike_times = np.empty(len(result['spike_time']))
        compressed_spike_times[0] = 0.0
        np.cumsum(np.diff(result['spike_time'])**0.25, out=compressed_spike_times[1:])

        if self.plot_checks['likelihood'].isChecked():
            self.plots['likelihood'].clear()
            self.plots['likelihood'].plot(compressed_spike_times, result['likelihood'], pen=None, symbol='o', symbolBrush=brushes)
        
        if self.plot_checks['amplitude'].isChecked():
            self.plots['amplitude'].clear()
            self.plots['amplitude'].plot(compressed_spike_times, result['expected_amplitude'], pen=None, symbol='x', symbolPen=0.5, symbolBrush=brushes)
            amp_sp = self.plots['amplitude'].plot(compressed_spike_times, result['amplitude'], pen=None, symbol='o', symbolBrush=brushes)
            amp_sp.scatter.sigClicked.connect(self.amp_sp_clicked)

            # show regions for each type of stimulus
            last_stim_name = None
            rgns = []
            for i, stim_name in enumerate(full_result.event_meta['stim_name']):
                ev_time = compressed_spike_times[i]
                if stim_name != last_stim_name:
                    rgns.append([stim_name, ev_time, ev_time])
                    last_stim_name = stim_name
                else:
                    rgns[-1][1] = ev_time
            for stim_name, start_time, stop_time in rgns:
                rgn = pg.LinearRegionItem(values=[start_time, stop_time], orientation='vertical', brush=(len(self.stim_regions), 10), pen=None, movable=False)
                rgn.lines[0].label = pg.InfLineLabel(rgn.lines[1], stim_name, movable=False, rotateAxis=(1, 0), position=0, anchors=[(0, 0), (0, 0)])
                rgn.setZValue(-10)
                rgn.setOpacity(0.3)
                self.plots['amplitude'].addItem(rgn)
                self.stim_regions.append(rgn)

        for k in self.state_keys:
            if not self.plot_checks[k].isChecked():
                continue
            self.plots[k].clear()
            self.plots[k].plot(compressed_spike_times, pre_state[k], pen=None, symbol='t', symbolBrush=brushes)
            self.plots[k].plot(compressed_spike_times, post_state[k], pen=None, symbol='o', symbolBrush=brushes)

        # plot full distribution of event amplitudes
        self.amp_dist_plot.clear()
        bins = np.linspace(np.nanmin(result['amplitude']), np.nanmax(result['amplitude']), 40)
        d_amp = bins[1] - bins[0]
        amp_hist = np.histogram(result['amplitude'], bins=bins)
        self.amp_dist_plot.plot(amp_hist[1], amp_hist[0] / (amp_hist[0].sum() * d_amp), stepMode=True, fillLevel=0, brush=0.3)

        # plot average model event distribution
        amps = self.amp_sample_values
        d_amp = amps[1] - amps[0]
        total_dist = np.zeros(len(amps))
        for i in range(result.shape[0]):
            state = pre_state[i]
            if not np.all(np.isfinite(tuple(state))):
                continue
            total_dist += model.likelihood(amps, state)
        total_dist /= total_dist.sum() * d_amp
        self.amp_dist_plot.plot(amps, total_dist, fillLevel=0, brush=(255, 0, 0, 50))
Пример #21
0
    def standardView(self, trace_obj, sample_interval, picks):

        # pull in variables from function call
        self.trace_obj = trace_obj
        self.sample_interval = sample_interval
        self.picks = picks

        # create an empty array to store the list of pyqtgraph plot objects
        self.plot_frames = []

        # style the plots
        for i in range(len(self.trace_obj)):

            plot = self.addPlot(row=i, col=0)
            self.plot_frames.append(plot)

            self.plot_frames[i].clear()  # clear previous plot

            # Zero line
            zero_line = pg.InfiniteLine(
                movable=False, angle=0,
                pen=pg.mkColor(0.2))  #add infinte line at zero
            self.plot_frames[i].addItem(zero_line)

            #Time Picks
            if self.picks == True:

                vert_line = pg.InfiniteLine(
                    movable=True, angle=90,
                    pen=pg.mkColor(0.2))  #add infinte line at zero
                self.plot_frames[i].addItem(vert_line)
                vert_label = pg.InfLineLabel(vert_line,
                                             text="{value:0.2f}ms",
                                             position=0.9)

            # convert dataset to numpy array and create the calc x-axis value dependant on SI
            y = np.array(self.trace_obj[i].Raw_data)
            x = np.arange(0,
                          len(y) * (self.sample_interval / 1000),
                          self.sample_interval / 1000)

            #plot dataset
            self.plot_frames[i].plot(x, y, pen=pg.mkColor(0.7))
            self.plot_frames[i].enableAutoRange(pg.ViewBox.XYAxes)
            self.plot_frames[i].setMouseEnabled(x=True,
                                                y=False)  #lock vertical scroll
            self.plot_frames[i].hideButtons()  # hide auto scale A button

            #hide axis btoom and left
            self.plot_frames[i].hideAxis('bottom')
            self.plot_frames[i].hideAxis('left')

            #link all scrolling axis together
            if i > 0:
                self.plot_frames[i].setXLink(self.plot_frames[i - 1])

            #left axis stuff decriptors
            owner = owner_translate(self.trace_obj[i].Owner)

            self.plot_frames[i].showAxis('left')
            self.plot_frames[i].getAxis('left').enableAutoSIPrefix(
                enable=False)
            self.plot_frames[i].getAxis('left').setLabel(text=owner,
                                                         units=None)
            self.plot_frames[i].getAxis('left').setStyle(tickLength=0,
                                                         showValues=False)

            #right axis stuff decriptors
            desc = description_translate(self.trace_obj[i].Descriptor)
            self.plot_frames[i].showAxis('right')
            self.plot_frames[i].getAxis('right').enableAutoSIPrefix(
                enable=False)
            self.plot_frames[i].getAxis('right').setLabel(text=desc,
                                                          units=None)
            self.plot_frames[i].getAxis('right').setStyle(tickLength=0,
                                                          showValues=False)

        # check to allow for an empty plots scenario.
        if len(self.plot_frames) != 0:
            #show axis and label on top plot
            self.plot_frames[0].showAxis('top')
            self.plot_frames[0].getAxis('top').setStyle(showValues=True)

            #show axis on bottom plot
            self.plot_frames[-1].showAxis('bottom')
            self.plot_frames[-1].getAxis('bottom').setStyle(showValues=True)
#update it each time you receive data

#here the length is set to 300. 3 means the 3-dimension.
data1 = np.zeros((3, 300))
#contains acc_x, acc_y and acc_z
data2 = np.zeros((3, 300))
#contains gyr_x, gyr_y and gyr_z
data3 = np.zeros((3, 300))
#contains mag_x, mag_y and mag_z

p11 = win.addPlot()
p11.addLegend(offset=(10, 10))
p11.addItem(lr11, name='region11')
label = pg.InfLineLabel(lr11.lines[0],
                        "x2={value:0.2f}",
                        position=0.9,
                        rotateAxis=(1, 0),
                        anchor=(1, 1))
label = pg.InfLineLabel(lr11.lines[1],
                        "x1={value:0.2f}",
                        position=0.9,
                        rotateAxis=(1, 0),
                        anchor=(1, 1))
p12 = win.addPlot()
p12.addLegend(offset=(10, 10))
p12.addItem(lr12, name='region12')
label = pg.InfLineLabel(lr12.lines[0],
                        "x2={value:0.2f}",
                        position=0.9,
                        rotateAxis=(1, 0),
                        anchor=(1, 1))
Пример #23
0
 def mark_line(self):
     self.is_current_bar = True
     self.htext = pg.InfLineLabel(self.hline)
Пример #24
0
    def setup_figure(self):
        
        self.ui = load_qt_ui_file(sibling_path(__file__, "power_spec_logger.ui"))
        
        self.settings.activation.connect_to_widget(self.ui.run_checkBox)
        self.settings.channel.connect_to_widget(self.ui.chan_lineEdit)
        self.settings.refresh_time.connect_to_widget(self.ui.time_doubleSpinBox)
        
        auto_connect_widget_in_ui(self.ui, self.settings.update_display)
        auto_connect_widget_in_ui(self.ui, self.settings.view_freq_min)
        auto_connect_widget_in_ui(self.ui, self.settings.view_freq_max)
        auto_connect_widget_in_ui(self.ui, self.settings.log_freq_max)
        auto_connect_widget_in_ui(self.ui, self.settings.save_h5)
        auto_connect_widget_in_ui(self.ui, self.settings.save_raw)

        
        
            
        #### Plots
        self.graph_layout = pg.GraphicsLayoutWidget()
        self.ui.plot_groupBox.layout().addWidget(self.graph_layout)

        
        p = self.power_spec_plot = self.graph_layout.addPlot(row=0, col=0)
        self.dc_plotlines = [None,None,None]

        p.setTitle("Power Spectrum")
        p.addLegend()

        p.current_plotline = p.plot(pen=pg.mkPen('r'), name='Current')
        p.avg_plotline = p.plot(name='Running average')
    
        #p.showLabel('top', True)
        p.setLabel('bottom', "Frequency", 'Hz')
        p.setLabel('left', 'PSD [V<sup>2</sup>/Hz]')
        p.setLogMode(x=False, y=True)
        
        self.settings.view_freq_min.add_listener(self.on_update_freq_lims)
        self.settings.view_freq_max.add_listener(self.on_update_freq_lims)
        
        self.on_update_freq_lims()


                    
        dc_p = self.dc_plot = self.graph_layout.addPlot(row=1, col=0)
        dc_p.addLegend()
        dc_p.setTitle("DC")
        dc_p.setLabel('bottom', "Time", 's')
        dc_p.setLabel('left', '&Delta; <sub>DC</sub>', units='V')
        
        dc_p.addItem(pg.InfiniteLine(movable=False, angle=0))

        for i,name in enumerate('xyz'):
            self.dc_plotlines[i] = dc_p.plot(pen=pg.mkPen('rgb'[i]), name=name, autoDownsampleFactor=1.0)
        
        dc_p.setDownsampling(auto=True, mode='subsample',)
        
        
        p = self.roi_plot = self.graph_layout.addPlot(row=2, col=0)
        p.addLegend()
        p.setTitle("Frequency Band History")
        p.setLabel('bottom', "Time", 's')        
        p.setXLink(self.dc_plot)
        p.setLabel('left', 'V')
        p.setLogMode(x=False, y=True)
        
        self.linear_range_items = []
        for i in range(2):
            color = ['#F005','#0F05'][i]
            lr = pg.LinearRegionItem(values=[55*(i+1),65*(i+1)], brush=pg.mkBrush(color))
            lr.num = i
            self.power_spec_plot.addItem(lr)
            lr.label = pg.InfLineLabel(lr.lines[0], "Region {}".format(i), position=0.8, rotateAxis=(1,0), anchor=(1, 1), movable=True)
            self.linear_range_items.append(lr)
            
            lr.hist_plotline = self.roi_plot.plot(pen=pg.mkPen(color[:-1]), name='Region {}'.format(i))
            lr.hist_plotline.setAlpha(1, auto=False)
        
        self.roi_plot.setDownsampling(auto=True, mode='subsample',)

        self.settings.phys_unit.add_listener(self.on_change_phys_unit)
Пример #25
0
    def _setup_plot(self):

        # Get plot item and setup
        self.plt = self.getPlotItem()
        self.plt.setDownsampling(auto=True)
        self.plt.setTitle(
            type(self).
            __name__ if self.daq_device is None else type(self).__name__ +
            ' ' + self.daq_device)
        self.plt.setLabel('left', text='Vertical displacement', units='%')
        self.plt.setLabel('bottom', text='Horizontal displacement', units='%')
        self.plt.showGrid(x=True, y=True, alpha=0.66)
        self.plt.setRange(xRange=[-100, 100], yRange=[-100, 100])
        self.plt.setLimits(xMax=110, xMin=-110, yMax=110, yMin=-110)
        xyticks = dict([(v, str(abs(v))) for v in range(-120, 130, 20)])
        self.plt.getAxis('bottom').setTicks([xyticks.items()])
        self.plt.getAxis('left').setTicks([xyticks.items()])
        self.plt.hideButtons()
        v_line = self.plt.addLine(x=0,
                                  pen={
                                      'color': 'w',
                                      'style': pg.QtCore.Qt.DashLine
                                  })
        h_line = self.plt.addLine(y=0.,
                                  pen={
                                      'color': 'w',
                                      'style': pg.QtCore.Qt.DashLine
                                  })
        label_left = pg.InfLineLabel(line=h_line,
                                     text='Left',
                                     position=0.05,
                                     movable=False)
        label_right = pg.InfLineLabel(line=h_line,
                                      text='Right',
                                      position=0.95,
                                      movable=False)
        label_up = pg.InfLineLabel(line=v_line,
                                   text='Up',
                                   position=0.95,
                                   movable=False)
        label_down = pg.InfLineLabel(line=v_line,
                                     text='Down',
                                     position=0.05,
                                     movable=False)
        self.legend = pg.LegendItem(offset=(80, -50))
        self.legend.setParentItem(self.plt)

        self.curves = OrderedDict()

        if any(x in self.ro_types for x in ('sem_h_shift', 'sem_v_shift')):
            sig = 'analog'
            self.curves[sig] = BeamPositionItem(color=_MPL_COLORS[0],
                                                name=sig,
                                                horizontal='sem_h_shift'
                                                in self.ro_types,
                                                vertical='sem_v_shift'
                                                in self.ro_types)

        if any(
                all(x in self.ro_types for x in y)
                for y in [('sem_left', 'sem_right'), ('sem_up', 'sem_down')]):
            sig = 'digital'
            self.curves[sig] = BeamPositionItem(
                color=_MPL_COLORS[1],
                name=sig,
                horizontal='sem_left' in self.ro_types
                and 'sem_right' in self.ro_types,
                vertical='sem_up' in self.ro_types
                and 'sem_down' in self.ro_types)

        # Show data and legend
        if self.curves:
            for curve in self.curves:
                self.curves[curve].set_legend(self.legend)
                self.curves[curve].set_plotitem(self.plt)
                self.show_data(curve)
Пример #26
0
    def setup(self):
        
        self.ui = self.graph_layout = pg.GraphicsLayoutWidget()

        p = self.power_spec_plot = self.graph_layout.addPlot(row=0, col=0)
        self.dc_plotlines = [None,None,None]

        p.setTitle("Power Spectrum")
        p.addLegend()

        p.current_plotline = p.plot(pen=pg.mkPen('r'), name='Current')
        p.avg_plotline = p.plot(name='Running average')
    
        #p.showLabel('top', True)
        p.setLabel('bottom', "Frequency", 'Hz')
        p.setLabel('left', 'PSD [V<sup>2</sup>/Hz]')
        p.setLogMode(x=False, y=True)
        
        #self.settings.view_freq_min.add_listener(self.on_update_freq_lims)
        #self.settings.view_freq_max.add_listener(self.on_update_freq_lims)
        
        #self.on_update_freq_lims()


                    
        dc_p = self.dc_plot = self.graph_layout.addPlot(row=1, col=0)
        dc_p.addLegend()
        dc_p.setTitle("DC")
        dc_p.setLabel('bottom', "Time", 's')
        dc_p.setLabel('left', '&Delta; <sub>DC</sub>', units='V')
        
        dc_p.addItem(pg.InfiniteLine(movable=False, angle=0))

        for i,name in enumerate('xyz'):
            self.dc_plotlines[i] = dc_p.plot(pen=pg.mkPen('rgb'[i]), name=name, autoDownsampleFactor=1.0)
        
        dc_p.setDownsampling(auto=True, mode='subsample',)
        
        
        p = self.roi_plot = self.graph_layout.addPlot(row=2, col=0)
        p.addLegend()
        p.setTitle("Frequency Band History")
        p.setLabel('bottom', "Time", 's')        
        p.setXLink(self.dc_plot)
        p.setLabel('left', 'V')
        p.setLogMode(x=False, y=True)
        
        self.linear_range_items = []
        for i in range(2):
            color = ['#F005','#0F05'][i]
            lr = pg.LinearRegionItem(values=[55*(i+1),65*(i+1)], brush=pg.mkBrush(color))
            lr.num = i
            self.power_spec_plot.addItem(lr)
            lr.label = pg.InfLineLabel(lr.lines[0], "Region {}".format(i), position=0.8, rotateAxis=(1,0), anchor=(1, 1), movable=True)
            self.linear_range_items.append(lr)
            
            lr.hist_plotline = self.roi_plot.plot(pen=pg.mkPen(color[:-1]), name='Region {}'.format(i))
            lr.hist_plotline.setAlpha(1, auto=False)

            ### add listenr for linear_range_items changing range
            lr.sigRegionChanged.connect(self.update_display)
        
        self.roi_plot.setDownsampling(auto=True, mode='subsample',)
Пример #27
0
# Enable antialiasing for prettier plots
pg.setConfigOptions(antialias=True)

# Create a plot with some random data
p1 = win.addPlot(title="Plot Items example", y=np.random.normal(size=100, scale=10), pen=0.5)
p1.setYRange(-40, 40)

# Add three infinite lines with labels
inf1 = pg.InfiniteLine(movable=True, angle=90, label='x={value:0.2f}', 
                       labelOpts={'position':0.1, 'color': (200,200,100), 'fill': (200,200,200,50), 'movable': True})
inf2 = pg.InfiniteLine(movable=True, angle=0, pen=(0, 0, 200), bounds = [-20, 20], hoverPen=(0,200,0), label='y={value:0.2f}mm', 
                       labelOpts={'color': (200,0,0), 'movable': True, 'fill': (0, 0, 200, 100)})
inf3 = pg.InfiniteLine(movable=True, angle=45, pen='g', label='diagonal',
                       labelOpts={'rotateAxis': [1, 0], 'fill': (0, 200, 0, 100), 'movable': True})
inf1.setPos([2,2])
p1.addItem(inf1)
p1.addItem(inf2)
p1.addItem(inf3)

# Add a linear region with a label
lr = pg.LinearRegionItem(values=[70, 80])
p1.addItem(lr)
label = pg.InfLineLabel(lr.lines[1], "region 1", position=0.95, rotateAxis=(1,0), anchor=(1, 1))


## Start Qt event loop unless running in interactive mode or using pyside.
if __name__ == '__main__':
    import sys
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()
Пример #28
0
    def plot(self):
        self.resize(900, 600)

        # Center the window in the middle of the screen
        frame = self.frameGeometry()
        centerPoint = QtGui.QDesktopWidget().availableGeometry().center()
        frame.moveCenter(centerPoint)
        self.move(frame.topLeft())

        # This creates the central widget
        self.centralwidget = QtGui.QWidget()
        self.centralwidget.setStyleSheet("background-color: rgb(0, 0, 0);")
        self.centralgridLayout = QtGui.QGridLayout(self.centralwidget)
        self.centralgridLayout.setMargin(0)
        # This create the horizontal layout
        self.horizontalLayout = QtGui.QHBoxLayout()
        self.horizontalLayout.setSpacing(2)
        # Create the graphics layout widget
        self.win = pg.GraphicsLayoutWidget(self.centralwidget)
        pg.setConfigOptions(antialias=True)
        self.horizontalLayout.addWidget(self.win)
        self.horizontalLayout.setContentsMargins(0, 0, 0, 0)

        # Generate afrPlot
        self.afrPlot = self.win.addPlot(row=0, col=0)
        # Format afrPlot
        self.afrPlot.setLabel('left', 'Air-Fuel Ratio')
        self.afrPlot.setRange(yRange=[10 - .25, 20 + .25], padding=0.1)
        self.afrPlot.setLimits(yMin=10 - .25, yMax=20 + .25)
        self.afrPlot.showGrid(x=True, y=True, alpha=0.3)
        self.afrPlot.hideButtons()  #Disable auto-scale button
        self.afrPlot.setContentsMargins(0, 0, 0, 0)
        self.afrPlot.hideAxis('bottom')

        # Generate tpsPlot
        self.tpsPlot = self.win.addPlot(row=1, col=0)
        # Format tpsPlot
        self.tpsPlot.setLabel('left', 'Throttle (%)')
        self.tpsPlot.setRange(yRange=[0 - 2.5, 100 + 2.5], padding=0.1)
        self.tpsPlot.setLimits(yMin=0 - 2.5, yMax=100 + 2.5)
        self.tpsPlot.showGrid(x=True, y=True, alpha=0.3)
        self.tpsPlot.setXLink(self.afrPlot)
        self.tpsPlot.hideButtons()  #Disable auto-scale button
        self.tpsPlot.setContentsMargins(0, 0, 0, 0)
        self.tpsPlot.hideAxis('bottom')

        # Generate the velocityPlot
        self.velocityPlot = self.win.addPlot(row=2, col=0)
        # Format velocityPlot
        self.velocityPlot.setLabel('left', 'Velocity (MpH)')
        self.velocityPlot.setRange(yRange=[0 - 2.5, 100 + 2.5], padding=0.1)
        self.velocityPlot.setLimits(yMin=0 - 2.5, yMax=100 + 2.5)
        self.velocityPlot.showGrid(x=True, y=True, alpha=0.3)
        self.velocityPlot.setXLink(self.afrPlot)
        self.velocityPlot.hideButtons()  #Disable auto-scale button
        self.velocityPlot.setContentsMargins(0, 0, 0, 0)
        self.velocityPlot.hideAxis('bottom')

        # Generate the rangePlot
        self.rangePlot = self.win.addPlot(row=3, col=0)
        # Format rangePlot
        self.rangePlot.setLabel('left', 'Dataset')
        self.rangePlot.setRange(yRange=[10 - .25, 20 + .25], padding=0.1)
        self.rangePlot.setLimits(yMin=10 - .25, yMax=20 + .25)
        self.rangePlot.showGrid(x=True, y=True, alpha=0.3)
        self.rangePlot.hideButtons()  #Disable auto-scale button
        self.rangePlot.setContentsMargins(0, 0, 0, 0)

        # Build the UI
        self.centralgridLayout.addLayout(self.horizontalLayout, 0, 0, 1, 1)
        self.setCentralWidget(self.centralwidget)

        # Adjust the plot range to the data
        self.afrPlot.setRange(xRange=[x[0], x[-1]])
        self.afrPlot.setLimits(xMin=x[0], xMax=x[-1])
        self.tpsPlot.setRange(xRange=[x[0], x[-1]])
        self.tpsPlot.setLimits(xMin=x[0], xMax=x[-1])
        self.velocityPlot.setRange(xRange=[x[0], x[-1]])
        self.velocityPlot.setLimits(xMin=x[0], xMax=x[-1])
        self.rangePlot.setRange(xRange=[x[0], x[-1]])
        self.rangePlot.setLimits(xMin=x[0], xMax=x[-1])
        self.region = pg.LinearRegionItem()
        self.region.setZValue(10)
        self.rangePlot.addItem(self.region, ignoreBounds=True)
        # Adjust the range selector

        # Generate curve data
        self.afrPlot.plot(x, yAfr, pen='c', name='AFR')
        self.tpsPlot.plot(x, yTps, pen='m', name='TPS')
        self.velocityPlot.plot(x, velocity, pen='r', name='data')
        self.rangePlot.plot(x, yAfr, pen='y', name='data')

        # Crosshair
        self.lineAfr = pg.InfiniteLine(movable=True, angle=90)
        self.lineTps = pg.InfiniteLine(movable=True, angle=90)
        self.lineVel = pg.InfiniteLine(movable=True, angle=90)
        self.lineRange = pg.InfiniteLine(movable=True, angle=90)
        self.lineAfr.setPos(x[200])
        self.afrPlot.addItem(self.lineAfr)
        self.tpsPlot.addItem(self.lineTps)
        self.velocityPlot.addItem(self.lineVel)
        self.rangePlot.addItem(self.lineRange)
        self.lineRange.setZValue(20)

        self.labelAFR = pg.InfLineLabel(self.lineAfr,
                                        text="Drag",
                                        movable=True,
                                        position=0.5,
                                        color=(200, 200, 100),
                                        fill=(200, 200, 200, 50))

        def afr_line_pos():
            self.linePos = self.lineAfr.getPos()
            self.lineTps.setPos(self.linePos[0])
            self.lineRange.setPos(self.linePos[0])
            self.interpAfr = np.interp(self.linePos[0], x, yAfr)
            self.interpTps = np.interp(self.linePos[0], x, yTps)
            self.interpTmp = np.interp(self.linePos[0], x, tmpC)
            self.interpVel = np.interp(self.linePos[0], x, velocity)
            self.interp = [
                self.interpAfr, self.interpTps, self.interpTmp, self.interpVel
            ]
            #print("%0.2f, %0.2f" %(self.interpAfr, self.interpTps))
            self.labelAFR.setText(
                "AFR: %0.2f\nTPS: %0.1f%%\nTMP: %0.1fC\nVEL: %0.1f" %
                (self.interp[0], self.interp[1], self.interp[2],
                 self.interp[3]))

        def tps_line_pos():
            self.linePos = self.lineTps.getPos()
            self.lineAfr.setPos(self.linePos[0])
            self.lineVel.setPos(self.linePos[0])
            self.lineRange.setPos(self.linePos[0])

        def vel_line_pos():
            self.linePos = self.lineVel.getPos()
            self.lineAfr.setPos(self.linePos[0])
            self.lineTps.setPos(self.linePos[0])
            self.lineRange.setPos(self.linePos[0])

        def range_line_pos():
            self.linePos = self.lineRange.getPos()
            self.lineAfr.setPos(self.linePos[0])
            self.lineTps.setPos(self.linePos[0])
            self.lineVel.setPos(self.linePos[0])

        def update():
            self.region.setZValue(10)
            minX, maxX = self.region.getRegion()
            self.afrPlot.setXRange(minX, maxX, padding=0)
            self.lineAfr.setBounds((minX, maxX))
            self.lineTps.setBounds((minX, maxX))
            self.lineVel.setBounds((minX, maxX))
            self.lineRange.setBounds((minX, maxX))

        self.lineAfr.sigPositionChanged.connect(afr_line_pos)
        self.lineTps.sigPositionChanged.connect(tps_line_pos)
        self.lineVel.sigPositionChanged.connect(vel_line_pos)
        self.lineRange.sigPositionChanged.connect(range_line_pos)
        self.region.sigRegionChanged.connect(update)

        def updateRegion(window, viewRange):
            self.rgn = viewRange[0]
            self.region.setRegion(self.rgn)

        self.afrPlot.sigRangeChanged.connect(updateRegion)
        self.region.setRegion([x[100], x[-100]])