Esempio n. 1
0
    def setPlot(self, plot):
        """setting the ScatterPlotWidget for the node"""
        self.plot = plot

        # ScatterPlotItem for the current position of the 'Pointer'
        self.spiPos = pg.ScatterPlotItem(size=3,
                                         pen=pg.mkPen(None),
                                         brush=pg.mkBrush(255, 255, 255, 255))

        # ScatterPlotItem for the path, while drawing
        self.spiPath = pg.ScatterPlotItem(size=3,
                                          pen=pg.mkPen(None),
                                          brush=pg.mkBrush(255, 0, 0, 255))

        # ScatterPlotItem for the recognized template
        self.spiTemplate = pg.ScatterPlotItem(size=3,
                                              pen=pg.mkPen(None),
                                              brush=pg.mkBrush(0,
                                                               100, 255, 255))

        # setting the x and y range to width and height of the ir camera field
        self.plot.setXRange(0, 1024)
        self.plot.setYRange(0, 768)

        # appending legend to display which color shows which data
        self.legend = pg.LegendItem(offset=(-1, 1))
        self.legend.addItem(self.spiPos, 'position')
        self.legend.addItem(self.spiPath, 'path')
        self.legend.addItem(self.spiTemplate, 'template')
        self.legend.setParentItem(self.plot)
Esempio n. 2
0
 def __init__(self,name=None,items=None,colors=None):
     super(CParameterTree,self).__init__()
     self.name = name
     self.setColumnCount(4)
     self.setHeaderHidden(True)
     self.setDragEnabled(False)
     self.header = pg.TreeWidgetItem([name])
     self.setIndentation(0)
     headerBackgroundColor = pg.mkBrush(color=(100,100,100))
     fontcolor = pg.mkBrush(color=(255,255,255))
     self.setupHeader()
     # self.header.setBackground(0,headerBackgroundColor)
     # self.header.setBackground(1,headerBackgroundColor)
     # self.header.setBackground(2,headerBackgroundColor)
     # self.header.setBackground(3,headerBackgroundColor)
     # self.header.setForeground(0,fontcolor)
     # self.addTopLevelItem(self.header)
     # self.header.setSizeHint(0,QtCore.QSize(-1, 25))
     # self.setColumnWidth (0, 100)
     # self.setColumnWidth (1, 50)
     # self.setColumnWidth (2, 70)
     self.setColumnWidth (3, 5)
     if items is not None: self.names = items
     else: self.names = []
     self.items = {} # main widgets
     self.colors = {} # color widgets
     self.boxes = {} # checkbox widgets
     self.groups = {} # just empty items
     if items: self.addItems(items,colors)
Esempio n. 3
0
    def add_measure_rois(self):
        # First, remove existing rois
        for roi in self._rois:
            self._plot_item.removeItem(roi)

        if len(self._measure_rois) == 0:
            for i in range(3):
                view_range = self._plot_item.viewRange()
                x_vrange = view_range[0][1] - view_range[0][0]
                x_len = x_vrange * 0.25
                x_pos = view_range[0][0] + x_vrange * 0.1 + x_len * 1.1 * i

                roi = LinearRegionItem(values=[x_pos, x_pos + x_len],
                                       brush=pg.mkBrush(
                                           QColor(152, 251, 152, 50)),
                                       removable=False)

                if i == 1:
                    roi.setBrush(pg.mkBrush(QColor(255, 69, 0, 50)))

                self._measure_rois.append(roi)

            for roi in self._measure_rois:
                roi.sigRemoveRequested.connect(
                    lambda: Dispatch.on_updated_roi.emit(
                        measure_rois=self._measure_rois))
                roi.sigRegionChangeFinished.connect(
                    lambda: Dispatch.on_updated_roi.emit(
                        measure_rois=self._measure_rois))

            # Connect events
            Dispatch.on_updated_roi.emit(measure_rois=self._measure_rois)

        for roi in self._measure_rois:
            self._plot_item.addItem(roi)
Esempio n. 4
0
    def __init__(self, pen=None, brush=None, **opts):
        """
        Arguments for each surface are:
           x1,x2 - position of center of _physical surface_
           r1,r2 - radius of curvature
           d1,d2 - diameter of optic
        """
        defaults = dict(x1=-2, r1=100, d1=25.4, x2=2, r2=100, d2=25.4)
        defaults.update(opts)
        ParamObj.__init__(self)
        self.surfaces = [CircleSurface(defaults['r1'], defaults['d1']), CircleSurface(-defaults['r2'], defaults['d2'])]
        pg.GraphicsObject.__init__(self)
        for s in self.surfaces:
            s.setParentItem(self)
        
        if pen is None:
            self.pen = pg.mkPen((220,220,255,200), width=1, cosmetic=True)
        else:
            self.pen = pg.mkPen(pen)
        
        if brush is None: 
            self.brush = pg.mkBrush((230, 230, 255, 30))
        else:
            self.brush = pg.mkBrush(brush)

        self.setParams(**defaults)
Esempio n. 5
0
    def plotMA(self, G, R, z_scores, z_cuttof):
        ratio, intensity = expression.ratio_intensity(G, R)

        validmask = (numpy.isfinite(ratio) &
                     numpy.isfinite(intensity) &
                     numpy.isfinite(z_scores))
        for array in [ratio, intensity, z_scores]:
            if numpy.ma.is_masked(array):
                validmask &= ~array.mask

        filtered_ind = numpy.ma.where(validmask)
        ratio = numpy.take(ratio, filtered_ind)
        intensity = numpy.take(intensity, filtered_ind)
        z_scores = numpy.take(z_scores, filtered_ind)

        red_ind = numpy.ma.where(numpy.ma.abs(z_scores) >= z_cuttof)
        blue_ind = numpy.ma.where(numpy.ma.abs(z_scores) < z_cuttof)

        red_xdata, red_ydata = intensity[red_ind], ratio[red_ind]
        blue_xdata, blue_ydata = intensity[blue_ind], ratio[blue_ind]

        self.graph.clear()
        line = pg.InfiniteLine(pos=(0, 0), angle=0, pen=pg.mkPen((0, 0, 0)))
        self.graph.addItem(line)

        red_points = ScatterPlotItem(
            x=red_xdata, y=red_ydata,
            brush=pg.mkBrush((255, 0, 0, 100)), size=6, antialias=True)
        blue_points = ScatterPlotItem(
            x=blue_xdata, y=blue_ydata,
            brush=pg.mkBrush((0, 0, 255, 100)), size=6, antialias=True)

        self.graph.addItem(red_points)
        self.graph.addItem(blue_points)
Esempio n. 6
0
    def updateSelectedPenPointsGraphics(self, selectedpendata=None):
        if selectedpendata is None:
            selectedpendata = MarkWriteMainWindow.instance().project.selectedpendata

        pen=pen2=None
        brush=brush2=None
        psize=SETTINGS['spatialplot_selectedpoint_size']

        if MarkWriteMainWindow.instance().project.isSelectedDataValidForNewSegment():
            pen = pg.mkPen(SETTINGS['spatialplot_selectedvalid_color'],
                           width=SETTINGS['spatialplot_selectedpoint_size'])
            pen2 = pg.mkPen(SETTINGS['spatialplot_selectedvalid_color'].darker(300),
                           width=SETTINGS['spatialplot_selectedpoint_size'])
            brush = pg.mkBrush(SETTINGS['spatialplot_selectedvalid_color'])
            brush2 = pg.mkBrush(SETTINGS['spatialplot_selectedvalid_color'].darker(300))
        else:
            pen = pg.mkPen(SETTINGS['spatialplot_selectedinvalid_color'],
                           width=SETTINGS['spatialplot_selectedpoint_size'])
            brush = pg.mkBrush(SETTINGS['spatialplot_selectedinvalid_color'])
            pen2 = pg.mkPen(SETTINGS['spatialplot_selectedinvalid_color'].darker(300),
                           width=SETTINGS['spatialplot_selectedpoint_size'])
            brush2 = pg.mkBrush(SETTINGS['spatialplot_selectedinvalid_color'].darker(300))

        penarray = np.empty(selectedpendata.shape[0], dtype=object)
        penarray[:] = pen
        penarray[selectedpendata['pressure'] == 0] = pen2
        brusharray = np.empty(selectedpendata.shape[0], dtype=object)
        brusharray[:] = brush
        brusharray[selectedpendata['pressure'] == 0] = brush2

        self.selectedPlotDataItem.setData(x=selectedpendata[X_FIELD],
                                          y=selectedpendata[Y_FIELD], pen=None,
                                          symbol='o', symbolSize=psize,
                                          symbolBrush=brusharray, symbolPen=penarray)
Esempio n. 7
0
    def generatePicture(self):
        ## pre-computing a QPicture object allows paint() to run much more quickly, 
        ## rather than re-drawing the shapes every time.
        self.picture = QtGui.QPicture()
        p = QtGui.QPainter(self.picture)
        p.setPen(pg.mkPen('w'))
        barWidth = (self.data[1][0] - self.data[0][0]) / 3.
        
        for index,item in enumerate(self.data):
            time = item[0]
            open = item[1]
            high = item[2]
            low = item[3]
            close = item[4]
            
            # 01.draw high-low line,when high == low,it means the symbol is not traded.
            if(high != low):
                p.drawLine(QtCore.QPointF(index, low), QtCore.QPointF(index, high))
            
            # 02.decide the color of candle
            if open > close:
                p.setBrush(pg.mkBrush('g'))
            else:
                p.setBrush(pg.mkBrush('r'))
            
            # 03.draw the candle rect
            x=index-barWidth
            y=open
            width= barWidth*2
            height=close-open

            p.drawRect(QtCore.QRectF(x,y ,width,height))
        p.end()
    def __init__(self, parent = None):
        QtGui.QWidget.__init__(self, parent)
        
        pg.setConfigOption('background', 'w')
        pg.setConfigOption('foreground', 'k')
        pg.setConfigOptions(antialias=False)
        self.scopeWidget = pg.PlotWidget()
        self.scopeWidget.setTitle('Scope trace', size='12')

        self.vbl = QtGui.QVBoxLayout()
        self.vbl.addWidget(self.scopeWidget)
        self.setLayout(self.vbl)
        self.scopeWidget.setLabel('left', 'Signal', units='V')
        self.scopeWidget.setLabel('bottom', 'Time', units='s')
        self.scopeWidget.showGrid(x=False, y=True)
        self.scopeWidget.clear()

        self.lr1 = pg.LinearRegionItem([0,0], brush=pg.mkBrush(0,0,160,80))
        self.lr2 = pg.LinearRegionItem([0,0], brush=pg.mkBrush(52,124,23,80))
        self.lr1.setZValue(10)
        self.lr2.setZValue(10)
        self.scopeWidget.addItem(self.lr2)
        self.scopeWidget.addItem(self.lr1)
        self.lr1.setMovable(False)
        self.lr2.setMovable(False)
Esempio n. 9
0
 def makeGraph(self):
     #g1 = pg.GraphItem(pos=self.pos, adj=self.links[self.rope], pen=0.2, symbol=None)
     brushes = np.where(self.fixed, pg.mkBrush(0,0,0,255), pg.mkBrush(50,50,200,255))
     g2 = pg.GraphItem(pos=self.pos, adj=self.links[self.push & self.pull], pen=0.5, brush=brushes, symbol='o', size=(self.mass**0.33), pxMode=False)
     p = pg.ItemGroup()
     #p.addItem(g1)
     p.addItem(g2)
     return p
Esempio n. 10
0
 def generatePicture(self):
     ## pre-computing a QPicture object allows paint() to run much more quickly, 
     ## rather than re-drawing the shapes every time.
     self.picture = QtGui.QPicture()
     p = QtGui.QPainter(self.picture)
     p.setPen(pg.mkPen('w'))
     halfBarWidth = (self.data[1][0] - self.data[0][0]) / 3.
     
     for index,item in enumerate(self.data):
         time = item[0]
         open = item[1]
         high = item[2]
         low = item[3]
         close = item[4]
         
         if(True):
             x = time
         else:
             x = index
         # 01.draw high-low line,when high == low,it means the symbol is not traded.
         if(high != low):
             p.drawLine(QtCore.QPointF(x, low), QtCore.QPointF(x, high))
         
         # 02.decide the color of candle
         if open > close:
             p.setBrush(pg.mkBrush('g'))
         else:
             p.setBrush(pg.mkBrush('r'))
         
         # 03.draw the candle rect
         x=x-halfBarWidth
         y=open
         barWidth= halfBarWidth*2
         height=close-open
         rectToDraw = QtCore.QRectF(x,y ,barWidth,height)
         
         if(not self.bSelected):
             for lastRect in self.lastClicked:
                 for newRect in self.ptsClicked:
                     if(lastRect == newRect):
                         self.bSelected = True
         
         
         
         if(not self.bSelected):
             for rect in self.ptsClicked:
                 if(rect == rectToDraw):
                     self.lastClicked = self.ptsClicked 
                     p.setPen(pg.mkPen('w'))
                     p.setBrush(pg.mkBrush('w')) 
         else:
             self.bSelected = False
             
         p.drawRect(QtCore.QRectF(x,y ,barWidth,height))
         self.dataRects[index]=QtCore.QRectF(x,y ,barWidth,height)
     p.end()
	def setupGUI(self):
		self.setWindowTitle("Edit effectibve stress formula")
		self.setGeometry(500, 300, 350, 200)
		# self.centralWidget = QtGui.QWidget()
		# self.setCentralWidget(self.centralWidget)
		self.centralLayout = QtGui.QVBoxLayout()
		# self.centralWidget.setLayout(self.centralLayout)
		self.setLayout(self.centralLayout)
		self.variablesText = QtGui.QLabel('')

		tree = pg.TreeWidget()
		tree.setHeaderHidden(True)
		tree.setIndentation(0)
		tree.setColumnCount(3)
		
		# stuff to make gray background for tree widget
		g = pg.mkBrush(240,240,240)
		b = pg.mkBrush(0,0,0)
		w = pg.mkBrush(255,255,255)
		bgBrush = pg.mkBrush(255,0,0)
		tree.setFrameShape(QtGui.QFrame.NoFrame)
		palette = QtGui.QPalette(g, g, g, g, g, b, b, g, g)
		# tree.setPalette(palette)

		axStressItem = pg.TreeWidgetItem(['Axial stress'])
		# axStressItem.setTextAlignment(0,0)
		# axStressItem.setBackground(1,w)
		confStressItem = pg.TreeWidgetItem(['Confining pressure'])
		# confStressItem.setTextAlignment(0,0)
		porePressItem = pg.TreeWidgetItem(['Pore pressure'])
		biotItem = pg.TreeWidgetItem(['Biot coefficient'])
		porePressItem.setTextAlignment(0,0)

		self.axStressBox = QtGui.QLineEdit()
		self.confStressBox = QtGui.QLineEdit()
		self.porePressBox = QtGui.QLineEdit()
		self.biotBox = pg.SpinBox(value=1, bounds=[0.5, 1],step=0.1)
		
		axStressItem.setWidget(1,self.axStressBox)
		confStressItem.setWidget(1,self.confStressBox)
		biotItem.setWidget(1,self.biotBox)

		porePressItem.setWidget(1,self.porePressBox)
		tree.addTopLevelItem(axStressItem)
		tree.addTopLevelItem(confStressItem)
		tree.addTopLevelItem(porePressItem)
		tree.addTopLevelItem(biotItem)

		self.centralLayout.addWidget(self.variablesText)
		self.centralLayout.addWidget(tree)
		# self.centralLayout.addWidget(self.buttonsWidget)

		tree.setColumnWidth(0,120)
		tree.setColumnWidth(1,170)
		tree.setColumnWidth(2,10)
Esempio n. 12
0
    def change_to_image(self, image):
        """ Set curTrace to TRACE. Update all the buttons/table_slice
        and then highlight the proper row in the table_traces."""
        # Deselecting the previous curTrace
        if self.curImage is not None:
            index = -1
            for row in range(self.table_images.rowCount()):
                item = self.table_images.item(row, 0)
                if str(item.text()) == self.curImage.name:
                    index = row
            if index != -1: 
                item = self.table_images.item(index, 0)
                item.setBackground(pqg.mkBrush((255, 255, 255, 255)))

        # Selecting the current trace
        index = -1
        for row in range(self.table_images.rowCount()):
            item = self.table_images.item(row, 0)
            if str(item.text()) == image.name:
                index = row
        if index != -1:
            item = self.table_images.item(index, 0)
            item.setBackground(pqg.mkBrush((0, 255, 127, 100)))

        if self.curImage is not None:
            self.curImage.gradient = self.plot.getHistogramWidget().gradient.saveState()
            self.curImage.levels = self.plot.getHistogramWidget().getLevels()
            if self.plot.axes.get('t', None) is not None:
                self.curImage.time = self.plot.timeLine.value()

            self.curImage.savedGradient = self.gradient_isocurve.saveState()
            self.curImage.remove_isocurves()

        self.curImage = image
        image.update_slice_table(self.table_slice)
        self.sync_buttons()

        if image.gradient is not None:
            self.plot.getHistogramWidget().gradient.restoreState(image.gradient)

        if image.valName is not None:
            image.display_image()
        else:
            self.plot.clear()

        if image.levels is not None:
            self.plot.setLevels(*image.levels)
        if image.time is not None and self.plot.axes['t'] is not None:
            self.plot.timeLine.setValue(image.time)
            self.plot.timeLineChanged()

        if image.savedGradient is not None:
            self.gradient_isocurve.restoreState(image.savedGradient)
        self.table_isocurve.setRowCount(0)
        image.init_isocurves()
Esempio n. 13
0
    def setPlot(self, plot):
        self.plot = plot
        self.spi = pg.ScatterPlotItem(size=10,
                                      pen=pg.mkPen(None),
                                      brush=pg.mkBrush(255, 255, 255, 255))
        self.spi2 = pg.ScatterPlotItem(size=10,
                                      pen=pg.mkPen(None),
                                      brush=pg.mkBrush(255, 0, 0, 255))

        self.plot.setXRange(0, 1024)
        self.plot.setYRange(0, 768)
Esempio n. 14
0
def test_scatterplotitem():
    plot = pg.PlotWidget()
    # set view range equal to its bounding rect.
    # This causes plots to look the same regardless of pxMode.
    plot.setRange(rect=plot.boundingRect())

    # test SymbolAtlas accepts custom symbol
    s = pg.ScatterPlotItem()
    symbol = QtGui.QPainterPath()
    symbol.addEllipse(QtCore.QRectF(-0.5, -0.5, 1, 1))
    s.addPoints([{'pos': [0,0], 'data': 1, 'symbol': symbol}])

    for i, pxMode in enumerate([True, False]):
        for j, useCache in enumerate([True, False]):
            s = pg.ScatterPlotItem()
            s.opts['useCache'] = useCache
            plot.addItem(s)
            s.setData(x=np.array([10,40,20,30])+i*100, y=np.array([40,60,10,30])+j*100, pxMode=pxMode)
            s.addPoints(x=np.array([60, 70])+i*100, y=np.array([60, 70])+j*100, size=[20, 30])

            # Test uniform spot updates
            s.setSize(10)
            s.setBrush('r')
            s.setPen('g')
            s.setSymbol('+')
            app.processEvents()

            # Test list spot updates
            s.setSize([10] * 6)
            s.setBrush([pg.mkBrush('r')] * 6)
            s.setPen([pg.mkPen('g')] * 6)
            s.setSymbol(['+'] * 6)
            s.setPointData([s] * 6)
            app.processEvents()

            # Test array spot updates
            s.setSize(np.array([10] * 6))
            s.setBrush(np.array([pg.mkBrush('r')] * 6))
            s.setPen(np.array([pg.mkPen('g')] * 6))
            s.setSymbol(np.array(['+'] * 6))
            s.setPointData(np.array([s] * 6))
            app.processEvents()

            # Test per-spot updates
            spot = s.points()[0]
            spot.setSize(20)
            spot.setBrush('b')
            spot.setPen('g')
            spot.setSymbol('o')
            spot.setData(None)
            app.processEvents()

    plot.clear()
 def generatePicture(self):
     self.picture = QtGui.QPicture()
     p = QtGui.QPainter(self.picture)
     p.setPen(pg.mkPen('w'))
     w = (self.data[1][0] - self.data[0][0]) / 3.
     for (t, open, close, min, max) in self.data:
         p.drawLine(QtCore.QPointF(t, min), QtCore.QPointF(t, max))
         if open > close:
             p.setBrush(pg.mkBrush('r'))
         else:
             p.setBrush(pg.mkBrush('g'))
         p.drawRect(QtCore.QRectF(t-w, open, w*2, close-open))
     p.end()
Esempio n. 16
0
 def createDefaultPenBrushForData(self, pdat):
     pen = pg.mkPen(SETTINGS['spatialplot_default_color'],
                    width=SETTINGS['spatialplot_default_point_size'])
     pen2 = pg.mkPen(SETTINGS['spatialplot_default_color'].lighter(),
                     width=SETTINGS['spatialplot_default_point_size'])
     brush = pg.mkBrush(SETTINGS['spatialplot_default_color'])
     brush2 = pg.mkBrush(SETTINGS['spatialplot_default_color'].lighter())
     penarray = np.empty(pdat.shape[0], dtype=object)
     penarray[:] = pen
     penarray[pdat['pressure'] == 0] = pen2
     brusharray = np.empty(pdat.shape[0], dtype=object)
     brusharray[:] = brush
     brusharray[pdat['pressure'] == 0] = brush2
     return brusharray, penarray
Esempio n. 17
0
    def plotData(self, sz, wx, wy):
        self.plot(sz, wx, 
                  pen = None,
                  symbol = 'o',
                  symbolPen = pyqtgraph.mkPen(255,0,0),
                  symbolBrush = pyqtgraph.mkBrush(0,0,255),
                  symbolSize = 6)

        self.plot(sz, wy, 
                  pen = None,
                  symbol = 'o',
                  symbolPen = pyqtgraph.mkPen(0,255,0),
                  symbolBrush = pyqtgraph.mkBrush(0,0,255),
                  symbolSize = 6)
Esempio n. 18
0
 def generatePicture(self):
     ## pre-computing a QPicture object allows paint() to run much more quickly, 
     ## rather than re-drawing the shapes every time.
     self.picture = QtGui.QPicture()
     p = QtGui.QPainter(self.picture)
     p.setPen(pg.mkPen('w'))
     w = (self.data[1][0] - self.data[0][0]) / 3.
     for (t, open, close, min, max) in self.data:
         p.drawLine(QtCore.QPointF(t, min), QtCore.QPointF(t, max))
         if open > close:
             p.setBrush(pg.mkBrush('r'))
         else:
             p.setBrush(pg.mkBrush('g'))
         p.drawRect(QtCore.QRectF(t-w, open, w*2, close-open))
     p.end()
Esempio n. 19
0
 def setupHeader(self):
     self.header = pg.TreeWidgetItem([self.name])
     self.setIndentation(0)
     headerBackgroundColor = pg.mkBrush(color=(100,100,100))
     fontcolor = pg.mkBrush(color=(255,255,255))
     self.header.setBackground(0,headerBackgroundColor)
     self.header.setBackground(1,headerBackgroundColor)
     self.header.setBackground(2,headerBackgroundColor)
     self.header.setBackground(3,headerBackgroundColor)
     self.header.setForeground(0,fontcolor)
     self.addTopLevelItem(self.header)
     self.header.setSizeHint(0,QtCore.QSize(-1, 25))
     self.setColumnWidth (0, 100)
     self.setColumnWidth (1, 50)
     self.setColumnWidth (2, 70)
Esempio n. 20
0
 def generatePicture(self):
     # pre-computing a QPicture object allows paint() to run much more quickly,
     # rather than re-drawing the shapes every time.
     self.picture = QtGui.QPicture()
     p = QtGui.QPainter(self.picture)
     p.setPen(pg.mkPen('w'))
     barWidth = 1 / 3.
     for (open, close, min, max, index) in self.data:
         p.drawLine(QtCore.QPointF(index, min), QtCore.QPointF(index, max))
         if open > close:
             p.setBrush(pg.mkBrush('r'))
         else:
             p.setBrush(pg.mkBrush('g'))
         p.drawRect(QtCore.QRectF(index - barWidth, open, barWidth * 2, close - open))
     p.end()
Esempio n. 21
0
    def __init__(self):

        QtGui.QMainWindow.__init__(self)

        # variables
        self.columnSize = 20
        self.rowSize = 20
        self.xInitPos = 0
        self.yInitPos = 0
        self.state = conway.CONWAY(self.rowSize,self.columnSize)
        self.alive = 0
        self.aliveEvolution = []
        self.color1 = pg.mkBrush(255,255,255)
        self.color2 = pg.mkBrush(0,0,0)
        self.brushes = []
        self.fileName = ''
        self.pause = True
        self.generation = 0

        # se carga la ui
        self.ui = uic.loadUi('ventana.ui',self)

        # se conectan los botones en la ui a sus funciones
        self.ui.connect(self.ui.tick, QtCore.SIGNAL('clicked()'), self.nextState)
        self.ui.connect(self.ui.botonStartPause, QtCore.SIGNAL('clicked()'), self.startPause)
        self.ui.connect(self.ui.botonRestart, QtCore.SIGNAL('clicked()'), self.reloadState)
        self.ui.connect(self.ui.botonClean, QtCore.SIGNAL('clicked()'), self.cleanState)
        self.ui.connect(self.ui.botonOpen, QtCore.SIGNAL('clicked()'), self.openFileDialog)
        self.ui.sizeOptions.valueChanged.connect(self.gridSize)
        self.ui.speedSlide.valueChanged.connect(self.changeSpeed)
        self.ui.xPosValue.textEdited.connect(self.changeXInitPos)
        self.ui.yPosValue.textEdited.connect(self.changeYInitPos)
        
        # se crea el plot con la matriz de celdas
        self.gfx = self.ui.PlotView.addPlot()
        self.restartPlot()
        self.createGrid()
        self.updateGrid()

        # se crea el plot con la grafica de celdas vivas
        self.gfx2 = self.ui.PlotView2.addPlot(title='Celdas Vivas')
        self.restartPlot2()

        # Timer
        self.timer = pg.QtCore.QTimer()
        self.timer.timeout.connect(self.updateTimer)
        self.TIME_INTERVAL = 1000
        self.TIME_INTERVAL_MAX = 2000
Esempio n. 22
0
    def __init__(self, parent=None, **kwargs):
        pg.PlotWidget.__init__(self, parent, **kwargs)

        self.getAxis("bottom").setLabel("Score")
        self.getAxis("left").setLabel("Counts")

        self.__data = None
        self.__histcurve = None

        self.__mode = Histogram.NoSelection
        self.__min = 0
        self.__max = 0

        def makeline(pos):
            pen = QtGui.QPen(Qt.darkGray, 1)
            pen.setCosmetic(True)
            line = InfiniteLine(angle=90, pos=pos, pen=pen, movable=True)
            line.setCursor(Qt.SizeHorCursor)
            return line

        self.__cuthigh = makeline(self.__max)
        self.__cuthigh.sigPositionChanged.connect(self.__on_cuthigh_changed)
        self.__cuthigh.sigPositionChangeFinished.connect(self.selectionEdited)
        self.__cutlow = makeline(self.__min)
        self.__cutlow.sigPositionChanged.connect(self.__on_cutlow_changed)
        self.__cutlow.sigPositionChangeFinished.connect(self.selectionEdited)

        brush = pg.mkBrush((200, 200, 200, 180))
        self.__taillow = pg.PlotCurveItem(
            fillLevel=0, brush=brush, pen=QtGui.QPen(Qt.NoPen))
        self.__taillow.setVisible(False)

        self.__tailhigh = pg.PlotCurveItem(
            fillLevel=0, brush=brush, pen=QtGui.QPen(Qt.NoPen))
        self.__tailhigh.setVisible(False)
    def draw_path(self):
        path = self.combineXYPoints()
        points = []
        for i in range(0, len(path)):
            points.append(Point(path[i][0], path[i][1]))

        # display points
        if len(points) >= 3:
            points = resample(points, self.sample_size)
            if points is not None:
                path = []
                for i in range(0, len(points)):
                    path.append([points[i].x, points[i].y])

                self.pathScatter.addPoints(
                    pos=np.array(path), brush=pg.mkBrush(255, 255, 255, 120))

                # handle pressed keys
                if self.pressed_key is 'A':
                    self.compare_template()
                elif self.pressed_key is 'B':
                    self.create_template()

        self.path['x'] = []
        self.path['y'] = []
        self.pressed_key = None
Esempio n. 24
0
	def colorSelected(self, color):
		if color.isValid():
			self.color=QColor(color.name())
			self.pen.setColor(self.color)
			self.path_item.setPen(self.pen)
			self.ti.fill = pg.mkBrush(self.color)
		self.update()
Esempio n. 25
0
 def __start(self, plot_points, frame_rate, title = 'RPLIDAR Data Plot'):
     self.x = [0]*plot_points # x value data generated from dist*sin(theta)
     self.y = [0]*plot_points # y value data generated from dist*cos(theta)
     self.plot_points = plot_points
     # Create GUI Graphics and Window; Set up parameters
     app = QtGui.QApplication([])
     mw = QtGui.QMainWindow()
     mw.resize(800,800)
     view = pg.GraphicsLayoutWidget()  ## GraphicsView with GraphicsLayout inserted by default
     mw.setCentralWidget(view)
     mw.show() # Show the created GUI
     mw.setWindowTitle(title)
     # Create plot and set plot parameters
     w1 = view.addPlot() # Returns a PlotItem object
     w1.showGrid(x=True,y=True)
     w1.setMenuEnabled()
     w1.getViewBox().setXRange(min=-0.8,max=0.8)
     w1.getViewBox().setYRange(min=-1.0,max=1.0)
     w1.setLabel(axis='left',text='Y Distance',units='m')
     w1.setLabel(axis='bottom',text='X Distance',units='m')
     w1.setTitle(title=title)
     # Create scatter plot
     s1 = pg.ScatterPlotItem(size=3, pen=pg.mkPen(None), brush=pg.mkBrush(255, 0, 0, 120))
     s1.addPoints(self.x,self.y)
     # Add scatter plot to the window
     w1.addItem(s1)
     self.s1 = s1
     # Create plot GUI update timer
     timer = pg.QtCore.QTimer()
     timer.timeout.connect(self.__update_plot)
     timer.start(frame_rate)
     # Load plot
     if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
         QtGui.QApplication.instance().exec_()
Esempio n. 26
0
def plot_trace(xy, ids = None, depth = 0, colormap = 'rainbow', line_color = 'k', line_width = 1, point_size = 5, title = None):
  """Plot trajectories with positions color coded according to discrete ids"""
  
  #if ids is not None:
  uids = np.unique(ids);
  
  cmap = cm.get_cmap(colormap);
  n = len(uids);
  colors = cmap(range(n), bytes = True);
  
  #lines
  if line_width is not None:
    #plt.plot(xy[:,0], xy[:,1], color = lines);    
    plot = pg.plot(xy[:,0], xy[:,1], pen = pg.mkPen(color = line_color, width = line_width))    
  else:
    plot = pg.plot(title = title);
    
  if ids is None:
    sp = pg.ScatterPlotItem(pos = xy, size=point_size, pen=pg.mkPen(colors[0])); #, pxMode=True);
  else:
    sp = pg.ScatterPlotItem(size=point_size); #, pxMode=True);
    spots = [];
    for j,i in enumerate(uids):
      idx = ids == i;
      spots.append({'pos': xy[idx,:].T, 'data': 1, 'brush':pg.mkBrush(colors[j])}); #, 'size': point_size});
    sp.addPoints(spots)
  
  plot.addItem(sp);
  
  return plot;
Esempio n. 27
0
def violin_plot(ax, data, pos, dist=.0, bp=False):
    '''
    create violin plots on an axis
    '''

    if data is None or len(data) == 0:
        return  # skip trying to do the plot

    dist = max(pos)-min(pos)
    w = min(0.15*max(dist,1.0),0.5)
    for i, d in enumerate(data):
        if d == [] or len(d) == 0:
            continue
        k = scipy.stats.gaussian_kde(d) #calculates the kernel density
        m = k.dataset.min() #lower bound of violin
        M = k.dataset.max() #upper bound of violin
        y = np.arange(m, M, (M-m)/100.) # support for violin
        v = k.evaluate(y) #violin profile (density curve)
        v = v / v.max() * w #scaling the violin to the available space
        c1 = pg.PlotDataItem(y=y, x=pos[i]+v, pen=pg.mkPen('k', width=0.5))
        c2 = pg.PlotDataItem(y=y, x=pos[i]-v, pen=pg.mkPen('k', width=0.5))
        #mean = k.dataset.mean()
        #vm = k.evaluate(mean)
        #vm = vm * w
        #ax.plot(x=np.array([pos[i]-vm[0], pos[i]+vm[0]]), y=np.array([mean, mean]), pen=pg.mkPen('k', width=1.0))
        ax.addItem(c1)
        ax.addItem(c2)
        #ax.addItem(hbar)
        f = pg.FillBetweenItem(curve1=c1, curve2=c2, brush=pg.mkBrush((255, 255, 0, 96)))
        ax.addItem(f)

    if bp:
       pass
 def show(self):
     if self._view is None:
         pg.mkQApp()
         self._view_widget = pg.GraphicsLayoutWidget()
         self._view = self._view_widget.addViewBox(0, 0)
         v = self._view
         cell_ids = sorted(self.cells.keys())
         pos = np.array([self.cells[i].position[:2] for i in cell_ids])
         if len(self.connections) == 0:
             adj = np.empty((0,2), dtype='int')
         else:
             adj = np.array(self.connections) - 1
         colors = []
         for cid in cell_ids:
             cell = self.cells[cid]
             color = [0, 0, 0]
             for i,cre in enumerate(self.cre_types):
                 if cell.labels[cre] == '+':
                     color[i] = 255
             colors.append(color)
         brushes = [pg.mkBrush(c) for c in colors]
         print(pos)
         print(adj)
         print(colors)
         self._graph = pg.GraphItem(pos=pos, adj=adj, size=30, symbolBrush=brushes)
         v.addItem(self._graph)
     self._view_widget.show()
Esempio n. 29
0
    def __init__(self, clock):
        pg.ItemGroup.__init__(self)
        self.size = clock.size
        self.item = QtGui.QGraphicsEllipseItem(QtCore.QRectF(0, 0, self.size, self.size))
        self.item.translate(-self.size*0.5, -self.size*0.5)
        self.item.setPen(pg.mkPen(100,100,100))
        self.item.setBrush(clock.brush)
        self.hand = QtGui.QGraphicsLineItem(0, 0, 0, self.size*0.5)
        self.hand.setPen(pg.mkPen('w'))
        self.hand.setZValue(10)
        self.flare = QtGui.QGraphicsPolygonItem(QtGui.QPolygonF([
            QtCore.QPointF(0, -self.size*0.25),
            QtCore.QPointF(0, self.size*0.25),
            QtCore.QPointF(self.size*1.5, 0),
            QtCore.QPointF(0, -self.size*0.25),
            ]))
        self.flare.setPen(pg.mkPen('y'))
        self.flare.setBrush(pg.mkBrush(255,150,0))
        self.flare.setZValue(-10)
        self.addItem(self.hand)
        self.addItem(self.item)
        self.addItem(self.flare)
 
        self.clock = clock
        self.i = 1
        
        self._spaceline = None
Esempio n. 30
0
 def plotWxWyData(self, wx, wy, cat):
     self.plot(wx, wy,
               pen = None,
               symbol = 'o',
               symbolPen = pyqtgraph.mkPen(255,0,0),
               symbolBrush = pyqtgraph.mkBrush(0,0,255),
               symbolSize = 6)
Esempio n. 31
0
w2.setAspectLocked(True)
view.nextRow()
w3 = view.addPlot()
w4 = view.addPlot()
print("Generating data, this takes a few seconds...")

# There are a few different ways we can draw scatter plots; each is optimized for different types of data:


# 1) All spots identical and transform-invariant (top-left plot).
# In this case we can get a huge performance boost by pre-rendering the spot
# image and just drawing that image repeatedly.

n = 300
s1 = pg.ScatterPlotItem(size=10, pen=pg.mkPen(
    None), brush=pg.mkBrush(255, 255, 255, 120))
pos = np.random.normal(size=(2, n), scale=1e-5)
spots = [{'pos': pos[:, i], 'data': 1}
         for i in range(n)] + [{'pos': [0, 0], 'data': 1}]
s1.addPoints(spots)
w1.addItem(s1)

# Make all plots clickable
lastClicked = []


def clicked(plot, points):
    global lastClicked
    for p in lastClicked:
        p.resetPen()
    print("clicked points", points)
def pg_brush_cycler(i=0):
    return pg.mkBrush(color_cycler(i))
Esempio n. 33
0
    def plot_stepsAndSpikes(self, data, posSpike, negSpike):

        self.glmProcTimeSeries = np.append(self.glmProcTimeSeries, data, axis=1)
        sz, l = self.glmProcTimeSeries.shape

        for i in range(sz):
            if posSpike[i] == 1:
                if self.posSpikes[str(i)].any():
                    self.posSpikes[str(i)] = np.append(self.posSpikes[str(i)], l-1)
                else:
                    self.posSpikes[str(i)] = np.array([l-1])
            if negSpike[i] == 1:
                if self.negSpikes[str(i)].any():
                    self.negSpikes[str(i)] = np.append(self.negSpikes[str(i)], l-1)
                else:
                    self.negSpikes[str(i)] = np.array([l-1])

        x = np.arange(0, l, dtype=np.float64)

        plotitem = self.spikes_plot.getPlotItem()
        plotitem.clear()
        plots = []

        muster = self.drawMusterPlot(plotitem)

        for i, c in zip(range(sz), config.ROI_PLOT_COLORS):
            pen = pg.mkPen(color=c, width=config.ROI_PLOT_WIDTH)
            p = plotitem.plot(pen=pen)
            plots.append(p)

        self.plot_stepsAndSpikes.__dict__[plotitem] = plots, muster

        for p, y in zip(self.plot_stepsAndSpikes.__dict__[plotitem][0], self.glmProcTimeSeries):
            p.setData(x=x, y=np.array(y))

        for i, c in zip(range(sz), config.ROI_PLOT_COLORS):

            if self.posSpikes[str(i)].any():
                brush = pg.mkBrush(color=c)
                p = plotitem.scatterPlot(symbol='o', size=20, brush=brush)
                plots.append(p)
                plots[-1].setData(x=x[self.posSpikes[str(i)]], y=self.glmProcTimeSeries[i, self.posSpikes[str(i)]])

                pen = pg.mkPen(color=pg.mkColor(0, 0, 0), width=1.5*config.ROI_PLOT_WIDTH)
                p = plotitem.plot(pen=pen)
                plots.append(p)

                inds = self.posSpikes[str(i)]
                inds = np.array(list(itertools.chain.from_iterable(zip(inds, inds-1))))

                y = np.array(self.glmProcTimeSeries[i,inds])
                x1 = inds

                plots[-1].setData(x=x1, y=y, connect='pairs')

            if self.negSpikes[str(i)].any():
                brush = pg.mkBrush(color=c)
                p = plotitem.scatterPlot(symbol='d', size=20, brush=brush)
                plots.append(p)
                plots[-1].setData(x=x[self.negSpikes[str(i)]], y=self.glmProcTimeSeries[i, self.negSpikes[str(i)]])

                pen = pg.mkPen(color=pg.mkColor(0, 0, 0), width=1.5*config.ROI_PLOT_WIDTH)
                p = plotitem.plot(pen=pen)
                plots.append(p)

                inds = self.negSpikes[str(i)]
                inds = np.array(list(itertools.chain.from_iterable(zip(inds, inds - 1))))

                y = np.array(self.glmProcTimeSeries[i,inds])
                x1 = inds

                plots[-1].setData(x=x1, y=y, connect='pairs')

        cnt = 0;
        for i in range(sz):
            cnt = cnt + np.count_nonzero(self.posSpikes[str(i)])
        names = ['( Circles ) <br>Positive spikes: ' + str(int(cnt))]

        cnt = 0;
        for i in range(sz):
            cnt = cnt + np.count_nonzero(self.negSpikes[str(i)])
        names.append('<br>( Diamonds )<br>Negative spikes: ' + str(int(cnt)))
        pens = [pg.mkPen(color=config.STAT_PLOT_COLORS[0], width=1.2), pg.mkPen(color=config.STAT_PLOT_COLORS[0], width=1.2)]
        self.makeTextValueLabel(self.spikesLabel, names, pens)

        items = plotitem.listDataItems()

        for m in self.plot_stepsAndSpikes.__dict__[plotitem][1]:
            items.remove(m)

        if data.any():
            plotitem.setYRange(np.min(self.glmProcTimeSeries), np.max(self.glmProcTimeSeries), padding=0.0)
Esempio n. 34
0
from PyQt5 import QtCore, QtGui, QtWidgets
import numpy as np
import pyqtgraph as pg

STYLE = {
    'pen': pg.mkPen(0, 0, 0),
    'pen-hover': pg.mkPen(255, 255, 255, width=1),
    'brush': pg.mkBrush(100, 100, 100),
    'brush-hover': pg.mkBrush(150, 150, 150),
    'brush-selected': pg.mkBrush(200, 200, 200),
    'underline-central': pg.mkPen(176, 35, 48, width=3),
    'underline-flanker': pg.mkPen(51, 152, 188, width=3)
}
STYLE['underline-central'].setCapStyle(QtCore.Qt.FlatCap)
STYLE['underline-flanker'].setCapStyle(QtCore.Qt.FlatCap)


class ClickableBar(QtWidgets.QGraphicsRectItem):
    def __init__(self, barplot, x, y, w, h):
        self.barplot = barplot
        self.x = x
        _scale = 10000
        QtWidgets.QGraphicsRectItem.__init__(self, QtCore.QRectF(x * _scale, y * _scale, w * _scale, h * _scale))
        self.setScale(1 / _scale)
        self.setPen(STYLE['pen'])
        self.setBrush(STYLE['brush'])
        self.setAcceptHoverEvents(True)
        self.is_current_flag = False

    def hoverEnterEvent(self, ev):
        self.savedPen = self.pen()
Esempio n. 35
0
    'lomid': "#4f98ca",
    'dark': "#272727",
    'darker': "#23374d",
}

numlabelsize = 22
txtlabelsize = 20

# STYLING
numfont = QtGui.QFont("Avenir Next")  # requires macos
numfont.setPixelSize(numlabelsize)

txtfont = QtGui.QFont("Avenir Next")  # requires macos
txtfont.setPixelSize(txtlabelsize)

brushes = {k: pg.mkBrush(c) for k, c in colors.items()}

pg.setConfigOptions(antialias=True)
pg.setConfigOption('background', colors['dark'])
pg.setConfigOption('foreground', colors['light'])

QPushButton_style = f"""
QPushButton{{
	color: {colors['light']};
	background-color: transparent;
	border: 1px solid #4589b2;
	padding: 5px;

}}

QPushButton::hover{{
 def paint(self, painter: QPainter, *_):
     painter.save()
     painter.setPen(pg.mkPen((255, 255, 0), width=1))
     painter.setBrush(pg.mkBrush(255, 255, 0, 100))
     painter.drawRect(self.__rect)
     painter.restore()
    app = TaurusApplication()

    # a standard pyqtgraph plot_item
    w = pg.PlotWidget()

    # add legend to the plot, for that we have to give a name to plot items
    w.addLegend()

    # adding a regular data item (non-taurus)
    c1 = pg.PlotDataItem(name="st plot", pen="b", fillLevel=0, brush="c")
    c1.setData(numpy.arange(300) / 300.0)
    w.addItem(c1)

    pen = pg.mkPen(color="r", style=4)
    brush = pg.mkBrush(color="b")
    brush.setStyle(3)

    # adding a taurus data item
    # c2 = TaurusPlotDataItem(name='st2 plot', pen='r', symbol='o')
    c2 = TaurusPlotDataItem(pen=pen, name="foo")
    # c2 = TaurusPlotDataItem()

    # c2.loadConfigFile('tmp/conf.cfg')

    c2.setModel('eval:Quantity(rand(256),"m")')
    # c2.setModel('sys/tg_test/1/wave')
    # c2.setModel(None)
    # c2.setXModel(None)

    # c2.setXModel('eval:Quantity(rand(256),"m")')
Esempio n. 38
0
    def load_course(self):
        if len(self.config.logger.course.latitude) == 0:
            return

        t = datetime.datetime.utcnow()

        cp = pg.CoursePlotItem(
            x=self.config.logger.course.longitude,
            y=self.get_mod_lat_np(self.config.logger.course.latitude),
            brushes=self.config.logger.course.colored_altitude,
            width=6)
        self.plot.addItem(cp)

        #test
        if not self.config.G_IS_RASPI:
            plot_verification = pg.ScatterPlotItem(pxMode=True)
            test_points = []
            for i in range(len(self.config.logger.course.longitude)):
                p = {
                    'pos': [
                        self.config.logger.course.longitude[i],
                        self.get_mod_lat(self.config.logger.course.latitude[i])
                    ],
                    'size':
                    2,
                    'pen': {
                        'color': 'w',
                        'width': 1
                    },
                    'brush':
                    pg.mkBrush(color=(255, 0, 0))
                }
                test_points.append(p)
            plot_verification.setData(test_points)
            self.plot.addItem(plot_verification)
        print("\tpyqt_graph : course_plot : ",
              (datetime.datetime.utcnow() - t).total_seconds(), "sec")

        #course point
        if len(self.config.logger.course.point_longitude) == 0:
            return

        t = datetime.datetime.utcnow()

        self.course_points_plot = pg.ScatterPlotItem(pxMode=True, symbol="t")
        self.course_points = []

        for i in reversed(range(len(
                self.config.logger.course.point_longitude))):
            #if self.config.logger.course.point_type[i] == "Straight":
            #  continue
            cp = {
                'pos': [
                    self.config.logger.course.point_longitude[i],
                    self.get_mod_lat(
                        self.config.logger.course.point_latitude[i])
                ],
                'size':
                10,
                'pen': {
                    'color': 'r',
                    'width': 1
                },
                'brush':
                pg.mkBrush(color=(255, 0, 0))
            }
            self.course_points.append(cp)
        self.course_points_plot.setData(self.course_points)
        self.plot.addItem(self.course_points_plot)

        print("\tpyqt_graph : load course_points_plot : ",
              (datetime.datetime.utcnow() - t).total_seconds(), "sec")
        t = datetime.datetime.utcnow()

        self.course_points_label = []
        if self.config.G_FONT_NAME != "":
            self.font = QtGui.QFont(self.config.G_FONT_NAME)
        for i in reversed(range(len(
                self.config.logger.course.point_longitude))):
            #if self.config.logger.course.point_type[i] == "Straight":
            #  continue

            #CoursePointType from TCX schema
            # https://www8.garmin.com/xmlschemas/TrainingCenterDatabasev2.xsd
            #  Generic, Summit, Valley, Water, Food, Danger,
            #  Left, Right, Straight, First Aid,
            #  4th Category, 3rd Category, 2nd Category, 1st Category,
            #  Hors Category, Sprint,

            #arrow = ""
            #if self.config.logger.course.point_type[i] == "Left":
            #  arrow ="backarrow_black.png"
            #elif self.config.logger.course.point_type[i] == "Right":
            #  arrow ="nextarrow_black.png"
            #else:
            #  continue

            # Create text object, use HTML tags to specify color/size
            #  http://www.pyqtgraph.org/documentation/graphicsItems/textitem.html
            text = pg.TextItem(
                #html = '<div style="text-align: center">' + '<img src="img/' + arrow + '" /></div>',
                #html = '<div style="text-align: center">' + self.config.logger.course.point_name[i] + '</div>',
                text=self.config.logger.course.point_name[i],
                anchor=(-0.1, 1.2),
                angle=0,
                border=(255, 0, 0),
                fill=(255, 255, 255),
                color=(0, 0, 0),
            )
            #text.setTextWidth(int(self.config.G_WIDTH/2.5))
            if self.config.G_FONT_NAME != "":
                text.setFont(self.font)
            self.plot.addItem(text)
            text.setPos(
                self.config.logger.course.point_longitude[i],
                self.get_mod_lat(self.config.logger.course.point_latitude[i]))
            self.course_points_label.append(text)

        print("\tpyqt_graph : display course_points_plot : ",
              (datetime.datetime.utcnow() - t).total_seconds(), "sec")
Esempio n. 39
0
def brush(color):
    return pg.mkBrush(color)
Esempio n. 40
0
    def load_course(self):

        if len(self.config.logger.course.distance) == 0:
            return

        t = datetime.datetime.utcnow()

        if not self.config.logger.sensor.sensor_gps.hasGPS():
            self.zoom = self.config.G_MAX_ZOOM

        self.plot.showGrid(x=True, y=True, alpha=1)
        self.plot.showAxis('left')
        self.plot.showAxis('bottom')
        font = QtGui.QFont()
        font.setPixelSize(16)
        font.setBold(True)
        self.plot.getAxis("bottom").tickFont = font
        #self.plot.getAxis("bottom").setStyle(tickTextOffset = 5)
        self.plot.getAxis("left").tickFont = font
        #self.plot.getAxis("left").setStyle(tickTextOffset = 5)
        #self.plot.setAutoPan()

        print("\tpyqt_graph : load course profile : ",
              (datetime.datetime.utcnow() - t).total_seconds(), "sec")
        t = datetime.datetime.utcnow()

        bg = pg.CourseProfileGraphItem(
            x=self.config.logger.course.distance,
            y=self.config.logger.course.altitude,
            brushes=self.config.logger.course.colored_altitude,
            pen=pg.mkPen(color=(255, 255, 255, 0),
                         width=0.01))  #transparent(alpha=0) and thin line
        self.plot.addItem(bg)

        self.course_points_plot = pg.ScatterPlotItem(pxMode=True, symbol="t")
        self.course_points = []

        for i in reversed(range(len(
                self.config.logger.course.point_distance))):
            cp = {
                'pos': [
                    self.config.logger.course.point_distance[i],
                    self.config.logger.course.point_altitude[i]
                ],
                'size':
                10,
                'pen': {
                    'color': 'r',
                    'width': 1
                },
                'brush':
                pg.mkBrush(color=(255, 0, 0))
            }
            self.course_points.append(cp)
        self.course_points_plot.setData(self.course_points)
        self.plot.addItem(self.course_points_plot)

        self.course_points_label = []
        if self.config.G_FONT_NAME != "":
            self.font = QtGui.QFont(self.config.G_FONT_NAME)
        for i in reversed(range(len(
                self.config.logger.course.point_distance))):
            text = pg.TextItem(
                text=self.config.logger.course.point_name[i],
                anchor=(-0.1, 1.2),
                angle=0,
                border=(255, 0, 0),
                fill=(255, 255, 255),
                color=(0, 0, 0),
            )
            #text.setTextWidth(int(self.config.G_WIDTH/2.5))
            if self.config.G_FONT_NAME != "":
                text.setFont(self.font)
            self.plot.addItem(text)
            text.setPos(self.config.logger.course.point_distance[i],
                        self.config.logger.course.point_altitude[i])
            self.course_points_label.append(text)

        print("\tpyqt_graph : plot course profile : ",
              (datetime.datetime.utcnow() - t).total_seconds(), "sec")
    conn_data = np.empty((len(cell_classes), 3))
    n_probed = []
    n_connected = []
    brushes = []
    pens = []
    for i,class_info in enumerate(cell_classes):
        cell_class, _, color = class_info
        class_results = results[(cell_class, cell_class)]
        conn_data[i] = class_results['connection_probability']
        n_probed.append(class_results['n_probed'])
        n_connected.append(class_results['n_connected'])
        print("Cell class: %s  connected: %d  probed: %d  probability: %0.3f  min_ci: %0.3f  max_ci: %0.3f" % (
            cell_class.name, class_results['n_connected'], class_results['n_probed'], 
            class_results['connection_probability'][0], class_results['connection_probability'][1], class_results['connection_probability'][2],
        ))
        brushes.append(pg.mkBrush(color))

        # Add confidence interval line for this class
        errbar = pg.QtGui.QGraphicsLineItem(i, class_results['connection_probability'][1], i, class_results['connection_probability'][2])
        errbar.setPen(pg.mkPen(color, width=3))
        conn_plot.addItem(errbar)

    write_csv(csv_file, class_names, "Figure 4%s cell classes" % fig_letter)
    write_csv(csv_file, n_connected, "Figure 4%s n connected pairs < 100um" % fig_letter)
    write_csv(csv_file, n_probed, "Figure 4%s n probed pairs < 100um" % fig_letter)

    # plot connection probability points
    conn_plot.plot(conn_data[:,0], pen=None, symbol='o', symbolBrush=brushes, symbolPen='k')
    write_csv(csv_file, conn_data[:, 0], "Figure 4%s connection probability < 100um" % fig_letter)

    # write confidence intervals into csv
Esempio n. 42
0
    def on_activate(self):
        """ Definition and initialisation of the GUI.
        """

        self._wm_logger_logic = self.wavemeterloggerlogic1()
        self._save_logic = self.savelogic()

        # setting up the window
        self._mw = WavemeterLogWindow()

        ## giving the plots names allows us to link their axes together
        self._pw = self._mw.plotWidget  # pg.PlotWidget(name='Counter1')
        self._plot_item = self._pw.plotItem

        ## create a new ViewBox, link the right axis to its coordinate system
        self._right_axis = pg.ViewBox()
        self._plot_item.showAxis('right')
        self._plot_item.scene().addItem(self._right_axis)
        self._plot_item.getAxis('right').linkToView(self._right_axis)
        self._right_axis.setXLink(self._plot_item)

        ## create a new ViewBox, link the right axis to its coordinate system
        self._top_axis = pg.ViewBox()
        self._plot_item.showAxis('top')
        self._plot_item.scene().addItem(self._top_axis)
        self._plot_item.getAxis('top').linkToView(self._top_axis)
        self._top_axis.setYLink(self._plot_item)
        self._top_axis.invertX(b=True)

        # handle resizing of any of the elements
        self._update_plot_views()
        self._plot_item.vb.sigResized.connect(self._update_plot_views)

        self._pw.setLabel('left', 'Fluorescence', units='counts/s')
        self._pw.setLabel('right', 'Number of Points', units='#')
        self._pw.setLabel('bottom', 'Wavelength', units='nm')
        self._pw.setLabel('top', 'Relative Frequency', units='Hz')

        self._mw.actionStop_resume_scan.triggered.connect(
            self.stop_resume_clicked)
        self._mw.actionSave_histogram.triggered.connect(self.save_clicked)
        self._mw.actionStart_scan.triggered.connect(self.start_clicked)
        self._mw.actionAuto_range.triggered.connect(self.set_auto_range)

        # defining the parameters to edit
        self._mw.binSpinBox.setValue(self._wm_logger_logic.get_bins())
        self._mw.binSpinBox.editingFinished.connect(self.recalculate_histogram)

        self._mw.minDoubleSpinBox.setValue(
            self._wm_logger_logic.get_min_wavelength())
        self._mw.minDoubleSpinBox.editingFinished.connect(
            self.recalculate_histogram)

        self._mw.maxDoubleSpinBox.setValue(
            self._wm_logger_logic.get_max_wavelength())
        self._mw.maxDoubleSpinBox.editingFinished.connect(
            self.recalculate_histogram)

        self._mw.show()

        ## Create an empty plot curve to be filled later, set its pen
        self.curve_data_points = pg.PlotDataItem(pen=pg.mkPen(palette.c1),
                                                 symbol=None)

        self.curve_nm_counts = pg.PlotDataItem(pen=pg.mkPen(
            palette.c2, style=QtCore.Qt.DotLine),
                                               symbol=None)

        self.curve_hz_counts = pg.PlotDataItem(pen=pg.mkPen(
            palette.c6, style=QtCore.Qt.DotLine),
                                               symbol=None)

        self.curve_envelope = pg.PlotDataItem(pen=pg.mkPen(
            palette.c3, style=QtCore.Qt.DotLine),
                                              symbol=None)

        self.curve_fit = pg.PlotDataItem(pen=pg.mkPen(palette.c2, width=3),
                                         symbol=None)

        self._pw.addItem(self.curve_data_points)
        self._pw.addItem(self.curve_envelope)
        self._right_axis.addItem(self.curve_nm_counts)
        self._top_axis.addItem(self.curve_hz_counts)

        # scatter plot for time series
        self._spw = self._mw.scatterPlotWidget
        self._spi = self._spw.plotItem
        self._spw.setLabel('bottom', 'Wavelength', units='nm')
        self._spw.setLabel('left', 'Time', units='s')
        self._scatterplot = pg.ScatterPlotItem(size=10,
                                               pen=pg.mkPen(None),
                                               brush=pg.mkBrush(
                                                   255, 255, 255, 20))
        self._spw.addItem(self._scatterplot)
        self._spw.setXLink(self._plot_item)
        self._wm_logger_logic.sig_new_data_point.connect(self.add_data_point)

        self._wm_logger_logic.sig_data_updated.connect(self.updateData)

        # fit settings
        self._fsd = FitSettingsDialog(self._wm_logger_logic.fc)
        self._fsd.sigFitsUpdated.connect(
            self._mw.fit_methods_ComboBox.setFitFunctions)
        self._fsd.applySettings()

        #      self._mw.action_FitSettings.triggered.connect(self._fsd.show) #commented to debug
        self._mw.do_fit_PushButton.clicked.connect(self.doFit)
        self.sigDoFit.connect(self._wm_logger_logic.do_fit)
        self.sigFitChanged.connect(self._wm_logger_logic.fc.set_current_fit)
        self._wm_logger_logic.sig_fit_updated.connect(self.updateFit)
Esempio n. 43
0
    def __init__(self, parent):
        # graph
        self.name = "Transfer functions"
        super(IirGraphWidget, self).__init__(parent)
        self.parent = parent
        self.module = self.parent.module
        self.layout = QtWidgets.QVBoxLayout(self)
        self.win = MyGraphicsWindow(title="Amplitude", parent=self)
        self.win_phase = MyGraphicsWindow(title="Phase", parent=self)
        # self.proxy = pg.SignalProxy(self.win.scene().sigMouseClicked,
        # rateLimit=60, slot=self.mouse_clicked)
        self.mag = self.win.addPlot(title="Magnitude (dB)")
        self.phase = self.win_phase.addPlot(title="Phase (deg)")
        self.phase.setXLink(self.mag)
        # self.proxy_phase = pg.SignalProxy(self.win_phase.scene().sigMouseClicked,
        # rateLimit=60, slot=self.mouse_clicked)

        # we will plot the following curves:
        # poles, zeros -> large dots and crosses
        # design (designed filter) - yellow line
        # measured filter with na - orange dots
        # data (measruement data) - green line
        # data x design (or data/design) - red line
        self.plots = OrderedDict()

        # make scatterplot items
        for name, style in [('filter_measurement', dict(pen=pg.mkPen(None),
                                                        symbol='o',
                                                        size=5,
                                                        brush=pg.mkBrush(255, 100, 0, 180))),
                            ('zeros', dict(pen=pg.mkPen(None),
                                           symbol='o',
                                           size=10,
                                           brush=pg.mkBrush(255, 0, 255, 120))),
                            ('poles', dict(pen=pg.mkPen(None),
                                           symbol='x',
                                           size=10,
                                           brush=pg.mkBrush(255, 0, 255, 120))),
                            # ('actpole', dict(size=30,
                            #                symbol='x',
                            #                pen='r',
                            #                brush=pg.mkBrush(255, 0, 255,
                            #                                 120))),
                            # ('actzero', dict(size=30,
                            #                symbol='o',
                            #                pen='r',
                            #                brush=pg.mkBrush(255, 0, 255,
                            #                                 120)))
                            ]:
                item = pg.ScatterPlotItem(**style)
                self.mag.addItem(item)
                self.plots[name] = item
                item = pg.ScatterPlotItem(**style)
                self.phase.addItem(item)
                self.plots[name+'_phase'] = item

        # make lines
        for name, style in [('data', dict(pen='g')),
                            ('filter_design', dict(pen='y')),
                            ('data_x_design', dict(pen='r'))]:
            self.plots[name] = self.mag.plot(**style)
            self.plots[name + "_phase"] = self.phase.plot(**style)
            self.plots[name].setLogMode(xMode=self.xlog, yMode=None)
            self.plots[name + '_phase'].setLogMode(xMode=self.xlog, yMode=None)

        # also set logscale for the xaxis
        # make scatter plots
        self.mag.setLogMode(x=self.xlog, y=None)
        self.phase.setLogMode(x=self.xlog, y=None)
        self.layout.addWidget(self.win)
        self.layout.addWidget(self.win_phase)
Esempio n. 44
0
    def setup(self):

        ## Dummy data Structures (override in func:self.load_data())
        self.hyperspec_data = np.arange(10 * 10 * 34).reshape((10, 10, 34))
        self.display_image = self.hyperspec_data.sum(
            -1)  # np.random.rand(10,10)
        self.spec_x_array = np.arange(34)

        # Call :func:set_scalebar_params() during self.load_data() to add a scalebar!
        self.scalebar_type = None

        # Will be filled derived maps and x_arrays
        self.display_images = dict()
        self.spec_x_arrays = dict()

        ## Graphs and Interface
        self.line_colors = ['w', 'r', 'b', 'y', 'm', 'c', 'g']
        self.plot_n_fit = PlotNFit(Ndata_lines=2,
                                   pens=['g'] + self.line_colors)

        # Docks
        self.ui = self.dockarea = dockarea.DockArea()
        self.image_dock = self.dockarea.addDock(name='Image')
        self.spec_dock = self.dockarea.addDock(self.plot_n_fit.graph_dock)
        self.settings_dock = self.dockarea.addDock(name='settings',
                                                   position='left',
                                                   relativeTo=self.image_dock)
        self.export_dock = self.dockarea.addDock(name='export & adv. settings',
                                                 position='below',
                                                 relativeTo=self.settings_dock)
        self.dockarea.addDock(self.plot_n_fit.settings_dock,
                              relativeTo=self.settings_dock,
                              position='below')
        self.corr_dock = self.dockarea.addDock(name='correlation',
                                               position='right',
                                               relativeTo=self.spec_dock)

        # Image View
        self.imview = pg.ImageView()
        self.imview.getView().invertY(False)  # lower left origin
        self.image_dock.addWidget(self.imview)
        self.graph_layout = self.plot_n_fit.graph_layout

        # Rectangle ROI
        self.rect_roi = pg.RectROI([20, 20], [20, 20], pen=self.line_colors[0])
        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=self.line_colors[1])
        #self.circ_roi.removeHandle(self.circ_roi.getHandles()[0])
        h = self.circ_roi.addTranslateHandle((0.5, .5))
        h.pen = pg.mkPen(pen=self.line_colors[1])
        h.update()
        self.imview.getView().addItem(self.circ_roi)
        self.circ_roi.removeHandle(0)
        self.circ_roi_plotline = pg.PlotCurveItem([0], pen=self.line_colors[1])
        self.imview.getView().addItem(self.circ_roi_plotline)
        self.circ_roi.sigRegionChanged[object].connect(self.on_update_circ_roi)

        # Spec plot
        self.spec_plot = self.plot_n_fit.plot
        self.spec_plot.setLabel('left', 'Intensity', units='counts')
        self.rect_plotdata = self.plot_n_fit.data_lines[0]
        self.point_plotdata = self.plot_n_fit.data_lines[1]
        self.point_plotdata.setZValue(-1)

        #settings
        S = self.settings
        self.default_display_image_choices = ['default', 'sum']
        S.New('display_image',
              str,
              choices=self.default_display_image_choices,
              initial='default')
        S.display_image.add_listener(self.on_change_display_image)

        self.default_x_axis_choices = ['default', 'index']
        self.x_axis = S.New('x_axis',
                            str,
                            initial='default',
                            choices=self.default_x_axis_choices)
        self.x_axis.add_listener(self.on_change_x_axis)

        bg_subtract_choices = ('None', 'bg_slice', 'costum_const')
        self.bg_subtract = S.New('bg_subtract',
                                 str,
                                 initial='None',
                                 choices=bg_subtract_choices)

        self.bg_counts = S.New('bg_value', initial=0, unit='cts/bin')
        self.bg_counts.add_listener(self.update_display)

        self.binning = S.New('binning', int, initial=1, vmin=1)
        self.binning.add_listener(self.update_display)

        self.norm_data = S.New('norm_data', bool, initial=False)
        self.norm_data.add_listener(self.update_display)

        S.New('default_view_on_load', bool, initial=True)

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

        self.show_lines = ['show_circ_line', 'show_rect_line']
        for x in self.show_lines:
            lq = S.New(x, bool, initial=True)
            lq.add_listener(self.on_change_show_lines)

        # Settings Widgets
        self.settings_widgets = [
        ]  # Hack part 1/2: allows to use settings.New_UI() and have settings defined in scan_specific_setup()

        font = QtGui.QFont("Times", 12)
        font.setBold(True)
        self.x_slicer = RegionSlicer(
            self.spec_plot,
            name='x_slice',
            #slicer_updated_func=self.update_display,
            brush=QtGui.QColor(0, 255, 0, 50),
            ZValue=10,
            font=font,
            initial=[100, 511],
            activated=True)
        self.bg_slicer = RegionSlicer(
            self.spec_plot,
            name='bg_slice',
            #slicer_updated_func=self.update_display,
            brush=QtGui.QColor(255, 255, 255, 50),
            ZValue=11,
            font=font,
            initial=[0, 80],
            label_line=0)

        self.x_slicer.region_changed_signal.connect(self.update_display)
        self.bg_slicer.region_changed_signal.connect(self.update_display)

        self.bg_slicer.activated.add_listener(
            lambda: self.bg_subtract.update_value('bg_slice')
            if self.bg_slicer.activated.val else None)
        self.settings_widgets.append(self.x_slicer.New_UI())
        self.settings_widgets.append(self.bg_slicer.New_UI())

        ## Setting widgets, (w/o logged quantities)
        self.update_display_pushButton = QtWidgets.QPushButton(
            text='update display')
        self.settings_widgets.append(self.update_display_pushButton)
        self.update_display_pushButton.clicked.connect(self.update_display)

        self.default_view_pushButton = QtWidgets.QPushButton(
            text='default img view')
        self.settings_widgets.append(self.default_view_pushButton)
        self.default_view_pushButton.clicked.connect(self.default_image_view)

        self.recalc_median_pushButton = QtWidgets.QPushButton(
            text='recalc median map')
        self.settings_widgets.append(self.recalc_median_pushButton)
        self.recalc_median_pushButton.clicked.connect(self.recalc_median_map)

        self.recalc_sum_pushButton = QtWidgets.QPushButton(
            text='recalc sum map')
        self.settings_widgets.append(self.recalc_sum_pushButton)
        self.recalc_sum_pushButton.clicked.connect(self.recalc_sum_map)

        self.delete_current_display_image_pushButton = QtWidgets.QPushButton(
            text='delete image')
        self.settings_widgets.append(
            self.delete_current_display_image_pushButton)
        self.delete_current_display_image_pushButton.clicked.connect(
            self.delete_current_display_image)

        #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.sigClicked.connect(self.corr_plot_clicked)
        self.corr_dock.addWidget(self.corr_layout)

        self.corr_settings = CS = LQCollection()
        self.cor_X_data = self.corr_settings.New(
            'cor_X_data',
            str,
            choices=self.default_display_image_choices,
            initial='default')
        self.cor_Y_data = self.corr_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)
        self.corr_ui = self.corr_settings.New_UI()
        self.corr_dock.addWidget(self.corr_ui)

        # map exporter
        self.map_export_settings = MES = LQCollection()
        MES.New('include_scale_bar', bool, initial=True)
        MES.New('scale_bar_width', float, initial=1, spinbox_decimals=3)
        MES.New('scale_bar_text', str, ro=False)
        map_export_ui = MES.New_UI()
        self.export_dock.addWidget(map_export_ui)

        self.export_maps_as_jpegs_pushButton = QtWidgets.QPushButton(
            'export maps as jpegs')
        self.export_maps_as_jpegs_pushButton.clicked.connect(
            self.export_maps_as_jpegs)
        self.export_dock.addWidget(self.export_maps_as_jpegs_pushButton)

        self.save_state_pushButton = QtWidgets.QPushButton(text='save state')
        self.export_dock.addWidget(self.save_state_pushButton)
        self.save_state_pushButton.clicked.connect(self.save_state)

        # finalize settings widgets
        self.scan_specific_setup(
        )  # there could more settings_widgets generated here (part 2/2)

        hide_settings = [
            'norm_data', 'show_circ_line', 'show_rect_line',
            'default_view_on_load', 'spatial_binning', 'x_axis'
        ]
        self.settings_ui = self.settings.New_UI(exclude=hide_settings)
        self.settings_dock.addWidget(self.settings_ui)
        self.hidden_settings_ui = self.settings.New_UI(include=hide_settings)
        self.export_dock.addWidget(self.hidden_settings_ui)

        ui_widget = QtWidgets.QWidget()
        gridLayout = QtWidgets.QGridLayout()
        gridLayout.setSpacing(0)
        gridLayout.setContentsMargins(0, 0, 0, 0)
        ui_widget.setLayout(gridLayout)
        for i, w in enumerate(self.settings_widgets):
            gridLayout.addWidget(w, int(i / 2), i % 2)
        self.settings_dock.addWidget(ui_widget)

        self.plot_n_fit.add_button('fit_map', self.fit_map)

        self.settings_dock.raiseDock()

        self.plot_n_fit.settings_dock.setStretch(1, 1)
        self.export_dock.setStretch(1, 1)
        self.settings_dock.setStretch(1, 1)

        for layout in [
                self.settings_ui.layout(),
                self.export_dock.layout,
        ]:
            VSpacerItem = QtWidgets.QSpacerItem(
                0, 0, QtWidgets.QSizePolicy.Minimum,
                QtWidgets.QSizePolicy.Expanding)
            layout.addItem(VSpacerItem)
Esempio n. 45
0
 def paint(self, p, *args):
     p.setPen(pg.mkPen(self.border_color))
     p.setBrush(pg.mkBrush(self.fill_color))
     p.drawRect(self.boundingRect())
Esempio n. 46
0
    def __init__(self, populations):
        self.pops = populations
        pg.PlotWidget.__init__(self)
        self.setLogMode(x=True, y=False)

        self.cells = pg.ScatterPlotItem(clickable=True)
        self.cells.setZValue(10)
        self.addItem(self.cells)
        self.cells.sigClicked.connect(self.cells_clicked)

        self.selected = pg.ScatterPlotItem()
        self.selected.setZValue(20)
        self.addItem(self.selected)

        self.connections = pg.PlotCurveItem()
        self.addItem(self.connections)

        # first assign positions of all cells
        cells = []
        for y, pop in enumerate(self.pops.values()):
            pop.cell_spots = []
            pop.fwd_connections = {}
            for i, cell in enumerate(pop._cells):
                pos = (np.log10(cell['cf']), y)
                real = cell['cell'] != 0
                if not real:
                    pop.cell_spots.append(None)
                    continue
                brush = pg.mkBrush('b') if real else pg.mkBrush(
                    255, 255, 255, 30)
                spot = {
                    'x': pos[0],
                    'y': pos[1],
                    'symbol': 'o' if real else 'x',
                    'brush': brush,
                    'pen': None,
                    'data': (pop, i)
                }
                cells.append(spot)
                pop.cell_spots.append(spot)

        self.cells.setData(cells)

        self.getAxis('left').setTicks([list(enumerate(self.pops.keys()))])

        # now assign connection lines and record forward connectivity
        con_x = []
        con_y = []
        for pop in self.pops.values():
            for i, cell in enumerate(pop._cells):
                conns = cell['connections']
                if conns == 0:
                    continue
                for prepop, precells in conns.items():
                    spot = pop.cell_spots[i]
                    if spot is None:
                        continue
                    p1 = spot['x'], spot['y']
                    for j in precells:
                        prepop.fwd_connections.setdefault(j, [])
                        prepop.fwd_connections[j].append((pop, i))
                        spot2 = prepop.cell_spots[j]
                        if spot2 is None:
                            return
                        p2 = spot2['x'], spot2['y']
                        con_x.extend([p1[0], p2[0]])
                        con_y.extend([p1[1], p2[1]])
        self.connections.setData(x=con_x,
                                 y=con_y,
                                 connect='pairs',
                                 pen=(255, 255, 255, 60))
 def __clear_hover(self):
     for item in self.__fill_items:
         item.setBrush(pg.mkBrush(*item.rgb))
     self.__clear_tooltips()
Esempio n. 48
0
    def generatePicture(self, data=None, redraw=False):
        """重新生成图形对象"""
        # 重画或者只更新最后一个K线
        if redraw:
            self.pictures = []
        elif self.pictures:
            self.pictures.pop()
        w = 0.4
        bPen = self.bPen
        bBrush = self.bBrush
        rPen = self.rPen
        rBrush = self.rBrush
        low, high = (data[0]['low'], data[0]['high']) if len(data) > 0 else (0, 1)
        prehigh= 0
        prelow =0

        # '''
        for (t, open0, close0, low0, high0) in data:
            if t >= len(self.pictures):
                tShift = t

                low, high = (min(low, low0), max(high, high0))
                picture = QtGui.QPicture()
                p = QtGui.QPainter(picture)
                # # 下跌蓝色(实心), 上涨红色(空心)
                pen, brush, pmin, pmax = (bPen, bBrush, close0, open0) \
                    if open0 > close0 else (rPen, rBrush, open0, close0)
                p.setPen(pen)
                p.setBrush(brush)
                # 画K线方块和上下影线
                if pmin > low0:
                    p.drawLine(QtCore.QPointF(tShift, low0), QtCore.QPointF(tShift, pmin))
                if high0 > pmax:
                    p.drawLine(QtCore.QPointF(tShift, pmax), QtCore.QPointF(tShift, high0))
                # 指定图片绘制的区域 QRect,画方块
                p.drawRect(QtCore.QRectF(tShift - w, open0, w * 2, close0 - open0))
                if self.flag:
                    p.setPen(pg.mkPen('w'))
                    p.setBrush(pg.mkBrush('w'))
                    if prehigh==0:
                        p.drawLine(QtCore.QPointF(t, high0+5), QtCore.QPointF(t, high0+5))
                    else:
                        p.drawLine(QtCore.QPointF(t-1, prehigh), QtCore.QPointF(t, high0+5))
                    prehigh = high0+5

                    p.setPen(pg.mkPen(color=(255,215,0)))
                    if prelow == 0:
                        p.drawLine(QtCore.QPointF(t, low0-3), QtCore.QPointF(t, low0-3))
                    else:
                        p.drawLine(QtCore.QPointF(t - 1, prelow), QtCore.QPointF(t, low0-3))
                    prelow = low0-3


                p.end()
                self.pictures.append(picture)
                self.new_pictures[t] = p

        # '''
        # prehigh= 0
        # prelow = 0
        # t = 0
        # for (t, open0, close0, low0, high0) in data:
        #     p = self.new_pictures[t]
        #     p.setPen(pg.mkPen('w'))
        #     p.setBrush(pg.mkBrush('w'))
        #     if prehigh==0:
        #         p.drawLine(QtCore.QPointF(t, high0), QtCore.QPointF(t, high0))
        #     else:
        #         p.drawLine(QtCore.QPointF(t-1, prehigh), QtCore.QPointF(t, high0))
        #     prehigh = high0
        #     p.end()

        self.low, self.high = low, high
Esempio n. 49
0
w2 = view.addViewBox()
w2.setAspectLocked(True)
view.nextRow()
w3 = view.addPlot()
w4 = view.addPlot()
print("Generating data, this takes a few seconds...")

## There are a few different ways we can draw scatter plots; each is optimized for different types of data:


## 1) All spots identical and transform-invariant (top-left plot). 
## In this case we can get a huge performance boost by pre-rendering the spot 
## image and just drawing that image repeatedly.

n = 300
s1 = pg.ScatterPlotItem(size=10, pen=pg.mkPen(None), brush=pg.mkBrush(255, 255, 255, 120))
pos = np.random.normal(size=(2,n), scale=1e-5)
spots = [{'pos': pos[:,i], 'data': 1} for i in range(n)] + [{'pos': [0,0], 'data': 1}]
s1.addPoints(spots)
w1.addItem(s1)

## Make all plots clickable
lastClicked = []
def clicked(plot, points):
    global lastClicked
    for p in lastClicked:
        p.resetPen()
    print("clicked points", points)
    for p in points:
        p.setPen('b', width=2)
    lastClicked = points
Esempio n. 50
0
    def handle_checker_record(self, rec):
        expt = rec['experiment']
        if expt in self.records_by_expt:
            # use old record / item
            index = self.records_by_expt[expt]
            item = self.records[index]['item']
        else:
            # add new record / item
            item = pg.TreeWidgetItem()
            self.expt_tree.addTopLevelItem(item)
            rec['item'] = item
            index = self.records.add_record({})
            item.index = index

        record = self.records[index]
        record['item'] = item
        self.records_by_expt[expt] = index

        # update item/record fields
        update_filter = False
        for field, val in rec.items():
            if field in self.field_indices and isinstance(val, tuple):
                # if a tuple was given, interpret it as (text, color)
                val, color = val
            else:
                # otherwise make a guess on a good color
                color = 'w'
                if val is True:
                    color = pass_color
                elif val is False:
                    color = fail_color
                elif val in ('ERROR', 'MISSING', 'FAILED'):
                    color = fail_color
                elif val == '-':
                    # dash means item is incomplete but still acceptable
                    color = [c * 0.5 + 128 for c in pass_color]
            
            display_val = str(val)

            if field == 'timestamp' and rec.get('error') is not None:
                color = fail_color

            # update this field in the record
            record[field] = val
            
            # update this field in the tree item
            try:
                i = self.field_indices[field]
            except KeyError:
                continue

            item.setText(i, display_val)
            if color is not None:
                item.setBackground(i, pg.mkBrush(color))

            # update filter fields
            filter_field = self.filter_fields.get(field)
            if filter_field is not None and filter_field['mode'] == 'enum' and display_val not in filter_field['values']:
                filter_field['values'][display_val] = True
                update_filter = True

        if update_filter:
            self.filter.setFields(self.filter_fields)

        self.filter_items(self.records[index:index+1])
Esempio n. 51
0
    def init_bar_graph_caract(self):
        brushes = [pg.mkBrush(i) for i in range(len(self.gv.waves))]
        x = [w.get_half_pos() for w in self.gv.waves.values()]
        width = [w.get_delta_range() for w in self.gv.waves.values()]

        return brushes, x, width
Esempio n. 52
0
# # option1: only for .plot(), following c1,c2 for example-----------------------
# win.addLegend(frame=False, colCount=2)

# bar graph
x = np.arange(10)
y = np.sin(x+2) * 3
bg1 = pg.BarGraphItem(x=x, height=y, width=0.3, brush='b', pen='w', name='bar')
win.addItem(bg1)

# curve
c1 = win.plot([np.random.randint(0,8) for i in range(10)], pen='r', symbol='t', symbolPen='r', symbolBrush='g', name='curve1')
c2 = win.plot([2,1,4,3,1,3,2,4,3,2], pen='g', fillLevel=0, fillBrush=(255,255,255,30), name='curve2')

# scatter plot
s1 = pg.ScatterPlotItem(size=10, pen=pg.mkPen(None), brush=pg.mkBrush(255, 255, 255, 120), name='scatter')
spots = [{'pos': [i, np.random.randint(-3, 3)], 'data': 1} for i in range(10)]
s1.addPoints(spots)
win.addItem(s1)

# # option2: generic method------------------------------------------------
legend = pg.LegendItem((80,60), offset=(70,20))
legend.setParentItem(win.graphicsItem())
legend.addItem(bg1, 'bar')
legend.addItem(c1, 'curve1')
legend.addItem(c2, 'curve2')
legend.addItem(s1, 'scatter')

if __name__ == '__main__':
    pg.mkQApp().exec_()
Esempio n. 53
0
 def makeColoredBrush(self, percent, value):
     color = self.legend.getColor(percent)
     print("Value: ", value, " Percent: ", percent, " Color: ",
           color.getRgb())
     return pg.mkBrush(color)
Esempio n. 54
0
    def __init__(self, parent=None):
        super(TSNEPlot, self).__init__(parent=parent)
        self.model = ResultsTableModel()

        self.layout = QtGui.QGridLayout(self)
        self.layout.setAlignment(QtCore.Qt.AlignTop)

        self.random_seed = np.random.randint(1, 99999)
        self.perplexity = 30
        self.lr = 200.0

        self.plot_widget = pg.PlotWidget()
        self.tsne_plot = pg.ScatterPlotItem(
            symbol="o",
            size=10,
            pen=pg.mkPen(width=0.2, color="b"),
            brush=pg.mkBrush(0.7),
            antialias=True,
        )
        self.tsne_plot.sigClicked.connect(self.pointClicked)
        self.selectedPt = None
        self.plot_widget.hideAxis("left")
        self.plot_widget.hideAxis("bottom")
        self.plot_widget.addItem(self.tsne_plot)

        self.random_seed_edit = QtGui.QLineEdit(str(self.random_seed))
        self.random_seed_edit.setValidator(QtGui.QIntValidator(1, 99999))
        self.random_seed_edit.setMaximumWidth(75)
        self.perplexity_edit = QtGui.QLineEdit(str(self.perplexity))
        self.perplexity_edit.setValidator(QtGui.QIntValidator(1, 50))
        self.perplexity_edit.setMaximumWidth(75)
        self.lr_edit = QtGui.QLineEdit(str(self.lr))
        self.lr_edit.setValidator(QtGui.QDoubleValidator(10, 1000, 3))
        self.lr_edit.setMaximumWidth(75)

        self.select_feature = QtGui.QComboBox()

        self.run_button = QtGui.QPushButton("Run t-SNE")
        self.back_button = QtGui.QPushButton("<<< Feature Selection")
        self.save_button = QtGui.QPushButton("Export Image")
        self.save_button.setIcon(self.style().standardIcon(
            QtGui.QStyle.SP_FileDialogStart))

        self.legend = pg.GradientWidget(orientation="right")
        self.legend.setMaximumWidth(50)
        self.legend.sigGradientChangeFinished.connect(self.colorChange)
        # print(self.legend.colorMap())

        self.layout.addWidget(QtGui.QLabel("Perplexity"), 0, 0, 1, 1)
        self.layout.addWidget(self.perplexity_edit, 0, 1, 1, 1)
        self.layout.addWidget(QtGui.QLabel("Random Seed"), 1, 0, 1, 1)
        self.layout.addWidget(self.random_seed_edit, 1, 1, 1, 1)
        self.layout.addWidget(QtGui.QLabel("Learning Rate"), 2, 0, 1, 1)
        self.layout.addWidget(self.lr_edit, 2, 1, 1, 1)
        self.layout.addWidget(self.save_button, 3, 0, 1, 1)
        self.layout.addWidget(self.run_button, 3, 1, 1, 2)
        self.layout.addWidget(self.plot_widget, 4, 0, 4, 3)
        self.layout.addWidget(self.select_feature, 8, 0, 1, 3)
        self.layout.addWidget(self.back_button, 9, 0, 1, 3)
        self.layout.addWidget(self.legend, 4, 4, 4, 1)
        # self.layout.setColumnStretch(4, 1)

        self.select_feature.activated[str].connect(self.setBrushes)
    def setup(self, win):
        # Data plots

        self.data_plots = []
        self.data_curves = []
        for i in range(self.num_depths):
            title = "{:.0f} cm".format(100 * self.depths[i])
            plot = win.addPlot(row=0, col=i, title=title)
            plot.setMenuEnabled(False)
            plot.setMouseEnabled(x=False, y=False)
            plot.hideButtons()
            plot.showGrid(x=True, y=True)
            plot.setYRange(0, 2**16)
            plot.hideAxis("left")
            plot.hideAxis("bottom")
            plot.plot(np.arange(self.sweeps_per_frame),
                      2**15 * np.ones(self.sweeps_per_frame))
            curve = plot.plot(pen=utils.pg_pen_cycler())
            self.data_plots.append(plot)
            self.data_curves.append(curve)

        # Spectral density plot

        self.sd_plot = win.addPlot(row=1, col=0, colspan=self.num_depths)
        self.sd_plot.setMenuEnabled(False)
        self.sd_plot.setMouseEnabled(x=False, y=False)
        self.sd_plot.hideButtons()
        self.sd_plot.setLabel("left", "Normalized PSD (dB)")
        self.sd_plot.showGrid(x=True, y=True)
        self.sd_curve = self.sd_plot.plot(pen=utils.pg_pen_cycler())
        dashed_pen = pg.mkPen("k", width=2, style=QtCore.Qt.DashLine)
        self.sd_threshold_line = pg.InfiniteLine(angle=0, pen=dashed_pen)
        self.sd_plot.addItem(self.sd_threshold_line)

        self.smooth_max = utils.SmoothMax(
            self.est_update_rate,
            tau_decay=0.5,
            tau_grow=0,
            hysteresis=0.2,
        )

        # Rolling speed plot

        self.vel_plot = pg.PlotItem()
        self.vel_plot.setMenuEnabled(False)
        self.vel_plot.setMouseEnabled(x=False, y=False)
        self.vel_plot.hideButtons()
        self.vel_plot.setLabel("bottom", "Time (s)")
        self.vel_plot.showGrid(x=True, y=True)
        self.vel_plot.setXRange(-EST_VEL_HISTORY_LENGTH, 0)
        self.vel_max_line = pg.InfiniteLine(angle=0,
                                            pen=pg.mkPen("k", width=1))
        self.vel_plot.addItem(self.vel_max_line)
        self.vel_scatter = pg.ScatterPlotItem(size=8)
        self.vel_plot.addItem(self.vel_scatter)

        self.vel_html_fmt = '<span style="color:#000;font-size:24pt;">{:.1f} {}</span>'
        self.vel_text_item = pg.TextItem(anchor=(0.5, 0))
        self.vel_plot.addItem(self.vel_text_item)

        # Sequence speed plot

        self.sequences_plot = pg.PlotItem()
        self.sequences_plot.setMenuEnabled(False)
        self.sequences_plot.setMouseEnabled(x=False, y=False)
        self.sequences_plot.hideButtons()
        self.sequences_plot.setLabel("bottom", "History")
        self.sequences_plot.showGrid(y=True)
        self.sequences_plot.setXRange(-NUM_SAVED_SEQUENCES + 0.5, 0.5)
        tmp = np.flip(np.arange(NUM_SAVED_SEQUENCES) == 0)
        brushes = [pg.mkBrush(utils.color_cycler(n)) for n in tmp]
        self.bar_graph = pg.BarGraphItem(
            x=np.arange(-NUM_SAVED_SEQUENCES, 0) + 1,
            height=np.zeros(NUM_SAVED_SEQUENCES),
            width=0.8,
            brushes=brushes,
        )
        self.sequences_plot.addItem(self.bar_graph)

        self.sequences_text_item = pg.TextItem(anchor=(0.5, 0))
        self.sequences_plot.addItem(self.sequences_text_item)

        sublayout = win.addLayout(row=2, col=0, colspan=self.num_depths)
        sublayout.addItem(self.vel_plot, col=0)
        sublayout.addItem(self.sequences_plot, col=1)

        self.setup_is_done = True
        self.update_processing_config()
Esempio n. 56
0
    def __graph_results(self):
        yes_votes = self.poll_data[:, NUM_YES]
        no_votes = self.poll_data[:, NUM_NO]
        cycle = self.poll_data[:, ROUND]

        # Std processing
        std_votes = yes_votes[self.std_gamemode_mask] + no_votes[
            self.std_gamemode_mask]
        std_percent_yes_votes = yes_votes[self.std_gamemode_mask] / std_votes
        std_cycle = cycle[self.std_gamemode_mask]

        # Taiko processing
        taiko_votes = yes_votes[self.taiko_gamemode_mask] + no_votes[
            self.taiko_gamemode_mask]
        taiko_percent_yes_votes = yes_votes[
            self.taiko_gamemode_mask] / taiko_votes
        taiko_cycle = cycle[self.taiko_gamemode_mask]

        # Catch processing
        catch_votes = yes_votes[self.catch_gamemode_mask] + no_votes[
            self.catch_gamemode_mask]
        catch_percent_yes_votes = yes_votes[
            self.catch_gamemode_mask] / catch_votes
        catch_cycle = cycle[self.catch_gamemode_mask]

        # Mania processing
        mania_votes = yes_votes[self.mania_gamemode_mask] + no_votes[
            self.mania_gamemode_mask]
        mania_percent_yes_votes = yes_votes[
            self.mania_gamemode_mask] / mania_votes
        mania_cycle = cycle[self.mania_gamemode_mask]

        # Scatter plot highlighting
        brush_fail = (255, 100, 100, 200)
        brush_pass = (100, 100, 255, 200)

        std_scatter_brush = [
            pyqtgraph.mkBrush(
                brush_fail if std_percent_yes_vote <= 0.85 else brush_pass)
            for std_percent_yes_vote in std_percent_yes_votes
        ]
        taiko_scatter_brush = [
            pyqtgraph.mkBrush(
                brush_fail if taiko_percent_yes_vote <= 0.85 else brush_pass)
            for taiko_percent_yes_vote in taiko_percent_yes_votes
        ]
        catch_scatter_brush = [
            pyqtgraph.mkBrush(
                brush_fail if catch_percent_yes_vote <= 0.85 else brush_pass)
            for catch_percent_yes_vote in catch_percent_yes_votes
        ]
        mania_scatter_brush = [
            pyqtgraph.mkBrush(
                brush_fail if mania_percent_yes_vote <= 0.85 else brush_pass)
            for mania_percent_yes_vote in mania_percent_yes_votes
        ]

        # Graphing
        self.graphs['std']['plot'].setData(std_cycle,
                                           std_votes,
                                           pen=None,
                                           symbol='o',
                                           symbolPen=None,
                                           symbolSize=2,
                                           symbolBrush=std_scatter_brush)
        self.graphs['taiko']['plot'].setData(taiko_cycle,
                                             taiko_votes,
                                             pen=None,
                                             symbol='o',
                                             symbolPen=None,
                                             symbolSize=2,
                                             symbolBrush=taiko_scatter_brush)
        self.graphs['catch']['plot'].setData(catch_cycle,
                                             catch_votes,
                                             pen=None,
                                             symbol='o',
                                             symbolPen=None,
                                             symbolSize=2,
                                             symbolBrush=catch_scatter_brush)
        self.graphs['mania']['plot'].setData(mania_cycle,
                                             mania_votes,
                                             pen=None,
                                             symbol='o',
                                             symbolPen=None,
                                             symbolSize=2,
                                             symbolBrush=mania_scatter_brush)
Esempio n. 57
0
import numpy as np
import pyqtgraph as pg
from bwplot import cbox
from pyqtgraph.Qt import QtGui, QtCore

plt = pg.plot()
plt.setWindowTitle('pyqtgraph example: Legend')
plt.addLegend()

for i in range(100):
    x = np.array([3, 5, 5, 3, 3, 7, 9, 9, 7, 7, 7]) + i
    y = [2, 2, 4, 4, 2, 6, 6, 7, 7, 6, 6]
    connect = np.array([1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0])

    pen = 'w'
    brush = pg.mkBrush(cbox(0, as255=True, alpha=80))

    # c = plt.plot(x, y, pen='w', connect=connect, fillBrush=brush, fillLevel='enclosed', name="fillLevel='enclosed'")
    # item = pg.PlotDataItem(x, y, pen='w', connect=connect, fillBrush=brush, fillLevel='enclosed', name="fillLevel='enclosed'")
    item = pg.GraphicsObject
    item.yData = y
    item.xData = x
    item.z
    plt.addItem(item, params={})

if __name__ == '__main__':
    import sys
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()
    def __init__(self,
                 data_filename,
                 bgimg,
                 delta_video_filename,
                 load_original=False,
                 clickable_width=6,
                 draw_interesting_time_points=True,
                 draw_config_function=False):
        self.load_original = load_original

        TemplateBaseClass.__init__(self)
        self.setWindowTitle('Trajectory Viewer GUI v2')

        # Create the main window
        #self.app = QtGui.QApplication([])
        self.ui = WindowTemplate()
        self.ui.setupUi(self)
        #self.show()

        # options
        self.draw_interesting_time_points = draw_interesting_time_points
        self.draw_config_function = draw_config_function

        # Buttons
        self.ui.save_trajecs.clicked.connect(self.save_trajectories)
        self.ui.movie_save.clicked.connect(self.save_image_sequence)
        self.ui.movie_speed.sliderMoved.connect(self.set_movie_speed)
        self.ui.trajec_undo.clicked.connect(self.trajec_undo)
        self.ui.movie_play.clicked.connect(self.movie_play)
        self.ui.movie_pause.clicked.connect(self.movie_pause)
        self.ui.trajec_delete.clicked.connect(self.toggle_trajec_delete)
        self.ui.trajec_cut.clicked.connect(self.toggle_trajec_cut)
        self.ui.trajec_join_collect.clicked.connect(
            self.toggle_trajec_join_collect)
        self.ui.trajec_select_all.clicked.connect(self.select_all_trajecs)
        self.ui.trajec_join_add_data.clicked.connect(
            self.toggle_trajec_join_add_data)
        self.ui.trajec_join_save.clicked.connect(self.trajec_join_save)
        self.ui.trajec_join_clear.clicked.connect(
            self.toggle_trajec_join_clear)
        self.ui.save_annotation.clicked.connect(self.save_annotation)
        self.ui.load_annotations.clicked.connect(self.load_annotations)
        self.ui.annotated_color_checkbox.stateChanged.connect(
            self.toggle_annotated_colors)
        self.ui.annotated_hide_checkbox.stateChanged.connect(
            self.toggle_annotated_hide)

        if not SMALL:
            self.ui.get_original_objid.clicked.connect(
                self.trajec_get_original_objid)
            self.ui.save_colors.clicked.connect(self.save_trajec_colors)

            self.ui.min_selection_length.setPlainText(str(0))
            self.ui.max_selection_length.setPlainText(str(-1))  # -1 means all

        # parameters
        self.data_filename = data_filename
        self.load_data()
        self.backgroundimg_filename = bgimg
        self.backgroundimg = None
        self.binsx = None
        self.binsy = None
        trange = np.float(
            np.max(self.pd.time_epoch.values) -
            np.min(self.pd.time_epoch.values))
        self.troi = [
            np.min(self.pd.time_epoch.values),
            np.min(self.pd.time_epoch.values) + trange * 0.1
        ]
        self.skip_frames = 1
        self.frame_delay = 0.03
        self.path = os.path.dirname(data_filename)
        self.clickable_width = clickable_width

        # load delta video bag
        if delta_video_filename != 'none':
            self.dvbag = rosbag.Bag(delta_video_filename)
        else:
            self.dvbag = None

        # Initialize
        self.trajec_width_dict = {}
        try:
            fname = os.path.join(self.path, 'trajec_to_color_dict.pickle')
            f = open(fname, 'r+')
            self.trajec_to_color_dict = pickle.load(f)
            f.close()
        except:
            self.trajec_to_color_dict = {}
            for key in self.pd.objid.unique():
                color = get_random_color()
                self.trajec_to_color_dict.setdefault(key, color)
        self.plotted_traces_keys = []
        self.plotted_traces = []
        self.trajectory_ends_vlines = []
        self.data_to_add = []
        self.selected_trajectory_ends = []
        self.object_id_numbers = []

        self.annotations = os.path.join(self.path, 'annotations.pickle')
        if os.path.exists(self.annotations):
            f = open(self.annotations, 'r+')
            data = pickle.load(f)
            f.close()
            self.annotated_keys = data.keys()
        else:
            self.annotated_keys = []

        self.time_mouse_click = time.time()
        self.cut_objects = False
        self.delete_objects = False
        self.join_objects = False
        self.add_data = False
        self.crosshair_pen = pg.mkPen('w', width=1)

        self.ui.qtplot_timetrace.enableAutoRange('xy', False)
        if self.config is not None:
            print('**** Sensory stimulus: ', self.config.sensory_stimulus_on)
            for r, row in enumerate(self.config.sensory_stimulus_on):
                v1 = pg.PlotDataItem([
                    self.config.sensory_stimulus_on[r][0],
                    self.config.sensory_stimulus_on[r][0]
                ], [0, 10])
                v2 = pg.PlotDataItem([
                    self.config.sensory_stimulus_on[r][-1],
                    self.config.sensory_stimulus_on[r][-1]
                ], [0, 10])
                try:
                    f12 = pg.FillBetweenItem(
                        curve1=v1,
                        curve2=v2,
                        brush=pg.mkBrush(self.config.sensory_stimulus_rgba[r]))
                except:
                    f12 = pg.FillBetweenItem(curve1=v1,
                                             curve2=v2,
                                             brush=pg.mkBrush(
                                                 (255, 0, 0, 150)))
                self.ui.qtplot_timetrace.addItem(f12)

        lr = pg.LinearRegionItem(values=self.troi)
        f = 'update_time_region'
        lr.sigRegionChanged.connect(self.__getattribute__(f))
        self.ui.qtplot_timetrace.addItem(lr)

        print('drawing interesting time points')
        self.draw_timeseries_vlines_for_interesting_timepoints()
        print('done drawing interesting time points')
        self.ui.qtplot_timetrace.setRange(xRange=[
            np.min(self.time_epoch_continuous),
            np.max(self.time_epoch_continuous)
        ],
                                          yRange=[0, np.max(self.nflies)])
        self.ui.qtplot_timetrace.setLimits(yMin=0, yMax=np.max(self.nflies))
        self.ui.qtplot_timetrace.setLimits(minYRange=np.max(self.nflies),
                                           maxYRange=np.max(self.nflies))

        self.current_time_vline = pg.InfiniteLine(angle=90, movable=False)
        self.ui.qtplot_timetrace.addItem(self.current_time_vline,
                                         ignoreBounds=True)
        self.current_time_vline.setPos(0)
        pen = pg.mkPen((255, 255, 255), width=2)
        self.current_time_vline.setPen(pen)

        # hide a bunch of the axes
        self.ui.qtplot_timetrace.hideAxis('left')
        self.ui.qtplot_timetrace.hideAxis('bottom')

        self.ui.qtplot_trajectory.hideAxis('left')
        self.ui.qtplot_trajectory.hideAxis('bottom')
Esempio n. 59
0
 def update_plot(self):
     # first, we compile the line plot data, then we iterate over them and
     # plot them. we then plot the scatter plots in the same manner
     tfargs = {}  # args to the call of iir.transfer_function
     frequencies = self.frequencies
     plot = OrderedDict()
     # plot data curve (measurement)
     try:
         _, plot['data'] = self.module._data_curve_object.data
     except AttributeError:  # no curve for plotting available
         plot['data'] = []
     # plot designed filter
     plot['filter_design'] = self.module.transfer_function(frequencies, **tfargs)
     # plot product
     plot['data_x_design'] = []
     if self.module.plot_data_times_filter:
         try:
             plot['data_x_design'] = plot['data'] * plot['filter_design']
         except ValueError:
             pass
     # disable data plot if this is desired
     if not self.module.plot_data:
         plot['data'] = []
     # plot everything (all lines) up to here
     for k, v in plot.items():
         self.graph_widget.plots[k].setData(frequencies[:len(v)],
                                            self._magnitude(v))
         self.graph_widget.plots[k+'_phase'].setData(frequencies[:len(v)],
                                                 self._phase(v))
     # plot poles and zeros
     aws = self.attribute_widgets
     for end in ['poles', 'zeros']:
         mag, phase = [], []
         for start in ['complex', 'real']:
             key = start+'_'+end
             freq = getattr(self.module, key)
             if start == 'complex':
                 freq = np.imag(freq)
                 defsize = 15  # complex (double) PZ's are plotted with larger symbols
             else:
                 defsize = 10
             freq = np.abs(freq)
             tf = self.module.transfer_function(freq, **tfargs)
             selected = aws[key].attribute_value.selected
             brush = [pg.mkBrush(color='m')
                      if (num == selected)
                      else pg.mkBrush(color='y')
                      for num in range(aws[key].number)]
             size = [defsize*1.0 if (num == selected) else defsize
                      for num in range(aws[key].number)]
             mag += [{'pos': (fr, val), 'data': i, 'brush': br, 'size': si}
              for (i, (fr, val, br, si))
              in enumerate(zip(list(np.log10(freq)),
                               list(self._magnitude(tf)),
                               brush,
                               size))]
             phase += [{'pos': (fr, val), 'data': i, 'brush': br, 'size': si}
              for (i, (fr, val, br, si))
              in enumerate(zip(list(np.log10(freq)),
                               list(self._phase(tf)),
                               brush,
                               size))]
         self.graph_widget.plots[end].setPoints(mag)
         self.graph_widget.plots[end+'_phase'].setPoints(phase)
     # plot the measurement data if desired
     if self.module.plot_measurement and hasattr(self.module, '_measurement_data'):
         f, v = self.module._measurement_data
         f[f<=0] = sys.float_info.epsilon
         f = np.asarray(np.log10(f), dtype=float)
         self.graph_widget.plots['filter_measurement'].setData(x=f[:len(v)],
                                                               y=self._magnitude(v))
         self.graph_widget.plots['filter_measurement_phase'].setData(x=f[:len(v)],
                                                                     y=self._phase(v))
Esempio n. 60
0
    def __init__(self):
        super(ImageViewer, self).__init__()

        self.createActions()
        self.createMenus()
        self.resize(800, 600)
        win = QWidget()
        self.setCentralWidget(win)
        # creates plot
        self.plot = pg.PlotWidget(name="VES Locations")
        layout = BorderLayout()
        layout.add(QWidgetItem(self.plot), BorderLayout.Center)
        # List items
        # self.list_w =  myListWidget()
        self.list_w = QListWidget()
        self.listitem.append(QListWidgetItem('Welcome to ResLayer!!!'))
        self.list_w.setFrameStyle(QFrame.Box | QFrame.Raised)
        layout.add(QWidgetItem(self.list_w), BorderLayout.West)
        win.setLayout(layout)
        self.list_w.addItem(self.listitem[0])

        # text=self.list_w.itemClicked.connect(self.list_w.Clicked)
        self.list_w.itemClicked.connect(self.OnSingleClick)
        # print(text)

        self.setWindowTitle("Border Layout")

        mypen = pg.mkPen('y', width=1)
        self.vesdf, self.data_dfs = load_pkl(self.base_folder +
                                             'vesdf_datadf.pkl')
        self.lith_dict = load_pkl(self.base_folder + 'lith_dict.pkl')
        new_ves = load_pkl(self.base_folder + 'new_ves.pkl')
        try:
            self.boundaries = load_pkl(self.base_folder + 'boundaries.pkl')
        except:
            self.boundaries = []
        try:
            self.drilldf = load_pkl(self.base_folder + 'drill_info.pkl')

        except:
            self.drilldf = []
        try:
            self.profiles = load_pkl(self.base_folder + 'profiles.pkl')
            # print(self.profiles)
            for profile in self.profiles:
                self.listitem.append(
                    QListWidgetItem('Profile: ' +
                                    '-'.join([p for p, q in profile])))
                self.list_w.addItem(self.listitem[-1])
        except:
            self.profiles = []

        self.VES,self.E,self.N,self.Ele,self.block=self.vesdf['VES No.'].values,self.vesdf.Easting.values.astype(np.float), \
        self.vesdf.Northing.values.astype(np.float), \
        str_array2floats(self.vesdf.RL.values),self.vesdf.Block.values

        self.coords = [[xi, yi] for xi, yi in zip(self.E, self.N)]

        self.plot.setLabel('left', "Northing", units='deg')
        self.plot.setLabel('bottom', "Easting", units='deg')
        self.plot.showGrid(x=1, y=1, alpha=None)
        self.plot.showAxis('right')
        self.plot.showAxis('top')
        self.plot.getViewBox().setAspectLocked(True)
        # self.curve = pg.ScatterPlotItem(size=20, pen=pg.mkPen(None), brush=pg.mkBrush(255, 255, 255, 120))
        # spots = [{'pos': j, 'data': 1} for j in zip(self.E,self.N)]
        # self.curve.addPoints(spots)

        self.curve = self.plot.plot(
            x=self.E, y=self.N, size=10, pen=pg.mkPen(None),
            symbol='o')  #brush=pg.mkBrush(255, 100, 255, 120),pen=None,
        #drill information
        if len(self.drilldf) > 0:
            drillE, drillN, drill_labels = self.drilldf.Easting.values.astype(
                np.float), self.drilldf.Northing.values.astype(
                    np.float), self.drilldf.Location.values
            self.plot.plot(x=drillE,
                           y=drillN,
                           size=30,
                           pen=pg.mkPen(None),
                           symbol='s',
                           brush=pg.mkBrush('r'),
                           fc='r')
            self.plot_labels(self.plot, drillE, drillN, drill_labels)
        #district and block boundaries
        if len(self.boundaries) > 0:
            for b in self.boundaries:
                self.plot.plot(x=[g for g in b[0]], y=[g for g in b[1]])
        self.plot.addItem(self.curve)
        # labels=['{}-{}'.format(ves,blk) for ves,blk in zip(self.VES,self.block)]
        self.plot_labels(self.plot, self.E, self.N, self.VES, self.block)
        self.curve.scene().sigMouseMoved.connect(self.onMouseMoved)

        self.curve.scene().sigMouseClicked.connect(self.decideWhere2go)