Exemplo n.º 1
0
 def createPlotRegion(self):
     self.linearRegionItem = pg.LinearRegionItem(brush=pg.intColor(1,alpha=100))
     self.linearRegionItem.setZValue(10)
     self.regionLabel = pg.TextItem(self.trackableFeature.name, color=pg.intColor(1), anchor=(0,1))
     self.regionLabel.setX(self.linearRegionItem.getRegion()[0])
     self.plotWidget.addItem(self.regionLabel)
     self.plotWidget.addItem(self.linearRegionItem, ignoreBounds=True)
     self.linearRegionItem.sigRegionChanged.connect(self.linearRegionItem_RegionChanged)
     self.regionObserver.bind(self.linearRegionItem,self.linearRegionItem.setRegion,self._linearRegionItem_regionChanged)
Exemplo n.º 2
0
 def matchFreq(self):
     freq1,freq2,ok=matchDialog.getData()
     pencil1=pg.mkPen(color=pg.intColor(1))
     pencil2=pg.mkPen(color=pg.intColor(20))        
     pencil3=pg.mkPen(color=pg.intColor(30))
     for k in range(1,4):
         self.p3.plot([k*freq1,k*freq1],[0,1.],pen=pencil1)
         self.p3.plot([k*freq2,k*freq2],[0,1.],pen=pencil2)
         for l in range(1,3):
             self.p3.plot([k*freq2-l*freq1,k*freq2-l*freq1],[0,.5],pen=pencil3)            
             self.p3.plot([k*freq2+l*freq1,k*freq2+l*freq1],[0,.5],pen=pencil3)            
     self.p3.addItem(pg.PlotDataItem(pen=pencil1,name='ICRF'))
     self.p3.addItem(pg.PlotDataItem(pen=pencil2,name='Helicon'))
     self.p3.addItem(pg.PlotDataItem(pen=pencil3,name='Beat'))
Exemplo n.º 3
0
    def redrawPlot(self):
        self.graph.clearPushed()

        for bnum in range(0, self.numKeys):
            if self.enabledbytes[bnum]:
                self.graph.setColorInt(bnum, self.numKeys)
                self.graph.passTrace(self.SADList[bnum], pen=pg.mkPen(pg.intColor(bnum, 16)), idString = str(bnum))
Exemplo n.º 4
0
 def plotSignal(self,item):
     indexColor=0
     self.p1.clear()
     self.p2.clear()
     for fileName in self.fileName:
         print fileName
         self.Back=False
         self.signalName=item
         time,data,self.sampling=readHdf5.getData(fileName,item,self.env)
         self.time=np.array(time)
         self.data=np.array(data)
         self.frqlabel.setText('sampling rate: '+str(self.sampling))
         pencil=pg.mkPen(color=pg.intColor(indexColor))
         self.p1.plot(self.time,self.data,pen=pencil)
         self.p2.plot(self.time,self.data,pen=pencil)
         indexColor=indexColor+1
         
     if self.existingData:
         self.lr=pg.LinearRegionItem([self.left,self.right])
     else:
         self.lr=pg.LinearRegionItem([self.time[0],self.time[-1]])
         self.left=self.time[0]
         self.right=self.time[-1]
     self.lr.setZValue(-10)
     self.p1.addItem(self.lr)
     self.lr.sigRegionChanged.connect(self.updatePlot)
Exemplo n.º 5
0
    def updateBluetooth(self): 
        returnedList = blescan.parse_events(self.sock, 1)
        for beacon in returnedList:
            words = beacon.split(',')
            mac = words[0]
            uid = words[1]
            major = words[2]
            minor = words[3]
            power = words[4]
            rssi = words[5]
            print mac, rssi, minor
            #print "dict lenght" ,len(self.signalList)
            
            if mac not in self.signalList:
                #self.signalList[mac] = np.zeros(self.bufferLength,'f')
                self.signalList[mac] = np.zeros(0,'f')
                self.curveList[mac] = self.p.plot(pen=QtGui.QPen(pg.intColor(self.nextColor)))
                self.nextColor += 1
            
            s = self.signalList[mac]
            val = 100 + float(rssi)
            if s.size < self.bufferLength:
                s = np.append(s,val)
#                if s.size > 4:
#                     s[-1] = self.runningMeanFast(s,3)[0]             
                print "append" , val
            else:      
                s = np.roll(s,-1)
                s[-1] = val         
#                s[-1] = self.runningMeanFast(s,3)[0]             
        
            self.curveList[mac].setData(s)       
            self.signalList[mac] = s
            self.timeElapsed()
            self.app.processEvents()  ## force complete redraw for every plot
 def addTracesABR(self, x, ys, intensity, trace_num):
     self.clearTraces()
     nreps = ys.shape[0]
     for irep in reversed(range(nreps)):
         self.trace_stash.append(self.plot(x, ys[irep, :], pen=(irep, nreps)))
         line = self.plot(pen=pg.intColor(irep, hues=nreps))
         self.legend.addItem(line, 'trace_' + str(trace_num[irep]) + ': ' + str(intensity[irep]) + ' dB')
         self.legend_names.append('trace_' + str(trace_num[irep]) + ': ' + str(intensity[irep]) + ' dB')
Exemplo n.º 7
0
    def displayPartitions(self, differences={"partclass":None, "diffs":None}, traces=None, tRange=(0, -1)):
        if traces is None:
            traces = self.traceManager()

        if tRange[1] < 0:
            tRange = (tRange[0], traces.numTrace() + 1 + tRange[1])

        self.partObject.setPartMethod(differences["partclass"])

        self.numKeys = len(self.partObject.partMethod.getPartitionNum(traces, 0))
        self.SADList = differences["diffs"]

        self.graph = self.parent.getGraphWidgets(["Partition Differences"])[0]

        # Place byte selection option on graph
        if hasattr(self, 'enabledbytes') and len(self.enabledbytes) == self.numKeys:
            pass
        else:
            self.enabledbytes = [False] * self.numKeys

        self.doRedraw = True

        self.byteNumAct = []
        for i in range(0, self.numKeys):
            ql = QToolButton()
            ql.setText('%d' % i)
            color = pg.intColor(i, self.numKeys)
            ql.setStyleSheet("color: rgb(%d, %d, %d)" % (color.red(), color.green(), color.blue()))
            qa = QWidgetAction(self)
            qa.setDefaultWidget(ql)
            qa.setStatusTip('%d' % i)
            ql.setCheckable(True)
            ql.setChecked(self.enabledbytes[i])
            ql.clicked[bool].connect(partial(self.setBytePlot, i))
            self.byteNumAct.append(qa)

        byteNumAllOn = QAction('All On', self)
        byteNumAllOff = QAction('All Off', self)
        byteNumAllOn.triggered.connect(partial(self.setByteAll, True))
        byteNumAllOff.triggered.connect(partial(self.setByteAll, False))

        bselection = QToolBar()

        for i in range(0, self.numKeys):
            bselection.addAction(self.byteNumAct[i])
        bselection.addAction(byteNumAllOn)
        bselection.addAction(byteNumAllOff)
        self.graph.addWidget(bselection)

        self.graph.setPersistance(True)

        # self.poi.setDifferences(SADList)

        # self.parent.findParam('poi-pointrng').setLimits((0, len(SADList[0])))
        # self.parent.findParam('poi-pointrng').setValue((0, len(SADList[0])))
        self.redrawPlot()
def doPlot(columns, first, last):
    from pyqtgraph.Qt import QtGui, QtCore
    import numpy as np
    import pyqtgraph as pg
    import pyqtgraph.exporters
    import itertools

    pg.setConfigOptions(
        antialias=True,
        background='w',
        foreground='k',
        )
    app = QtGui.QApplication([])

    win = pg.GraphicsWindow(title="Curve plotter")
    win.setWindowTitle('Curve plotter')

    plot = win.addPlot(title="Rights and Usage")
    ndays=(last-first).days+1
    timeAxis = plot.getAxis('bottom')
    timeAxis.setTicks([[
        (i*25, first+datetime.timedelta(days=i))
        for i in xrange(ndays)
        ],[
        (i, i%25)
        for i in xrange(25*ndays)
        ]])
    timeAxis.setStyle(
        tickTextHeight=390,
        )
    timeAxis.setGrid(100)

    plot.addLegend()
    for i,column in enumerate(columns):
        plot.plot(np.array(column[1:]),
            pen=pg.intColor(i),
            name=column[0],
            symbol='o',
            symbolBrush=pg.intColor(i),
            )

    win.show()
    app.exec_()
Exemplo n.º 9
0
 def __init__(self, x0=0.0, v0=0.0, t0=0.0, prog=None, pen=None, brush=None):
     if pen is None:
         pen = pg.intColor(Clock.nClocks, 12)
     if brush is None:
         brush = (0,0,150)
     Clock.nClocks += 1
     self.x0 = x0
     self.v0 = v0
     self.t0 = t0
     self.prog = prog
     self.pen = pen
     self.brush = brush
Exemplo n.º 10
0
    def __init__(self, groups, xlims=None, parent=None):
        super(ProgressWidget, self).__init__(parent)
        self.lines = []
        self.legend = self.addLegend()
        for iline in range(len(groups)):
            # give each line a different color
            line = self.plot(pen=pg.intColor(iline, hues=len(groups)))
            self.lines.append(line)
            self.legend.addItem(line, str(groups[iline]))

        if xlims is not None:
            self.setXlim((xlims[0], xlims[1]))
        self.groups = groups
Exemplo n.º 11
0
 def new_curve(self, results, color=pg.intColor(0), **kwargs):
     if 'pen' not in kwargs:
         kwargs['pen'] = pg.mkPen(color=color, width=2)
     if 'antialias' not in kwargs:
         kwargs['antialias'] = False
     curve = ResultsCurve(results, 
         x=self.plot_frame.x_axis,
         y=self.plot_frame.y_axis,
         **kwargs
     )
     curve.setSymbol(None)
     curve.setSymbolBrush(None)
     return curve
Exemplo n.º 12
0
 def __init__(self, dataForCandle=None):
     super(pgCandleWidget, self).__init__()
     # 0) adds candle
     self.candleData = dataForCandle 
     self.item01 = CandlestickItem(dataForCandle)        
     #self.addItem(self.item01) 
     # 1)cross hair
     self.vLine = pg.InfiniteLine(angle=90, movable=False)
     self.hLine = pg.InfiniteLine(angle=0, movable=False)
     self.addItem(self.vLine, ignoreBounds=True)
     self.addItem(self.hLine, ignoreBounds=True)
     # 2) adds textInfo
     self.textInfo = pg.TextItem("test")
     self.addItem(self.textInfo, ignoreBounds=True)        
     
     #vb = self.plotItem.vb
     #vb.setAspectLocked(True)
     n = 300
     self.lastClicked = []
     def clicked(plot, points):
         for p in self.lastClicked:
             p.resetPen()
         print("clicked points", points)
         for p in points:
             p.setPen('b', width=2)
         self.lastClicked = points
         
     self.item02 = pg.ScatterPlotItem(size=10, pen=pg.mkPen('w'), pxMode=False)
     pos = np.random.normal(size=(2,n), scale=1e-5)
     
     spots3 = []
     for i in range(10):
         for j in range(10):
             spots3.append({'pos': (1e-6*i, 1e-6*j), 'size': 1, 'pen': {'color': 'w', 'width': 2}, 'brush':pg.intColor(i*10+j, 100)})        
     
     n=5
     spots = [{'pos': pos[:,i],  'brush':pg.intColor(i, n), 'symbol': i%5, 'size': 50+i/10.} for i in range(n)]
     
     a1 = {'pos': (10, 20), 'data': 5,'size': 5, 'pen': {'color': 'w', 'width': 2}, 'symbol': 't', 'brush':pg.intColor(10, 100)}
     a2 = {'pos': (15, 20), 'data': 5,'size': 5, 'pen': {'color': 'w', 'width': 2}, 'symbol': 'd', 'brush':pg.intColor(10, 100)}
     a3 = {'pos': (20, 20), 'data': 5,'size': 5, 'pen': {'color': 'w', 'width': 2}, 'symbol': '+', 'brush':pg.intColor(10, 100)}
     spots2 = []
     spots2.append(a1)
     spots2.append(a2)
     spots2.append(a3)
     self.item02.addPoints(spots2)
     self.addItem(self.item02)
     self.item02.sigClicked.connect(clicked)         
     
     
     self.proxy = pg.SignalProxy(self.scene().sigMouseMoved, rateLimit=60, slot=self.mouseMoved)
Exemplo n.º 13
0
	def receiveNewNames(self, newNames):
		# print("Receiving new names")
		self.names = newNames
		self.dataColumns = len(self.names)

		for i in range(self.dataColumns):	  
			color = pg.intColor(i, self.dataColumns) 
			self.curveColors.append(color)	
			item = QtGui.QStandardItem(self.names[i])
			item.setBackground(color)
			item.setCheckState(Qt.Checked)
			item.setCheckable(True)
			self.listViewModel.appendRow(item)
			self.nameCheckItems.append(item)
Exemplo n.º 14
0
    def addSource(self, sourceX=None, sourceY=None):
        if (sourceX is not None and not (isinstance(sourceX.content(),  int) or isinstance(sourceX.content(),  float))) or \
        (sourceY is not None and not (isinstance(sourceY.content(),  int) or isinstance(sourceY.content(),  float))):
            print "cannot add this type as source"
            return

        sourceTarget=Curve2DBox("data", self, dataRange=[0,0], color=pg.intColor(len(self.targets)))
        #if sourceX is not None:
        #    sourceTarget.sources[0].updateSource(sourceX)
        if sourceY is not None:
            sourceTarget.sources[1].updateSource(sourceY)
        self.targets.append(sourceTarget)
        self.targets_layout.addWidget(sourceTarget)
        self.rebuildLegend()
Exemplo n.º 15
0
 def __init__(self, x0=0.0, y0=0.0, m0=1.0, v0=0.0, t0=0.0, pen=None, brush=None, prog=None):
     if pen is None:
         pen = pg.intColor(Clock.nClocks, 12)
     if brush is None:
         brush = (0,0,150)
     Clock.nClocks += 1
     self.pen = pg.mkPen(pen)
     self.brush = pg.mkBrush(brush)
     self.y0 = y0
     self.x0 = x0
     self.v0 = v0
     self.m0 = m0
     self.t0 = t0
     self.prog = prog
Exemplo n.º 16
0
def onViewRangeChanged(viewRange, x, y, barGraphItem):
    """Updates barGraphItem data depending on plotItem viewRange.
    @param viewRange: PlotItem viewRange
    @param x, y: Data of barGraphItem
    @param barGraphItem: BarGraphItem which data is to be updated
    """
    v = list()
    v.append(max(x[0], viewRange[0]))
    v.append(min(x[-1], viewRange[-1]))
    # n = 1024
    newX = np.linspace(v[0], v[1], n)
    newY = np.interp(newX, x, y)
    # colors must be interpolated either in my task, here I just create new list of random colors
    colors = [pg.intColor(np.random.randint(1, 100)) for i in xrange(n)]
    barGraphItem.setOpts(x0=newX[:-1], x1=newX[1:], y0=[0] * n, y1=newY, brushes=colors, pens=colors)
Exemplo n.º 17
0
    def setup_plot(self):
        self.plot = self#.plot()
        self.showGrid(x=True, y=True)

        # don't show the default left & bottom axes
        [self.plot.showAxis(o, False) for o in ('left', 'bottom')]

        # create & add scatter item to plot
        self.scatters = []
        for i, ul in enumerate(self.ulabels):
            mask = self.labels == ul
            brush = pg.intColor(i, hues=len(self.ulabels), alpha=125)
            spi = pg.ScatterPlotItem(x=self.x[mask], y=self.y[mask], pen=None, brush=brush)
            self.scatters.append(spi)

        map(self.plot.addItem, self.scatters)
Exemplo n.º 18
0
 def to_update(self,obj=None):
     self.spots,self.adj = self.graphModel.to_plot()
     self.pos = []
     try:
         selected = self.selectionModel().selectedRows()
         selected = [x.row() for x in selected]
     except AttributeError:
         selected = []
     for i,s in enumerate(self.spots):
         if i in selected:
             s['pen'] = pg.mkPen('r')
         else:
             s['pen'] = pg.mkPen('k')
         for k,v in s.items():
             if k == 'pos':
                 self.pos.append(v)
             elif k == 'symbol':
                 if v is None:
                     val = symbols[0]
                 elif v[0] == 'factor':
                     if v[1] > len(symbols) - 1:
                         val = symbols[-1]
                     else:
                         val = symbols[v[1]]
                 else:
                     val = symbols[0]
                 s[k] = val
             elif k == 'size':
                 if v is None:
                     val = s_r[0]
                 elif v[0] == 'factor':
                     val = ((s_r[1] - s_r[0]) * (v[1]/v[2])) + s_r[0]
                 else:
                     val = ((s_r[1] - s_r[0]) * v[1]) + s_r[0]
                 s[k] = val
             elif k == 'brush':
                 if v is None:
                     val = pg.mkBrush('c')
                 elif v[0] == 'factor':
                     s[k] = pg.mkBrush(pg.intColor(v[1], hues = v[2]))
                 else:
                     s[k] = pg.mkBrush(0,0,((c_r[1] - c_r[0]) * v[1]) + c_r[0])
         self.spots[i] = s
     self.update_data()
def makeScatterPlot():
## 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)
    s1.sigClicked.connect(clicked)


## 2) Spots are transform-invariant, but not identical (top-right plot). 
## In this case, drawing is as fast as 1), but there is more startup overhead
## and memory usage since each spot generates its own pre-rendered image.
    s2 = pg.ScatterPlotItem(size=10, pen=pg.mkPen('w'), pxMode=True)
    pos = np.random.normal(size=(2,n), scale=1e-5)
    spots = [{'pos': pos[:,i], 'data': 1, 'brush':pg.intColor(i, n), 'symbol': i%5, 'size': 5+i/10.} for i in range(n)]
    s2.addPoints(spots)
    w2.addItem(s2)
    s2.sigClicked.connect(clicked)


## 3) Spots are not transform-invariant, not identical (bottom-left). 
## This is the slowest case, since all spots must be completely re-drawn 
## every time because their apparent transformation may have changed.
    s3 = pg.ScatterPlotItem(pxMode=False)   ## Set pxMode=False to allow spots to transform with the view
    spots3 = []
    for i in range(10):
        for j in range(10):
            spots3.append({'pos': (1e-6*i, 1e-6*j), 'size': 1e-6, 'pen': {'color': 'w', 'width': 2}, 'brush':pg.intColor(i*10+j, 100)})
    s3.addPoints(spots3)
    w3.addItem(s3)
    s3.sigClicked.connect(clicked)


## Test performance of large scatterplots
    s4 = pg.ScatterPlotItem(size=10, pen=pg.mkPen(None), brush=pg.mkBrush(255, 255, 255, 20))
    pos = np.random.normal(size=(2,10000), scale=1e-9)
    s4.addPoints(x=pos[0], y=pos[1])
    w4.addItem(s4)
    s4.sigClicked.connect(clicked)
    QtGui.QApplication.instance().exec_()
Exemplo n.º 20
0
    def plot_data(self, X, y):
        self.clear_plot()

        # get the simple cross validation score
        clf = LDA()
        scores = cross_validation.cross_val_score(clf, X, y, cv=5)
        score = np.mean(scores)
        self.ui.titleLabel.setText("Accuracy: %.2f" % score)

        # project the data to 3D for visualization
        clf = LDA(n_components=3)
        X_proj = clf.fit(X, y).transform(X)

        labels = sorted(np.unique(y))
        for i in labels:
            plot = gl.GLScatterPlotItem(
                pos=X_proj[y == i], color=pg.glColor(pg.intColor(i)))
            self.plotWidget.addItem(plot)
            self.plot_items.append(plot)
Exemplo n.º 21
0
    def color_by_layer(self, root=None):
        try:
            unblock = False
            if not isinstance(root, pg.QtGui.QTreeWidgetItem):
                self.blockSignals(True)
                unblock = True
                root = self.labels_by_acronym['Isocortex']['item']

            name = str(root.text(1))
            if ', layer' in name.lower():
                layer = name.split(' ')[-1]
                layer = {'1': 0, '2': 1, '2/3': 2, '4': 3, '5': 4, '6a': 5, '6b': 6}[layer]
                self.set_label_color(root.id, pg.intColor(layer, 10), recursive=False, emit=False)

            for i in range(root.childCount()):
                self.color_by_layer(root.child(i))
        finally:
            if unblock:
                self.blockSignals(False)
                self.labels_changed.emit()
Exemplo n.º 22
0
    def __init__(self, plotter, refresh_time=0.1, parent=None):
        super(PlotterWindow, self).__init__(parent)
        self.plotter = plotter
        columns = plotter.results.procedure.DATA_COLUMNS

        self.setWindowTitle("Results Plotter")
        self.main = QtGui.QWidget(self)

        vbox = QtGui.QVBoxLayout(self.main)
        vbox.setSpacing(0)

        hbox1 = QtGui.QHBoxLayout()
        hbox1.setSpacing(6)
        hbox1.setContentsMargins(-1, 6, -1, -1)

        file_label = QtGui.QLabel(self.main)
        file_label.setText("Data Filename:")

        self.file = QtGui.QLineEdit(self.main)
        self.file.setText(plotter.results.data_filename)

        hbox1.addWidget(file_label)
        hbox1.addWidget(self.file)
        vbox.addLayout(hbox1)

        self.plot_widget = PlotWidget(columns, check_status=False)
        self.plot = self.plot_widget.plot

        vbox.addWidget(self.plot_widget)

        self.main.setLayout(vbox)
        self.setCentralWidget(self.main)
        self.main.show()
        self.resize(800, 600)

        self.curve = ResultsCurve(
            plotter.results, columns[0], columns[1], pen=pg.mkPen(color=pg.intColor(0), width=2), antialias=False
        )
        self.plot.addItem(self.curve)

        self.plot_widget.updated.connect(self.check_stop)
    def setup(self, buffer):
        """
        Setup the graph with the number of sensors from the buffer.
        """

        self._number_of_sensors = buffer.number_of_sensors

        # Create the data lists for the graph.
        self._graph_data = [[] for vehicle in range(1, self._number_of_sensors + 1)]

        # Create the curves for the graph.
        color_index = 0
        for vehicle in range(1, self._number_of_sensors + 1):
            index = vehicle - 1

            color = pg.intColor(color_index, hues=len(self._graph_data), maxValue=200)
            color_index += 1

            curve = self._graph.plot()
            curve.setData(self._graph_data[index], pen=pg.mkPen(color, width=1.5))
            self._graph_curves.append(curve)
Exemplo n.º 24
0
 def calculatefft(self):
     indexColor=0
     self.p3.clear()
     self.p3.addLegend()
     for fileName in self.fileName:
         time,data,self.sampling=readHdf5.getData(fileName,self.signalName,self.env)
         self.time=np.array(time)
         self.data=np.array(data)
         rang=self.p2.getPlotItem().getViewBox().viewRange()
         rang2=rang[0]
         # Number of samplepoints
         dataslice=self.data[(self.time>=rang2[0]) & (self.time<=rang2[1])]
         N=len(dataslice)
         # sample spacing
         T = 1.0 / self.sampling
         yf = scipy.fftpack.fft(dataslice)
         xf = np.linspace(0.0, 1.0/(2.0*T), N/2)
         pencil=pg.mkPen(color=pg.intColor(indexColor))
         self.p3.plot(xf, 2.0/N * np.abs(yf[0:N/2]),pen=pencil,name=fileName[0:-5])
         indexColor=indexColor+1
     self.p3.setLabel('left', "Spectral power (SI)")
     self.p3.setLabel('bottom', "Frequency (Hz)")
Exemplo n.º 25
0
def main():
    app = QtGui.QApplication(sys.argv)
    tabs = QtGui.QTabWidget()

    for family in families:
        scroller = QtGui.QScrollArea()
        vb = pg.GraphicsWindow()
        vb.setMinimumHeight(3000)
        vb.setMinimumWidth(1900)
        scroller.setWidget(vb)
        for i, name in enumerate(pywt.wavelist(family)):
            pen = pg.intColor(i)
            wavelet = pywt.Wavelet(name)
            if wavelet.orthogonal:
                phi, psi, x = wavelet.wavefun(level=5)
                ax = vb.addPlot(title=wavelet.name + " phi")
                ax.plot(phi, pen=pen)
                bx = vb.addPlot(title=wavelet.name + " psi")
                bx.plot(psi, pen=pen)
            else:
                phi, psi, phi_r, psi_r, x = wavelet.wavefun(level=5)
                ax = vb.addPlot(title=wavelet.name + " phi")
                ax.plot(phi, pen=pen)
                bx = vb.addPlot(title=wavelet.name + " psi")
                bx.plot(psi, pen=pen)
                ax = vb.addPlot(title=wavelet.name + " phi_r")
                ax.plot(phi_r, pen=pen)
                bx = vb.addPlot(title=wavelet.name + " psi_r")
                bx.plot(psi_r, pen=pen)
            if i % 2 == 0:
                vb.nextRow()
        tabs.addTab(scroller, family)

    tabs.setWindowTitle('Wavelets')
    tabs.resize(1920, 1080)
    tabs.show()
    sys.exit(app.exec_())
    def _check(self):
        # Update progress bar completion percentage every time, not only when 
        # new iteration callback data has arrived.
        self._progress.setValue(self._runner.get_iteration_current())

        # Stop the runner and update timer if the planning is done, then check 
        # for updates and final data.
        if self._runner.done or not self._running:
            self._stop()
            self._update_timer.stop()

        if self._updated:
            # Update the graph with updated iteration statistics.
            c = 0
            for name, data in self._graph_data.iteritems():
                if name not in self._graph_plots:
                    color = pg.intColor(c, hues=len(self._graph_data),
                                        maxValue=200)
                    plot = self._graph.plot(symbol='o', symbolBrush=color,
                                            symbolSize=5, pen=color, name=name)
                    self._graph_plots[name] = plot

                self._graph_plots[name].setData(data)
                c += 1

            self._draw_list_item(self._graph_label, self._graph)

        if self._runner.done or self._updated:
            # Draw the plots for the Pareto front and any selected solution.
            self._runner.make_pareto_plot(self._front_axes)
            self._front_canvas.draw()
            self._draw_list_item(self._front_label, self._front_canvas)

            self._draw_solutions()

        self._updated = False
Exemplo n.º 27
0
import numpy as np

win = pg.plot()
win.setWindowTitle('pyqtgraph example: beeswarm')

data = np.random.normal(size=(4,20))
data[0] += 5
data[1] += 7
data[2] += 5
data[3] = 10 + data[3] * 2

## Make bar graph
#bar = pg.BarGraphItem(x=range(4), height=data.mean(axis=1), width=0.5, brush=0.4)
#win.addItem(bar)

## add scatter plots on top
for i in range(4):
    xvals = pg.pseudoScatter(data[i], spacing=0.4, bidir=True) * 0.2
    win.plot(x=xvals+i, y=data[i], pen=None, symbol='o', symbolBrush=pg.intColor(i,6,maxValue=128))

## Make error bars
err = pg.ErrorBarItem(x=np.arange(4), y=data.mean(axis=1), height=data.std(axis=1), beam=0.5, pen={'color':'w', 'width':2})
win.addItem(err)


## Start Qt event loop unless running in interactive mode or using pyside.
if __name__ == '__main__':
    import sys
    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()
Exemplo n.º 28
0
    def show(self):
        self.win = pg.GraphicsWindow()
        self.win.setBackground('w')
        Fs = self.Fs
        p1 = self.win.addPlot(title='Stimulus',
                              row=0,
                              col=0,
                              labels={
                                  'bottom': 'T (ms)',
                                  'left': 'V'
                              })
        p1.plot(self.stim.time * 1000,
                self.stim.sound,
                pen=pg.mkPen('k', width=0.75))
        p1.setXLink(p1)

        p2 = self.win.addPlot(title='AN spikes',
                              row=1,
                              col=0,
                              labels={
                                  'bottom': 'T (ms)',
                                  'left': 'AN spikes (first trial)'
                              })
        for nr in range(self.nrep):
            xan = []
            yan = []
            for k in range(len(self.pre_cells[nr])):
                r = self.pre_cells[nr][k]._spiketrain
                xan.extend(r)
                yr = k + np.zeros_like(r) + 0.2
                yan.extend(yr)
            c = pg.PlotCurveItem()
            xp = np.repeat(np.array(xan), 2)
            yp = np.repeat(np.array(yan), 2)
            yp[1::2] = yp[::2] + 0.6
            c.setData(xp.flatten(),
                      yp.flatten(),
                      connect='pairs',
                      pen=pg.mkPen(pg.intColor(nr, self.nrep),
                                   hues=self.nrep,
                                   width=1.0))
            p2.addItem(c)
        p2.setXLink(p1)

        p3 = self.win.addPlot(title='%s Spikes' % self.cell,
                              row=2,
                              col=0,
                              labels={
                                  'bottom': 'T (ms)',
                                  'left': 'Trial #'
                              })
        xcn = []
        ycn = []
        xspks = []
        for k in range(self.nrep):
            bspk = PU.findspikes(self.time[k], self.vms[k], -35.)
            xcn.extend(bspk)
            yr = k + np.zeros_like(bspk) + 0.2
            ycn.extend(yr)
        d = pg.PlotCurveItem()
        xp = np.repeat(np.array(xcn), 2)
        yp = np.repeat(np.array(ycn), 2)
        yp[1::2] = yp[::2] + 0.6
        d.setData(xp.flatten(),
                  yp.flatten(),
                  connect='pairs',
                  pen=pg.mkPen('k', width=1.5))
        p3.addItem(d)
        p3.setXLink(p1)

        p4 = self.win.addPlot(title='%s Vm' % self.cell,
                              row=3,
                              col=0,
                              labels={
                                  'bottom': 'T (ms)',
                                  'left': 'Vm (mV)'
                              })
        for nr in range(self.nrep):
            p4.plot(self.time[nr],
                    self.vms[nr],
                    pen=pg.mkPen(pg.intColor(nr, self.nrep),
                                 hues=self.nrep,
                                 width=1.0))
        p4.setXLink(p1)

        p5 = self.win.addPlot(title='xmtr',
                              row=0,
                              col=1,
                              labels={
                                  'bottom': 'T (ms)',
                                  'left': 'gSyn'
                              })
        if synapseType == 'multisite':
            for nr in [0]:
                syn = self.synapses[nr]
                j = 0
                for k in range(self.n_sgc):
                    synapse = syn[k]
                    for i in range(synapse.terminal.n_rzones):
                        p5.plot(self.time[nr],
                                self.xmtrs[nr]['xmtr%04d' % j],
                                pen=pg.mkPen(pg.intColor(nr, self.nrep),
                                             hues=self.nrep,
                                             width=1.0))
                        j = j + 1
        p5.setXLink(p1)

        p6 = self.win.addPlot(title='AN PSTH',
                              row=1,
                              col=1,
                              labels={
                                  'bottom': 'T (ms)',
                                  'left': 'Sp/ms/trial'
                              })
        bins = np.arange(0, 200, 1)
        (hist, binedges) = np.histogram(xan, bins)
        curve6 = p6.plot(binedges,
                         hist,
                         stepMode=True,
                         fillBrush=(0, 0, 0, 255),
                         brush=pg.mkBrush('k'),
                         fillLevel=0)

        p7 = self.win.addPlot(title='%s PSTH' % self.cell,
                              row=2,
                              col=1,
                              labels={
                                  'bottom': 'T (ms)',
                                  'left': 'Sp/ms/trial'
                              })
        bins = np.arange(0, 200, 1)
        (hist, binedges) = np.histogram(xcn, bins)
        curve7 = p7.plot(binedges,
                         hist,
                         stepMode=True,
                         fillBrush=(0, 0, 0, 255),
                         brush=pg.mkBrush('k'),
                         fillLevel=0)

        self.win.show()
Exemplo n.º 29
0
def makefigs(bounds:(int, int)=(1922, 2005), outdir:str='.'):
    "Construit et enregistre les visualisations graphiques de la fonction Rollin"
    makepath = lambda path: os.path.join(outdir, path)
    if not os.path.isdir(outdir):
        raise RuntimeError("Given output directory is not valid: " + str(outdir))
    # Build the data
    ANNEES = tuple(range(*bounds))
    NOMBRES_ROLLIN = range(1, 10)
    ROLLIN = tuple(rollin(annee) for annee in ANNEES)
    assert min(ROLLIN) == 1 and max(ROLLIN) == 9, (min(ROLLIN), max(ROLLIN))
    def evolution(nbs:[int], start:int) -> [int]:
        prev = start
        for nb in nbs:
            nb, prev = nb - prev, nb
            yield nb
    EVOLUTION = tuple(evolution(ROLLIN, rollin(bounds[0] - 1)))
    GREEN = (119,172,48)
    RED = (200,12,48)

    # Association nombre de Rollin -> années
    ANNEE_PAR_NB = {}  # nombre de rollin -> {années}
    for annee, nb_rollin in zip(ANNEES, ROLLIN):
        ANNEE_PAR_NB.setdefault(nb_rollin, []).append(annee)
    COMPTAGE_ANNEES = tuple(len(ANNEE_PAR_NB[nb]) for nb in NOMBRES_ROLLIN)

    # Simple plot de la fonction
    plot = init("Nombre de Rollin et son évolution en fonction de l'année ({}-{})".format(*bounds))
    # plot = win.addPlot(title="Plotting with symbols")
    plot.addLegend()
    plot.plot(ANNEES, ROLLIN, pen=GREEN, symbolBrush=GREEN, symbolPen='w', symbol='d', symbolSize=14, name="Nombre de Rollin")
    # Plot de l'évolution du nombre de Rollin
    plot.plot(ANNEES, EVOLUTION, pen=RED, symbolBrush=RED, symbolPen='w', symbol='t2', symbolSize=14, name="Évolution du nombre de Rollin")
    # plot.setXRange(bounds[0]-10, bounds[1]+1)
    plot.setYRange(min(EVOLUTION + ROLLIN), max(EVOLUTION + ROLLIN) + 2)
    plot.show()

    # Nombre d'années pour chaque nombre de Rollin
    win = init_base("Dénombrement des années {}-{} selon leur nombre de Rollin".format(*bounds))
    # help(pg.BarGraphItem)
    win.addItem(pg.BarGraphItem(x=NOMBRES_ROLLIN, height=COMPTAGE_ANNEES, width=0.3))
    # for nb_rollin in NOMBRES_ROLLIN:
        # win.addItem(pg.BarGraphItem(x=[nb_rollin], height=[ANNEE_PAR_NB[nb_rollin]], width=0.3))
    win.show()

    # Boxplot, pour avoir une idée de la distribution des années
    #  does not exists in pyqtgraph ; building it myself…
    win = init_base("Dénombrement des années {}-{} selon leur nombre de Rollin".format(*bounds))
    for nb_rollin in NOMBRES_ROLLIN:
        annees = ANNEE_PAR_NB[nb_rollin]
        win.plot(x=[nb_rollin], y=annees, pen=None, symbol='o', symbolBrush=pg.intColor(nb_rollin,6))
        mean, median, stdev = statistics.mean(annees), statistics.median(annees), statistics.stdev(annees)
        maxi, mini = max(annees), min(annees)
        limits_amplitude = (maxi - mini) / 2
        middle = limits_amplitude + mini
        boxes = (
            (middle, limits_amplitude*2, 0.8, 'b', 1.2),
            (mean, stdev, 0.5, 'w', 3),
            (mean, 0, 0.5, 'w', 3),
            (median, 0, 0.5, 'r', 4),
        )
        for center, amplitude, beam, color, width in boxes:
            win.addItem(pg.ErrorBarItem(x=np.array([nb_rollin]), y=np.array([center]), height=np.array([amplitude]), beam=beam, pen={'color': color, 'width': width}))
    win.show()
Exemplo n.º 30
0
    f = QtGui.QFont()
    f.setPointSize(10)
    symbol.addText(0, 0, f, label)
    br = symbol.boundingRect()
    scale = min(1. / br.width(), 1. / br.height())
    tr = QtGui.QTransform()
    tr.scale(scale, scale)
    tr.rotate(angle)
    tr.translate(-br.x() - br.width()/2., -br.y() - br.height()/2.)
    return TextSymbol(label, tr.map(symbol), 0.1 / scale)

random_str = lambda : (''.join([chr(np.random.randint(ord('A'),ord('z'))) for i in range(np.random.randint(1,5))]), np.random.randint(0, 360))

s2 = pg.ScatterPlotItem(size=10, pen=pg.mkPen('w'), pxMode=True)
pos = np.random.normal(size=(2,n), scale=1e-5)
spots = [{'pos': pos[:,i], 'data': 1, 'brush':pg.intColor(i, n), 'symbol': i%5, 'size': 5+i/10.} for i in range(n)]
s2.addPoints(spots)
spots = [{'pos': pos[:,i], 'data': 1, 'brush':pg.intColor(i, n), 'symbol': label[1], 'size': label[2]*(5+i/10.)} for (i, label) in [(i, createLabel(*random_str())) for i in range(n)]]
s2.addPoints(spots)
w2.addItem(s2)
s2.sigClicked.connect(clicked)


## 3) Spots are not transform-invariant, not identical (bottom-left).
## This is the slowest case, since all spots must be completely re-drawn
## every time because their apparent transformation may have changed.

s3 = pg.ScatterPlotItem(pxMode=False)   ## Set pxMode=False to allow spots to transform with the view
spots3 = []
for i in range(10):
    for j in range(10):
Exemplo n.º 31
0
import numpy as np

win = pg.plot()
win.setWindowTitle('pyqtgraph example: beeswarm')

data = np.random.normal(size=(4, 20))
data[0] += 5
data[1] += 7
data[2] += 5
data[3] = 10 + data[3] * 2

## Make bar graph
# bar = pg.BarGraphItem(x=range(4), height=data.mean(axis=1), width=0.5, brush=0.4)
# win.addItem(bar)

## add scatter plots on top
for i in range(4):
    xvals = pg.pseudoScatter(data[i], spacing=0.4, bidir=True) * 0.2
    win.plot(x=xvals + i, y=data[i], pen=None, symbol='o', symbolBrush=pg.intColor(i, 6, maxValue=128))

## Make error bars
err = pg.ErrorBarItem(x=np.arange(4), y=data.mean(axis=1), height=data.std(axis=1), beam=0.5,
                      pen={'color': 'w', 'width': 2})
win.addItem(err)

## Start Qt event loop unless running in interactive mode or using pyside.
if __name__ == '__main__':
    import sys

    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
        QtGui.QApplication.instance().exec_()
Exemplo n.º 32
0
        p.setPen('b', width=2)
    lastClicked = points


s1.sigClicked.connect(clicked)

## 2) Spots are transform-invariant, but not identical (top-right plot).
## In this case, drawing is as fast as 1), but there is more startup overhead
## and memory usage since each spot generates its own pre-rendered image.

s2 = pg.ScatterPlotItem(size=10, pen=pg.mkPen('w'), pxMode=True)
pos = np.random.normal(size=(2, n), scale=1e-5)
spots = [{
    'pos': pos[:, i],
    'data': 1,
    'brush': pg.intColor(i, n),
    'symbol': i % 5,
    'size': 5 + i / 10.
} for i in range(n)]
s2.addPoints(spots)
w2.addItem(s2)
s2.sigClicked.connect(clicked)

## 3) Spots are not transform-invariant, not identical (bottom-left).
## This is the slowest case, since all spots must be completely re-drawn
## every time because their apparent transformation may have changed.

s3 = pg.ScatterPlotItem(
    pxMode=False
)  ## Set pxMode=False to allow spots to transform with the view
spots3 = []
Exemplo n.º 33
0
def plot_transform(transform, scales=None, multiview=False):
    """ Display the different bands on the requested scales.

    Parameters
    ----------
    transform: WaveletTransformBase derived instance
        a wavelet decomposition.
    scales: list of int, default None
        the desired scales, if None compute at all scales.
    multiview: bool, default False
        if True use a slider to select a specific band.
    """
    # Set default scales
    scales = scales or range(transform.nb_scale)

    # Create application and tab widget
    app = pyqtgraph.mkQApp()
    tabs = QtGui.QTabWidget()
    tabs.setWindowTitle("Wavelet Transform")

    # Go through each scale
    pen = pyqtgraph.intColor(2)
    for scale in scales:

        # Create the plots for this scales with scrolling possibilities
        scroller = QtGui.QScrollArea()
        tabs.addTab(scroller, "Scale {0}".format(scale))

        # Go through each band of the current scale
        # > using multiview
        # TODO: update this code
        if multiview:
            raise NotImplementedError(
                "Multiview transform view not yet implemented.")
            window = pyqtgraph.image(numpy.asarray(transform[scale]))
            scroller.setWidget(window)
        # > using mosaic
        else:
            window = pyqtgraph.GraphicsWindow()
            scroller.setWidget(window)

            scale_data = transform[scale]
            if not isinstance(scale_data, list):
                scale_data = [scale_data]

            for subband_data in scale_data:

                # Deal with complex data
                if numpy.iscomplex(subband_data).any():
                    subband_data = numpy.abs(subband_data)
                subband_data = numpy.lib.pad(
                    subband_data, 1, "constant",
                    constant_values=subband_data.max())

                # Select viewer
                if subband_data.ndim == 1:
                    ax = window.addPlot()
                    ax.plot(subband_data, pen=pen)
                elif subband_data.ndim == 2:
                    box = window.addViewBox()
                    box.setAspectLocked(True)
                    image = pyqtgraph.ImageItem(subband_data)
                    box.addItem(image)
                else:
                    raise ValueError("This function currently support only "
                                     "1D or 2D data.")
                window.nextRow()

    # Display the tab
    tabs.show()

    # Run application
    app.exec_()
Exemplo n.º 34
0
    def __init__(self, rts, update_freq=50, z_ax='abs_pu', use_colors=False, rotating=False, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.rts = rts
        self.ps = rts.ps
        self.dt = self.rts.dt
        ps = self.ps
        self.z_ax = z_ax

        # nx.draw(G)
        self.scale = 10

        if self.z_ax == 'angle':
            self.scale_z = 10*np.ones(ps.n_bus)
            self.offset_z = 3  # *np.ones(ps.n_bus)
        elif self.z_ax == 'abs':
            self.scale_z = 10 * ps.v_n / max(ps.v_n) * 0.3
            self.offset_z = 0  # np.zeros(ps.n_bus)

        elif self.z_ax == 'abs_pu':
            self.scale_z = 10 * 0.3*(ps.v_n**0)
            self.offset_z = 0  # np.zeros(ps.n_bus)
        # elif self.z_ax == 'both':
        #     self.scale_z = 10*np.ones(ps.n_bus)
        #     self.offset_z = 12*np.ones(ps.n_bus)


        line_admittances = np.zeros(len(ps.lines), dtype=[('Y', float)])
        for i, line in enumerate(ps.lines):
            line_admittances[i] = abs(ps.read_admittance_data('line', line)[2])

        trafo_admittances = np.zeros(len(ps.transformers), dtype=[('Y', float)])
        for i, trafo in enumerate(ps.transformers):
            trafo_admittances[i] = abs(ps.read_admittance_data('transformer', trafo)[2])

        self.G = nx.MultiGraph()
        self.G.add_nodes_from(ps.buses['name'])
        # G.add_edges_from(ps.lines[['from_bus', 'to_bus']])
        # G.add_edges_from(ps.transformers[['from_bus', 'to_bus']])
        self.G.add_weighted_edges_from(
            dps_uf.combine_recarrays(ps.lines, line_admittances)[['from_bus', 'to_bus', 'Y']])
        self.G.add_weighted_edges_from(
            dps_uf.combine_recarrays(ps.transformers, trafo_admittances)[['from_bus', 'to_bus', 'Y']])

        self.grid_layout()

        self.n_edges = len(ps.lines) + len(ps.transformers)
        self.edge_from_bus = np.concatenate([dps_uf.lookup_strings(type_['from_bus'], ps.buses['name']) for type_ in [ps.lines, ps.transformers]])
        self.edge_to_bus = np.concatenate([dps_uf.lookup_strings(type_['to_bus'], ps.buses['name']) for type_ in [ps.lines, ps.transformers]])

        self.edge_x = np.vstack([self.x[self.edge_from_bus], self.x[self.edge_to_bus]]).T
        self.edge_y = np.vstack([self.y[self.edge_from_bus], self.y[self.edge_to_bus]]).T
        self.edge_z = np.vstack([self.z[self.edge_from_bus], self.z[self.edge_to_bus]]).T

        self.colors = lambda i: pg.intColor(i, hues=9, values=1, maxValue=255, minValue=150, maxHue=360, minHue=0, sat=255, alpha=255)

        self.window = gl.GLViewWidget()
        # self.window.setBackgroundColor('w')
        self.window.setWindowTitle('Grid')
        self.window.setGeometry(0, 110, 1920, 1080)
        self.window.setCameraPosition(distance=30, elevation=12)
        self.window.show()

        self.rotating = rotating

        self.gz = gl.GLGridItem()
        self.gz.translate(dx=0, dy=0, dz=-self.offset_z)
        self.window.addItem(self.gz)

        color = np.ones((ps.n_bus, 4))
        color[:, -1] = 0.5
        if use_colors:
            color[ps.gen_bus_idx, :] = np.array([self.colors(i).getRgb() for i in range(self.ps.n_gen_bus)]) / 255
        else:
            color[ps.gen_bus_idx, :] = np.array([1 / 3, 2 / 3, 1, 0.5])[None, :]

        self.points = gl.GLScatterPlotItem(
            pos=np.vstack([self.x, self.y, self.z]).T,
            color=color,
            size=15
        )

        self.edge_x_mod = np.append(self.edge_x, np.nan*np.ones((self.n_edges, 1)), axis=1)
        self.edge_y_mod = np.append(self.edge_y, np.nan*np.ones((self.n_edges, 1)), axis=1)
        self.edge_z_mod = np.append(self.edge_z, np.nan*np.ones((self.n_edges, 1)), axis=1)
        # line_x_mod = line_x
        # line_y_mod = line_y
        edge_pos = np.vstack([self.edge_x_mod.flatten(), self.edge_y_mod.flatten(), self.edge_z_mod.flatten()]).T
        line_color = np.ones((self.n_edges, 4))
        line_color[:, -1] = 0.5
        line_color[len(ps.lines):, :] = np.array([1 / 3, 2 / 3, 1, 0.5])[None, :]
        # self.scale_branch_flows = 4
        line_widths = np.ones((self.n_edges, 4))
        self.lines = gl.GLLinePlotItem(pos=edge_pos, color=np.repeat(line_color, 3, axis=0), antialias=True, width=2)

        self.window.addItem(self.points)
        self.window.addItem(self.lines)

        # self.axis = gl.GLAxisItem()

        # self.graphWidget.show()

        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.update)
        self.timer.start(1000//update_freq)
        self.t_prev = time.time()
Exemplo n.º 35
0
for index in range(1, len(sPi)):  #   Build the plot series
    if index == 1:
        print('Decimal Point skipped')
    else:
        x.append(float(xDict[int(sPi[index])]) + x[index - 2])
        y.append(float(yDict[int(sPi[index])]) + y[index - 2])

# create plot

pg.setConfigOption('background', 'w')
pg.intColor(index,
            hues=9,
            values=1,
            maxValue=255,
            minValue=150,
            maxHue=360,
            minHue=0,
            sat=255,
            alpha=255)
print()
plt = pg.plot(x,
              y,
              title=theTitle,
              pen=pg.mkPen(cosmetic=True, width=1.2,
                           color='b'))  #, symbol='.')
plt.showGrid(x=True, y=True)
plt.hideAxis('left')
plt.hideAxis('bottom')

## Start Qt event loop.
Exemplo n.º 36
0
    def _update_plots(self):
        sweeps = self.sweeps
        self.current_event_set = None
        self.event_table.clear()
        
        # clear all plots
        self.pre_plot.clear()
        self.post_plot.clear()

        pre = self.params['pre']
        post = self.params['post']
        
        # If there are no selected sweeps or channels have not been set, return
        if len(sweeps) == 0 or pre == post or pre not in self.channels or post not in self.channels:
            return

        pre_mode = sweeps[0][pre].clamp_mode
        post_mode = sweeps[0][post].clamp_mode
        for ch, mode, plot in [(pre, pre_mode, self.pre_plot), (post, post_mode, self.post_plot)]:
            units = 'A' if mode == 'vc' else 'V'
            plot.setLabels(left=("Channel %d" % ch, units), bottom=("Time", 's'))
        
        # Iterate over selected channels of all sweeps, plotting traces one at a time
        # Collect information about pulses and spikes
        pulses = []
        spikes = []
        post_traces = []
        for i,sweep in enumerate(sweeps):
            pre_trace = sweep[pre]['primary']
            post_trace = sweep[post]['primary']
            
            # Detect pulse times
            stim = sweep[pre]['command'].data
            sdiff = np.diff(stim)
            on_times = np.argwhere(sdiff > 0)[1:, 0]  # 1: skips test pulse
            off_times = np.argwhere(sdiff < 0)[1:, 0]
            pulses.append(on_times)

            # filter data
            post_filt = self.artifact_remover.process(post_trace, list(on_times) + list(off_times))
            post_filt = self.baseline_remover.process(post_filt)
            post_filt = self.filter.process(post_filt)
            post_traces.append(post_filt)
            
            # plot raw data
            color = pg.intColor(i, hues=len(sweeps)*1.3, sat=128)
            color.setAlpha(128)
            for trace, plot in [(pre_trace, self.pre_plot), (post_filt, self.post_plot)]:
                plot.plot(trace.time_values, trace.data, pen=color, antialias=False)

            # detect spike times
            spike_times = []
            spike_info = []
            for on, off in zip(on_times, off_times):
                spikes = detect_evoked_spikes(sweep[pre], [on, off])
                spike_info.append(spikes)
                for spike in spikes:
                    if spike['max_slope_time'] is None:
                        continue
                    spike_times.append(spike['max_slope_time'])
            spikes.append(spike_info)
                    
            dt = pre_trace.dt
            vticks = pg.VTickGroup(spike_times, yrange=[0.0, 0.2], pen=color)
            self.pre_plot.addItem(vticks)

        # Iterate over spikes, plotting average response
        all_responses = []
        avg_responses = []
        fits = []
        fit = None
        
        npulses = max(map(len, pulses))
        self.response_plots.clear()
        self.response_plots.set_shape(1, npulses+1) # 1 extra for global average
        self.response_plots.setYLink(self.response_plots[0,0])
        for i in range(1, npulses+1):
            self.response_plots[0,i].hideAxis('left')
        units = 'A' if post_mode == 'vc' else 'V'
        self.response_plots[0, 0].setLabels(left=("Averaged events (Channel %d)" % post, units))
        
        fit_pen = {'color':(30, 30, 255), 'width':2, 'dash': [1, 1]}
        for i in range(npulses):
            # get the chunk of each sweep between spikes
            responses = []
            all_responses.append(responses)
            for j, sweep in enumerate(sweeps):
                # get the current spike
                if i >= len(spikes[j]):
                    continue
                spike = spikes[j][i]
                if spike is None:
                    continue
                
                # find next spike
                next_spike = None
                for sp in spikes[j][i+1:]:
                    if sp is not None:
                        next_spike = sp
                        break
                    
                # determine time range for response
                max_len = int(40e-3 / dt)  # don't take more than 50ms for any response
                start = spike['rise_index']
                if next_spike is not None:
                    stop = min(start + max_len, next_spike['rise_index'])
                else:
                    stop = start + max_len
                    
                # collect data from this trace
                trace = post_traces[j]
                d = trace.data[start:stop].copy()
                responses.append(d)

            if len(responses) == 0:
                continue
                
            # extend all responses to the same length and take nanmean
            avg = ragged_mean(responses, method='clip')
            avg -= float_mode(avg[:int(1e-3/dt)])
            avg_responses.append(avg)
            
            # plot average response for this pulse
            start = np.median([sp[i]['rise_index'] for sp in spikes if sp[i] is not None]) * dt
            t = np.arange(len(avg)) * dt
            self.response_plots[0,i].plot(t, avg, pen='w', antialias=True)

            # fit!
            fit = self.fit_psp(avg, t, dt, post_mode)
            fits.append(fit)
            
            # let the user mess with this fit
            curve = self.response_plots[0,i].plot(t, fit.eval(), pen=fit_pen, antialias=True).curve
            curve.setClickable(True)
            curve.fit = fit
            curve.sigClicked.connect(self.fit_curve_clicked)
            
        # display global average
        global_avg = ragged_mean(avg_responses, method='clip')
        t = np.arange(len(global_avg)) * dt
        self.response_plots[0,-1].plot(t, global_avg, pen='w', antialias=True)
        global_fit = self.fit_psp(global_avg, t, dt, post_mode)
        self.response_plots[0,-1].plot(t, global_fit.eval(), pen=fit_pen, antialias=True)
            
        # display fit parameters in table
        events = []
        for i,f in enumerate(fits + [global_fit]):
            if f is None:
                continue
            if i >= len(fits):
                vals = OrderedDict([('id', 'avg'), ('spike_time', np.nan), ('spike_stdev', np.nan)])
            else:
                spt = [s[i]['peak_index'] * dt for s in spikes if s[i] is not None]
                vals = OrderedDict([('id', i), ('spike_time', np.mean(spt)), ('spike_stdev', np.std(spt))])
            vals.update(OrderedDict([(k,f.best_values[k]) for k in f.params.keys()]))
            events.append(vals)
            
        self.current_event_set = (pre, post, events, sweeps)
        self.event_set_list.setCurrentRow(0)
        self.event_set_selected()
Exemplo n.º 37
0
    def analyze(self):
        if self.plotlist != [[], [], [], [], []]:
            for x in self.plotlist:
                self.p1.getRoiPlot().removeItem(x)
                self.plotlist = [[], [], [], [], []]

        dntpnames = ["dCTP", "dATP", "dGTP", "dTTP"]
        dntps = [[], [], [], []]
        zpro = [[], [], [], []]
        n = len(dntps)

        lz, lx, ly = self.stack.shape
        seq = self.stack.reshape(lz, lx * ly)

        for i, x in enumerate(dntpnames):
            fn = [
                filename for filename in os.listdir(self.direc)
                if filename.startswith(x) and filename.endswith('.h5')
            ]
            hfile = h5py.File(self.direc + os.sep + fn[-1])
            #            print self.direc + os.sep+ fn[-1]
            dntps[i] = np.array(hfile["images"]).astype(float)
            if self.roip1 != []:
                dntps[i] = dntps[i][:, self.roip1[1]:self.roip2[1] + 1,
                                    self.roip1[0]:self.roip2[0] + 1]

#            if self.filtertype != []:

            dntps[i] = dntps[i][100:900]
            dntps[i] -= np.mean(dntps[i])
            dntps[i] = (dntps[i] / dntps[i].std())
            zpro[i] = np.median(dntps[i], 0)

        zpro[0] -= np.mean(zpro[0])
        zpro[1] -= np.mean(zpro[1])
        zpro[1] -= np.mean(zpro[2])
        zpro[2] -= np.mean(zpro[3])

        cscore = ascore = gscore = tscore = np.array(())
        scores = [cscore, ascore, gscore, tscore]
        total = []

        for i, x in enumerate(scores):
            x = np.dot(seq, zpro[i].ravel())
            x = (x - x.mean()) / x.std()
            if i == 0:
                total = x**2
            else:
                total = total + x**2

            color = pg.intColor(i, hues=4)
            scores[i] = x

            self.plotlist[i] = self.p1.getRoiPlot().plot(x - np.median(x),
                                                         pen=color)
        self.p1.getRoiPlot().setRange(yRange=[-4, 10])

        scores = pd.DataFrame(np.transpose(scores))
        tot = abs(scores[0] + scores[1] - scores[2] - scores[3])

        predictedseq = np.zeros(len(tot))
        predictedseq[np.array(scores.idxmax(axis=1) == 0)] = 1
        predictedseq[np.array(scores.idxmax(axis=1) == 1)] = 2
        predictedseq[np.array(scores.idxmax(axis=1) == 2)] = 3
        predictedseq[np.array(scores.idxmax(axis=1) == 3)] = 4

        predictedseq[np.array(
            tot < np.median(predictedseq) + np.std(predictedseq))] = 0

        self.plotlist[4] = self.p1.getRoiPlot().plot(predictedseq,
                                                     pen=pg.mkPen('w',
                                                                  width=3))
Exemplo n.º 38
0
expts = ExperimentList(cache='expts_cache.pkl')

dates = [(e.date - expts[0].date).days for e in expts]
ud = list(np.unique(dates))
days = [ud.index(d) for d in dates]

probed = np.array([e.n_connections_probed for e in expts])
found = np.array([e.n_connections for e in expts])

ctypes = [tuple(exp.cre_types) for exp in expts]
n_ctypes = len(set(ctypes))
ctype_colors = {}
for exp in expts:
    ct = tuple(exp.cre_types)
    color = pg.intColor(len(ctype_colors), hues=6, values=2, minValue=100)
    ctype_colors.setdefault(ct, pg.mkBrush(color))

expt_colors = [ctype_colors[ct] for ct in ctypes]

p1 = pg.plot(
    dates,
    np.cumsum(probed),
    symbol='o',
    symbolBrush=expt_colors,
    symbolPen=None,
    title="Connections probed over time (including no-experiment days)")

p1 = pg.plot(days,
             np.cumsum(probed),
             symbol='o',
Exemplo n.º 39
0
    def myLayout(self):
        self.layout = QtGui.QVBoxLayout(self)  #the whole window, main layout
        self.inputLayout = QtGui.QGridLayout()
        self.plotLayout = QtGui.QGridLayout()
        self.layout.addLayout(self.inputLayout)
        self.layout.addLayout(self.plotLayout)

        self.m_button = QtGui.QSpinBox()
        self.m_button.setRange(-50, 50)
        self.m_button.setValue(0)
        self.inputLayout.addWidget(self.m_button, 1, 0)
        self.inputLayout.addWidget(QtGui.QLabel("Zernike m"), 0, 0)

        self.n_button = QtGui.QSpinBox()
        self.n_button.setValue(2)
        self.inputLayout.addWidget(self.n_button, 1, 1)
        self.inputLayout.addWidget(QtGui.QLabel("Zernike n"), 0, 1)

        self.m_button.editingFinished.connect(self.worker_calc_zernike)
        self.n_button.editingFinished.connect(self.worker_calc_zernike)

        self.scatterPlotItem1 = pg.ScatterPlotItem(size=30,
                                                   pen=pg.mkPen(None),
                                                   brush=pg.intColor(2))
        ah = 0.5
        hh = ah * np.sqrt(3) / 2.0
        hpoint1 = QtCore.QPointF(0, -ah)
        hpoint2 = QtCore.QPointF(hh, -ah / 2)
        hpoint3 = QtCore.QPointF(hh, ah / 2)
        hpoint4 = QtCore.QPointF(0, ah)
        hpoint5 = QtCore.QPointF(-hh, ah / 2)
        hpoint6 = QtCore.QPointF(-hh, -ah / 2)
        hexagonShape = QtGui.QPolygonF(
            [hpoint1, hpoint2, hpoint3, hpoint4, hpoint5, hpoint6])
        spotShape = QtGui.QPainterPath()
        spotShape.addPolygon(hexagonShape)
        #self.scatterPlotItem1.Symbols['h'] = hexagonShape
        self.scatterPlotItem1.setData(symbol=spotShape)

        self.graphWindow1 = pg.GraphicsLayoutWidget()
        self.graphWindow2 = pg.GraphicsLayoutWidget()
        self.graphWindow3 = pg.GraphicsLayoutWidget()
        self.graphWindow4 = pg.GraphicsLayoutWidget()
        #self.graphWindow.setSizePolicy(QtGui.QSizePolicy.Expanding,QtGui.QSizePolicy.Expanding)
        self.plotLayout.addWidget(self.graphWindow1, 0, 0)
        self.plotLayout.addWidget(self.graphWindow2, 0, 1)
        self.plotLayout.addWidget(self.graphWindow3, 1, 0)
        self.plotLayout.addWidget(self.graphWindow4, 1, 1)

        view1 = self.graphWindow1.addViewBox()
        view1.setAspectLocked(True)
        self.img1 = pg.ImageItem(border='w')
        #self.scatterPlotItem1.addPoints(self.electrodeCoordinates[:,0]*self.x_points/2.0/self.laserSpotSizeScale+self.x_points/2, self.electrodeCoordinates[:,1]*self.y_points/2.0/self.laserSpotSizeScale+self.y_points/2)
        view1.addItem(self.img1)
        view1.addItem(self.scatterPlotItem1)

        view2 = self.graphWindow2.addViewBox()
        view2.setAspectLocked(True)
        self.img2 = pg.ImageItem(border='w')
        self.scatterPlotItem1.addPoints(
            self.electrodeCoordinates[:, 0] * self.x_points /
            self.laserSpotSizeScale + self.x_points / 2,
            self.electrodeCoordinates[:, 1] * self.y_points /
            self.laserSpotSizeScale + self.y_points / 2)
        view2.addItem(self.img2)

        view3 = self.graphWindow3.addViewBox()
        view3.setAspectLocked(True)
        self.img3 = pg.ImageItem(border='w')
        self.scatterPlotItem1.addPoints(
            self.electrodeCoordinates[:, 0] * self.x_points /
            self.laserSpotSizeScale + self.x_points / 2,
            self.electrodeCoordinates[:, 1] * self.y_points /
            self.laserSpotSizeScale + self.y_points / 2)
        view3.addItem(self.img3)

        view4 = self.graphWindow4.addViewBox()
        view4.setAspectLocked(True)
        self.img4 = pg.ImageItem(border='w')
        self.scatterPlotItem1.addPoints(
            self.electrodeCoordinates[:, 0] * self.x_points /
            self.laserSpotSizeScale + self.x_points / 2,
            self.electrodeCoordinates[:, 1] * self.y_points /
            self.laserSpotSizeScale + self.y_points / 2)
        view4.addItem(self.img4)

        #
        #self.spots = QtGui.QGraphicsWidget()
        #self.spots.data(0)
        #self.graphWindow.addItem(self.spots,{'pos': self.electrodeCoordinates[1], 'data': 1, 'brush':pg.intColor(2), 'symbol': 'o', 'size': 50})

        #=======================================================================
        # spots = {'pos': self.electrodeCoordinates[1], 'data': 1, 'brush':pg.intColor(2), 'symbol': 'o', 'size': 50}
        # #for i in range(0,3):
        # #    spots.append({'pos': self.electrodeCoordinates[i], 'data': 1, 'brush':pg.intColor(2), 'symbol': 'o', 'size': 50})
        #
        #=======================================================================

        self.calc_zernike()
    def show_pg(self, cell=None, rmponly=False):
        print("rmpvalue : ")
        print(rmponly)
        """
        Plot results from run_iv()
        Using pyqtgraph.
        
        Parameters
        ----------
        cell : cell object (default: None)
        
        """
        
        #
        # Generate figure with subplots
        # note that some of the plot windows are not used... maybe later
        #
        app = pg.mkQApp()
        win = pg.GraphicsWindow()  #'%s  %s (%s)' % (cell.status['name'], cell.status['modelType'], cell.status['species']))
        self.win = win
        win.resize(1000, 800)
        Vplot = win.addPlot(labels={'left': 'Vm (mV)', 'bottom': 'Time (ms)'})
        rightGrid = win.addLayout(rowspan=2)
        win.nextRow()
        PostCellPlot = win.addPlot(labels={'left': 'Ipost (nA)', 'bottom': 'Time (ms)'})
        win.nextRow()
        Iplot = win.addPlot(labels={'left': 'Iinj (nA)', 'bottom': 'Time (ms)'})
        
        # right side:
        IVplot = rightGrid.addPlot(labels={'left': 'Vm (mV)', 'bottom': 'Icmd (nA)'})
        IVplot.showGrid(x=True, y=True)
        rightGrid.nextRow()
        spikePlot = rightGrid.addPlot(labels={'left': 'Iinj (nA)', 'bottom': 'Spike times (ms)'})
        rightGrid.nextRow()
        FIplot = rightGrid.addPlot(labels={'left': 'Spike count', 'bottom': 'Iinj (nA)'})
        
        win.ci.layout.setRowStretchFactor(0, 10)
        win.ci.layout.setRowStretchFactor(1, 5)

        #
        # Plot the simulation results
        #
        Vm = self.sgc_voltage_traces
        Iinj = self.current_traces
        # Icmd = self.current_cmd
        DVm = self.axon_voltage_traces
        post = self.post_cell_current_traces
        calyxca = self.calyx_ca
        t = self.time_values
        steps = len(Iinj)
        # plot I, V traces
        colors = [(i, steps*3./2.) for i in range(steps)]
        
        # plot all the stimuli
        for i in range(steps):
            Vplot.plot(t, Vm[i], pen='w')
            #Iplot.plot(t, Iinj[i], pen=colors[i])  # that was the current pulses
            Iplot.plot(t[:len(calyxca[i])], calyxca[i], pen='y') # calcium is more interesting
            PostCellPlot.plot(t, post[i], pen=colors[i])
            if len(DVm) == 0:
                continue
            nnodes = len(DVm[i])
            axcolors = [pg.intColor(k, nnodes) for k in range(nnodes)]
            for j in range(len(DVm[i])):  # for each site
                if j in range(nnodes): #[1, nnodes-1]:
                    ilen = len(DVm[i][j])
                    Vplot.plot(t[:ilen], DVm[i][j], pen=axcolors[j])
            trange = [0,140]
            xmin = trange[0]
            xmax = trange[1]
            Vplot.setXRange(xmin, xmax)
            print("rescaled voltage")
            Iplot.setXRange(xmin, xmax)
            PostCellPlot.setXRange(xmin, xmax)
        Iplot.setXLink(Vplot)
        PostCellPlot.setXLink(Vplot)
        if rmponly:
            print("In this condition")
            return
Exemplo n.º 41
0
data[0] += 5
data[1] += 7
data[2] += 5
data[3] = 10 + data[3] * 2

## Make bar graph
#bar = pg.BarGraphItem(x=range(4), height=data.mean(axis=1), width=0.5, brush=0.4)
#win.addItem(bar)

## add scatter plots on top
for i in range(4):
    xvals = pg.pseudoScatter(data[i], spacing=0.4, bidir=True) * 0.2
    win.plot(x=xvals + i,
             y=data[i],
             pen=None,
             symbol='o',
             symbolBrush=pg.intColor(i, 6, maxValue=128))

## Make error bars
err = pg.ErrorBarItem(x=np.arange(4),
                      y=data.mean(axis=1),
                      height=data.std(axis=1),
                      beam=0.5,
                      pen={
                          'color': 'w',
                          'width': 2
                      })
#win.addItem(err)

## Start Qt event loop unless running in interactive mode or using pyside.
Exemplo n.º 42
0
 def get_color(i, j, data):
     x = data.iloc[i][data.columns[j]]
     return pg.intColor(int((x + 1) / 2 * 1000), 1000)
Exemplo n.º 43
0
    def __init__(self,
                 settings: Settings,
                 data_model: DataModel,
                 parent: Optional[QWidget] = None,
                 *args: Any) -> None:
        super().__init__(parent, *args)

        self.setObjectName('plot_dialog')

        self.settings: Settings = settings
        self.setModal(True)
        self.setWindowTitle(self.tr('Plot'))
        if parent is not None:
            self.setWindowIcon(parent.windowIcon())

        layout: QHBoxLayout = QHBoxLayout(self)

        controls_panel: QWidget = QWidget(self)
        layout.addWidget(controls_panel)
        controls_layout: QFormLayout = QFormLayout(controls_panel)

        plot: pg.PlotWidget = pg.PlotWidget(self)
        canvas: pg.PlotItem = plot.getPlotItem()
        canvas.setAxisItems({'bottom': pg.DateAxisItem()})
        layout.addWidget(plot)
        layout.setStretch(0, 0)
        cursor_balloon: pg.TextItem = pg.TextItem()
        plot.addItem(cursor_balloon, True)  # ignore bounds

        def on_mouse_moved(event: Tuple[QPointF]) -> None:
            pos: QPointF = event[0]
            if plot.sceneBoundingRect().contains(pos):
                point: QPointF = canvas.vb.mapSceneToView(pos)
                if plot.visibleRange().contains(point):
                    cursor_balloon.setPos(point)
                    cursor_balloon.setText(
                        f'{datetime.fromtimestamp(round(point.x()))}\n{point.y()}'
                    )
                    balloon_border: QRectF = cursor_balloon.boundingRect()
                    sx: float
                    sy: float
                    sx, sy = canvas.vb.viewPixelSize()
                    balloon_width: float = balloon_border.width() * sx
                    balloon_height: float = balloon_border.height() * sy
                    anchor_x: float = 0.0 if point.x() - plot.visibleRange(
                    ).left() < balloon_width else 1.0
                    anchor_y: float = 0.0 if plot.visibleRange().bottom(
                    ) - point.y() < balloon_height else 1.0
                    cursor_balloon.setAnchor((anchor_x, anchor_y))
                    cursor_balloon.setVisible(True)
                else:
                    cursor_balloon.setVisible(False)
            else:
                cursor_balloon.setVisible(False)

        self._mouse_moved_signal_proxy: pg.SignalProxy = pg.SignalProxy(
            plot.scene().sigMouseMoved, rateLimit=10, slot=on_mouse_moved)

        header: str
        column: np.ndarray
        visibility: bool
        self.lines: List[pg.PlotDataItem] = []
        self.color_buttons: List[pg.ColorButton] = []
        visible_columns_count: int = 0
        visible_headers: List[str] = []
        for header, column, visibility in zip(
                data_model.header, data_model.all_data,
                self.settings.check_items_values):
            if not (visibility and (self.settings.show_all_zero_columns
                                    or not np.alltrue((column == 0.0) | np.isnan(column)))) \
                    or header.endswith(('(s)', '(sec)', '(secs)')):
                continue
            else:
                visible_columns_count += 1
                visible_headers.append(header)

        def set_line_color(sender: pg.ColorButton) -> None:
            index: int = self.color_buttons.index(sender)
            self.lines[index].setPen(sender.color())
            self.settings.line_colors[visible_headers[index]] = sender.color()

        for header, column, visibility in zip(
                data_model.header, data_model.all_data,
                self.settings.check_items_values):
            if not (visibility and (self.settings.show_all_zero_columns
                                    or not np.alltrue((column == 0.0) | np.isnan(column)))) \
                    or header.endswith(('(s)', '(sec)', '(secs)')):
                continue
            color: QColor = self.settings.line_colors.get(
                header, pg.intColor(len(self.lines),
                                    hues=visible_columns_count))
            self.color_buttons.append(pg.ColorButton(controls_panel, color))
            controls_layout.addRow(header, self.color_buttons[-1])
            self.lines.append(
                canvas.plot(np.column_stack((data_model.all_data[0], column)),
                            name=header,
                            pen=color))
            self.color_buttons[-1].sigColorChanged.connect(set_line_color)

        self.settings.beginGroup('plot')
        window_settings: bytes = self.settings.value('geometry')
        if window_settings is not None:
            self.restoreGeometry(window_settings)
        self.settings.endGroup()
Exemplo n.º 44
0
    for p in lastClicked:
        p.resetPen()
    for p in points:
        print('Pos: ', p.pos())
        p.setPen('b', width=2)
    lastClicked = points


n = 20
w = view.addViewBox()
s = pg.ScatterPlotItem(size=10, pen=pg.mkPen('w'))
pos = np.linspace(0, 100, n)
spots = [{
    'pos': (0, pos[i]),
    'data': 1,
    'brush': pg.intColor(i),
    'symbol': 1,
    'size': 10
} for i in range(n)]
s.addPoints(spots)
w.addItem(s)
s.sigClicked.connect(clicked)

if __name__ == '__main__':
    QtGui.QApplication.instance().exec_()

import pyqtgraph as pg
import pyqtgraph.opengl


class MyView(pg.opengl.GLViewWidget):
Exemplo n.º 45
0
    for p in points:
        p.setPen('b', width=2)
    lastClicked = points


s1.sigClicked.connect(clicked)


# 2) Spots are transform-invariant, but not identical (top-right plot).
# In this case, drawing is almsot as fast as 1), but there is more startup
# overhead and memory usage since each spot generates its own pre-rendered
# image.

s2 = pg.ScatterPlotItem(size=10, pen=pg.mkPen('w'), pxMode=True)
pos = np.random.normal(size=(2, n), scale=1e-5)
spots = [{'pos': pos[:, i], 'data': 1, 'brush':pg.intColor(
    i, n), 'symbol': i % 5, 'size': 5+i/10.} for i in range(n)]
s2.addPoints(spots)
w2.addItem(s2)
s2.sigClicked.connect(clicked)


# 3) Spots are not transform-invariant, not identical (bottom-left).
# This is the slowest case, since all spots must be completely re-drawn
# every time because their apparent transformation may have changed.

# Set pxMode=False to allow spots to transform with the view
s3 = pg.ScatterPlotItem(pxMode=False)
spots3 = []
for i in range(10):
    for j in range(10):
        spots3.append({'pos': (1e-6*i, 1e-6*j), 'size': 1e-6,
Exemplo n.º 46
0
    def __init__(self, model_runner):
        QtGui.QWidget.__init__(self)
        self.layout = QtGui.QGridLayout()
        self.layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(self.layout)
        
        self.slicer = NDSlicer(model_runner.param_space.axes())
        self.slicer.selection_changed.connect(self.selection_changed)
        self.layout.addWidget(self.slicer)
        
        # set up a few default 2D slicer views
        v1 = self.slicer.params.child('2D views').addNew()
        v1['axis 0'] = 'n_release_sites'
        v1['axis 1'] = 'base_release_probability'
        v2 = self.slicer.params.child('2D views').addNew()
        v2['axis 0'] = 'depression_amount'
        v2['axis 1'] = 'base_release_probability'
        self.slicer.dockarea.moveDock(v2.viewer.dock, 'bottom', v1.viewer.dock)
        v3 = self.slicer.params.child('2D views').addNew()
        v3['axis 0'] = 'depression_tau'
        v3['axis 1'] = 'base_release_probability'
        v4 = self.slicer.params.child('2D views').addNew()
        v4['axis 0'] = 'facilitation_amount'
        v4['axis 1'] = 'base_release_probability'
        self.slicer.dockarea.moveDock(v4.viewer.dock, 'bottom', v3.viewer.dock)

        self.result_widget = ModelSingleResultWidget()
        self.result_dock = pg.dockarea.Dock('model results')
        self.result_dock.addWidget(self.result_widget)
        self.slicer.dockarea.addDock(self.result_dock, 'bottom')

        # turn on max projection for all parameters by default
        for ch in self.slicer.params.child('max project'):
            if ch.name() == 'synapse':
                continue
            ch.setValue(True)
        
        self.model_runner = model_runner
        self.param_space = model_runner.param_space
        
        # result_img = np.zeros(self.param_space.result.shape)
        # for ind in np.ndindex(result_img.shape):
        #     result_img[ind] = self.param_space.result[ind].likelihood
        result_img = self.param_space.result['likelihood']
        self.slicer.set_data(result_img)
        self.results = result_img
        
        # select best result
        best = np.unravel_index(np.argmax(result_img), result_img.shape)
        self.select_result(best)

        max_like = self.results.max()
        
        # if results are combined across synapses, set up colors
        if 'synapse' in self.param_space.params:
            self.slicer.params['color axis', 'axis'] = 'synapse'
            syn_axis = list(self.param_space.params.keys()).index('synapse')
            max_img = np.array([result_img.take(i, axis=syn_axis).max() for i in range(result_img.shape[syn_axis])])
            max_like = max_img.min()
            max_img = max_img.min() / max_img
            syns = self.param_space.params['synapse']
            for i in syns:
                c = pg.colorTuple(pg.intColor(i, len(syns)*1.2))
                c = pg.mkColor(c[0]*max_img[i], c[1]*max_img[i], c[2]*max_img[i])
                self.slicer.params['color axis', 'colors', str(i)] = c
            
        # set histogram range
        self.slicer.histlut.setLevels(max_like * 0.85, max_like)
 def _get_color(self, index):
     ''' Returns incremental plot colors based on index '''
     return pg.intColor(index, minValue=self.plot_min_value, maxValue=self.plot_max_value,
                         hues=self.distinct_plot_hues, minHue=self.plot_min_hue, maxHue=self.plot_max_hue)
def makeMultiplePlots():
##    if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):
##        QtGui.QApplication.instance().exec_()
    app = QtGui.QApplication([])
    mw = QtGui.QMainWindow()
    mw.resize(800,800)
    view = pg.GraphicsLayoutWidget()  ## GraphicsView with GraphicsLayout inserted by default
    mw.setCentralWidget(view)
    mw.show()
    mw.setWindowTitle('pyqtgraph example: ScatterPlot')

## create four areas to add plots
    w1 = view.addPlot()
    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
    s1.sigClicked.connect(clicked)



## 2) Spots are transform-invariant, but not identical (top-right plot). 
## In this case, drawing is as fast as 1), but there is more startup overhead
## and memory usage since each spot generates its own pre-rendered image.

    s2 = pg.ScatterPlotItem(size=10, pen=pg.mkPen('w'), pxMode=True)
    pos = np.random.normal(size=(2,n), scale=1e-5)
    spots = [{'pos': pos[:,i], 'data': 1, 'brush':pg.intColor(i, n), 'symbol': i%5, 'size': 5+i/10.} for i in range(n)]
    s2.addPoints(spots)
    w2.addItem(s2)
    s2.sigClicked.connect(clicked)


## 3) Spots are not transform-invariant, not identical (bottom-left). 
## This is the slowest case, since all spots must be completely re-drawn 
## every time because their apparent transformation may have changed.

    s3 = pg.ScatterPlotItem(pxMode=False)   ## Set pxMode=False to allow spots to transform with the view
    spots3 = []
    for i in range(10):
        for j in range(10):
            spots3.append({'pos': (1e-6*i, 1e-6*j), 'size': 1e-6, 'pen': {'color': 'w', 'width': 2}, 'brush':pg.intColor(i*10+j, 100)})
    s3.addPoints(spots3)
    w3.addItem(s3)
    s3.sigClicked.connect(clicked)


## Test performance of large scatterplots

    s4 = pg.ScatterPlotItem(size=10, pen=pg.mkPen(None), brush=pg.mkBrush(255, 255, 255, 20))
    pos = np.random.normal(size=(2,10000), scale=1e-9)
    s4.addPoints(x=pos[0], y=pos[1])
    w4.addItem(s4)
    s4.sigClicked.connect(clicked)
Exemplo n.º 49
0
    def setup(self):

        self.has_turbo = 'tc110_turbo' in self.app.hardware

        if self.has_turbo:
            self.turbo_names = []
            for name in ['prep', 'ion', 'nano']:
                for x in ['speed', 'power', 'temp']:
                    self.turbo_names.append(name + "_" + x)

        self.settings.New('delta_t',
                          dtype=float,
                          unit='s',
                          vmin=0.0,
                          initial=1.0)
        self.settings.New('save_h5', dtype=bool, initial=True)

        #display
        self.settings.New('show_last', dtype=int, initial=-1)

        self.names = names = ('Prep', 'Nano')
        for name in self.names:
            self.settings.New(name + "_pressure",
                              dtype=float,
                              ro=True,
                              si=True,
                              unit="Bar")
        #self.settings.New('start_time', dtype=str, ro=True, initial = datestring())
        self.settings.New('ADC_channels', dtype=str, initial='9215A/ai0:1')
        self.settings.New('TC_channels', dtype=str, initial='cDAQ1-9211/ai0:1')

        #setup gui
        self.ui = QtWidgets.QWidget()
        self.layout = QtWidgets.QHBoxLayout()
        self.ui.setLayout(self.layout)
        self.control_widget = QtWidgets.QGroupBox(self.name)
        self.layout.addWidget(self.control_widget, stretch=0)
        self.control_widget.setLayout(QtWidgets.QVBoxLayout())

        self.start_button = QtWidgets.QPushButton("Start")
        self.control_widget.layout().addWidget(self.start_button)
        self.stop_button = QtWidgets.QPushButton("Stop")
        self.control_widget.layout().addWidget(self.stop_button)

        self.start_button.clicked.connect(self.start)
        self.stop_button.clicked.connect(self.interrupt)

        self.control_widget.layout().addWidget(\
            self.settings.New_UI(exclude=['activation','progress','profile']))

        self.control_widget.layout().addWidget(\
            self.app.settings.New_UI())

        self.graph_layout = pg.GraphicsLayoutWidget(border=(100, 100, 100))
        self.layout.addWidget(self.graph_layout, stretch=1)

        self.ui.show()
        self.ui.setWindowTitle("auger_pressure_history")

        self.NUM_CHANS = 2

        self.TC_CHAN_NAMES = ['oven_air', 'vac_system']
        self.TC_CHANS = 2

        self.plots = []

        #ion gauge pressure display
        axis = DateAxis(orientation='bottom')
        self.pressure_plot = plot = self.graph_layout.addPlot(
            title="Pressure", axisItems={'bottom': axis})
        plot.setLogMode(y=True)
        plot.setYRange(-11, -6)
        plot.showGrid(y=True, x=True, alpha=1.0)
        plot.addLegend()

        self.plots.append(plot)

        self.pressure_plot_lines = []
        for i in range(self.NUM_CHANS):
            color = pg.intColor(i)
            plot_line = self.pressure_plot.plot(pen=pg.mkPen(color, width=4),
                                                name=names[i],
                                                autoDownsample=True)
            self.pressure_plot_lines.append(plot_line)
        self.graph_layout.nextRow()

        #turbo status display
        self.turbo_plot = self.graph_layout.addPlot(title="Turbo",
                                                    axisItems={'bottom': axis})
        self.turbo_plot.showGrid(y=True, x=True, alpha=1.0)
        self.turbo_plot.addLegend()
        self.turbo_plot_lines = dict()

        for name in self.turbo_names:
            if 'prep' in name:
                color = 'r'
            elif 'ion' in name:
                color = 'y'
            else:
                color = 'w'
            if 'speed' in name:
                width = 4
                style = 1
            elif 'power' in name:
                style = 2
                width = 2
            else:
                style = style = 3
                width = 1

            self.turbo_plot_lines[name] = self.turbo_plot.plot(
                pen=pg.mkPen(color=color, width=width),
                name=name,
                autoDownsample=True)
Exemplo n.º 50
0
    def __init__(self,filename,env,parent=None):
         super(overview,self).__init__(parent)
         pg.setConfigOption('background', 'w')
         pg.setConfigOption('foreground', 'k')
         self.fileName=filename
         self.setWindowTitle("Overview Signal")
         self.showMaximized()
         self.env=env
         p1=self.addPlot(title='Current Big coils')
         self.nextRow()
         p2=self.addPlot(title='Pressure')
         self.nextRow()
         p3=self.addPlot(title='Helicon power')         
         self.nextRow()
         p4=self.addPlot(title='ICRF power')      
         self.nextRow()
         p5=self.addPlot(title='Density Langmuir probe')         
         self.nextRow()
         p6=self.addPlot(title='Amplitude B-dot probes')         
         self.nextRow()
         p7=self.addPlot(title='Phase B-dot probes')         
         indexColor=0
         for x in self.fileName:
             try:
                 timeCoils,dataCoils,sampling=readHdf5.getData(x,'S7/Big_coil_I [A]',env)
             except:
                 pass

             try:
                 timeP,dataP,sampling=readHdf5.getData(x,'S7/vacuum [mbar]',env)
             except: 
                 pass
             try:
                 timeHF,dataHF,sampling=readHdf5.getData(x,'Generator/Fpower',env)
             except: 
                 pass
             try:
                 timeHR,dataHR,sampling=readHdf5.getData(x,'Generator/Rpower',env)
             except: 
                 pass
             try:
                 timeIF,dataIF,sampling=readHdf5.getData(x,'PXI M6251/IC_fwd',env)
             except: 
                 pass
             try:
                 timeIR,dataIR,sampling=readHdf5.getData(x,'PXI M6251/IC_ref',env)
             except: 
                 pass
             try:
                 dataL=np.array(readHdf5.getDataProcess(x,'Process/Langmuir_dens',env))
                 timeL=np.array(readHdf5.getDataProcess(x,'Process/Langmuir_time',env))
             except: 
                 pass
             try:
                 timeFW,dataFW,sampling=readHdf5.getData(x,'PXI M6251/U_fast',env)
             except: 
                 pass
             try:
                 timeSW,dataSW,sampling=readHdf5.getData(x,'PXI M6251/U_slow',env)
             except: 
                 pass
             try:
                 timePhase1,dataPhase1,sampling=readHdf5.getData(x,'PXI M6251/Phi_fast',env)
             except: 
                 pass
             try:
                 timePhase2,dataPhase2,sampling=readHdf5.getData(x,'PXI M6251/Phi_slow',env)
             except: 
                 pass
             
             pencil=pg.mkPen(color=pg.intColor(indexColor)) 
             try:
                 p1.plot(timeCoils,dataCoils,pen=pencil)
             except:    
                 pass
             try:
                p2.plot(timeP,dataP,pen=pencil)
             except:    
                pass
             try:
                p3.plot(timeHF,dataHF,pen=pencil)
                p3.plot(timeHR,dataHR,pen=pencil)
             except:    
                pass
             try:
                p4.plot(timeIF,dataIF,pen=pencil)
                p4.plot(timeIR,dataIR,pen=pencil)
             except:    
                pass
             try:
                p5.plot(timeL,dataL,pen=pencil)
             except:    
                pass
             try:
                p6.plot(timeFW,dataFW,pen=pencil)
                p6.plot(timeSW,dataSW,pen=pencil)
             except:    
                pass
             try:
                p7.plot(timePhase1,dataPhase1-dataPhase2,pen=pencil)

             except:
                 pass
             indexColor=indexColor+1
             
         p7.setXLink(p1)
         p6.setXLink(p1)
         p5.setXLink(p1)        
         p4.setXLink(p1)         
         p3.setXLink(p1)         
         p2.setXLink(p1)         
Exemplo n.º 51
0
    def init_UI(self):
        """Produce the widgets and buttons."""
        self.centre_widget = QWidget()
        self.tabs = QTabWidget()       # make tabs for each main display 
        self.centre_widget.layout = QVBoxLayout()
        self.centre_widget.layout.addWidget(self.tabs)
        self.centre_widget.setLayout(self.centre_widget.layout)
        self.setCentralWidget(self.centre_widget)
        
        # change font size
        font = QFont()
        font.setPixelSize(18)

        #### menubar at top gives options ####
        menubar = self.menuBar()

        # file menubar allows you to save/load data
        file_menu = menubar.addMenu('File')
        for label, function in [['Load Config', self.load_config],
                ['Save Config', self.save_config],
                ['Load Trace', self.load_trace], 
                ['Save Trace', self.save_trace], 
                ['Save Graph', self.save_graph]]:
            action = QAction(label, self) 
            action.triggered.connect(function)
            file_menu.addAction(action)

        #### tab for settings  ####
        settings_tab = QWidget()
        settings_grid = QGridLayout()
        settings_tab.setLayout(settings_grid)
        self.tabs.addTab(settings_tab, "Settings")

        self.settings = QTableWidget(1, 6)
        self.settings.setHorizontalHeaderLabels(['Duration (ms)', 
            'Sample Rate (kS/s)', 'Trigger Channel', 'Trigger Level (V)', 
            'Trigger Edge', 'Use Trigger?'])
        settings_grid.addWidget(self.settings, 0,0, 1,1)
        defaults = [str(self.stats['Duration (ms)']), str(self.stats['Sample Rate (kS/s)']), 
            self.stats['Trigger Channel'], str(self.stats['Trigger Level (V)']), 
            self.stats['Trigger Edge'], '1']
        validators = [double_validator, double_validator, None, double_validator, None, bool_validator]
        for i in range(6):
            table_item = QLineEdit(defaults[i]) # user can edit text to change the setting
            if defaults[i] == 'Sample Rate (kS/s)': table_item.setEnabled(False)
            table_item.setValidator(validators[i]) # validator limits the values that can be entered
            self.settings.setCellWidget(0,i, table_item)
        self.settings.resizeColumnToContents(1) 
        self.settings.setFixedHeight(70) # make it take up less space
        self.settings.cellWidget(0,0).textChanged.connect(self.check_slice_duration)
                    
        # start/stop: start waiting for a trigger or taking an acquisition
        self.toggle = QPushButton('Start', self)
        self.toggle.setCheckable(True)
        self.toggle.clicked.connect(self.activate)
        settings_grid.addWidget(self.toggle, 1,0, 1,1)

        # channels
        self.channels = QTableWidget(8, 7) # make table
        self.channels.setHorizontalHeaderLabels(['Channel', 'Label', 
            'Scale (X/V)', 'Offset (V)', 'Range', 'Acquire?', 'Plot?'])
        settings_grid.addWidget(self.channels, 2,0, 1,1) 
        validators = [None, double_validator, double_validator, None, bool_validator, bool_validator]
        for i in range(8):
            chan = 'Dev2/ai'+str(i)  # name of virtual channel
            table_item = QLabel(chan)
            self.channels.setCellWidget(i,0, table_item)
            if chan in self.stats['channels']: # load values from previous
                defaults = self.stats['channels'][chan]
            else: # default values when none are loaded
                defaults = channel_stats("[dummy, "+str(i)+", 1.0, 0.0, 5.0, 0, 0]")['dummy']
            for j, key in zip([0,1,2,4,5], ['label', 'scale', 'offset', 'acquire', 'plot']):
                table_item = QLineEdit(str(defaults[key]))
                if 'acquire' in key:
                    table_item.textChanged.connect(self.check_slice_channels)
                elif 'plot' in key:
                    table_item.textChanged.connect(self.set_acquire)
                table_item.setValidator(validators[j])        
                self.channels.setCellWidget(i,j+1, table_item)
            vrange = QComboBox() # only allow certain values for voltage range
            vrange.text = vrange.currentText # overload function so it's same as QLabel
            vrange.addItems(['%.1f'%x for x in self.slave.vrs])
            try: vrange.setCurrentIndex(self.slave.vrs.index(defaults['range']))
            except Exception as e: logger.error('Invalid channel voltage range\n'+str(e))
            self.channels.setCellWidget(i,4, vrange)

        #### Plot for most recently acquired trace ####
        trace_tab = QWidget()
        trace_grid = QGridLayout()
        trace_tab.setLayout(trace_grid)
        self.tabs.addTab(trace_tab, "Trace")
        
        # button activates horizontal line
        self.hline_toggle = QPushButton('Horizontal line', self, checkable=True)
        self.hline_toggle.clicked.connect(self.add_horizontal)
        trace_grid.addWidget(self.hline_toggle, 0,0, 1,1)
        self.hline_label = QLabel()
        trace_grid.addWidget(self.hline_label, 0,1, 1,1)
        fadeline_button = QPushButton('Persist', self)
        fadeline_button.clicked.connect(self.set_fadelines)
        trace_grid.addWidget(fadeline_button, 0,2, 1,1)
        

        # plot the trace
        self.trace_canvas = pg.PlotWidget()
        self.trace_legend = self.trace_canvas.addLegend()
        self.trace_canvas.getAxis('bottom').tickFont = font
        self.trace_canvas.getAxis('left').tickFont = font
        self.trace_canvas.setLabel('bottom', 'Time', 's', **{'font-size':'18pt'})
        self.trace_canvas.setLabel('left', 'Voltage', 'V', **{'font-size':'18pt'})
        self.lines = [] # handles for lines plotting the last measurement
        self.fadelines = [] # handles for previous measurement lines
        for i in range(8):
            chan = self.channels.cellWidget(i,1).text()
            self.lines.append(self.trace_canvas.plot([1], name=chan, 
                    pen=pg.mkPen(pg.intColor(i), width=3)))
            self.lines[i].hide()
            self.fadelines.append(self.trace_canvas.plot([1], 
                    pen=pg.mkPen(pg.intColor(i, alpha=50), width=2)))
            self.fadelines[i].hide()
        self.hline = pg.InfiniteLine(1., angle=0, pen='k', movable=True)
        self.trace_canvas.addItem(self.hline)
        self.hline.sigPositionChanged.connect(self.update_hline)
        self.hline.hide()
        
            
        trace_grid.addWidget(self.trace_canvas, 1,0, 1,3)
        
        #### Settings for slices of the trace accumulating into the graph ####
        slice_tab = QWidget()
        slice_grid = QGridLayout()
        slice_tab.setLayout(slice_grid)
        self.tabs.addTab(slice_tab, "Slice")
        
        # Buttons to add/remove slices and reset graph
        for i, (label, func) in enumerate([['Add slice', self.add_slice],
                ['Remove slice', self.del_slice], ['Reset graph', self.reset_graph]]):
            button = QPushButton(label, self)
            button.clicked.connect(func)
            slice_grid.addWidget(button, 0,i, 1,1)
        
        # parameters for slices
        self.slices = QTableWidget(0, 4) # make table
        self.slices.setHorizontalHeaderLabels(['Slice name', 
            'Start (ms)', 'End (ms)', 'Channels'])
        slice_grid.addWidget(self.slices, 1,0, 1,3) 

        #### Plot for graph of accumulated data ####
        graph_tab = QWidget()
        graph_grid = QGridLayout()
        graph_tab.setLayout(graph_grid)
        self.tabs.addTab(graph_tab, "Graph")

        self.mean_graph = pg.PlotWidget() # for plotting means
        self.stdv_graph = pg.PlotWidget() # for plotting standard deviations
        self.graph_legends = []
        for i, g in enumerate([self.mean_graph, self.stdv_graph]):
            g.getAxis('bottom').tickFont = font
            g.getAxis('bottom').setFont(font)
            g.getAxis('left').tickFont = font
            g.getAxis('left').setFont(font)
            graph_grid.addWidget(g, i,0, 1,1)
        self.reset_lines() # make a line for every slice channel
        self.stdv_graph.setLabel('bottom', 'Shot', '', **{'font-size':'18pt'})
        self.stdv_graph.setLabel('left', 'Standard Deviation', 'V', **{'font-size':'18pt'})
        self.mean_graph.setLabel('left', 'Mean', 'V', **{'font-size':'18pt'})
        
        #### tab for TCP message settings  ####
        tcp_tab = QWidget()
        tcp_grid = QGridLayout()
        tcp_tab.setLayout(tcp_grid)
        self.tabs.addTab(tcp_tab, "Sync")

        label = QLabel('Run number: ')
        tcp_grid.addWidget(label, 0,0, 1,1)
        self.n_edit = QLineEdit(str(self.stats['n']))
        self.n_edit.setValidator(int_validator)
        self.n_edit.textEdited[str].connect(self.set_n)
        tcp_grid.addWidget(self.n_edit, 0,1, 1,1)
        
        label = QLabel('Save directory: ')
        tcp_grid.addWidget(label, 1,0, 1,1)
        self.save_edit = QLineEdit(self.stats['save_dir'])
        self.save_edit.textEdited[str].connect(self.set_save_dir)
        tcp_grid.addWidget(self.save_edit, 1,1, 1,1)
        
        label = QLabel('Trace file name: ')
        tcp_grid.addWidget(label, 2,0, 1,1)
        self.trace_edit = QLineEdit(self.stats['trace_file'])
        self.trace_edit.textEdited[str].connect(self.set_trace_file)
        tcp_grid.addWidget(self.trace_edit, 2,1, 1,1)
        
        label = QLabel('Graph file name: ')
        tcp_grid.addWidget(label, 3,0, 1,1)
        self.graph_edit = QLineEdit(self.stats['graph_file'])
        self.graph_edit.textEdited[str].connect(self.set_graph_file)
        tcp_grid.addWidget(self.graph_edit, 3,1, 1,1)
        
        reset = QPushButton('Reset TCP client', self)
        reset.clicked.connect(self.reset_client)
        tcp_grid.addWidget(reset, 4,0, 1,1)

        #### Title and icon ####
        self.setWindowTitle('- NI DAQ Controller -')
        self.setWindowIcon(QIcon('docs/daqicon.png'))
        self.setGeometry(200, 200, 800, 600)
Exemplo n.º 52
0
    def creategradient(self):
        g = QtGui.QLinearGradient()
        for i in range(17):
            g.setColorAt(float(i)/17.0, pg.intColor(i, hues=17))

        return g
Exemplo n.º 53
0
 def new_curve(self, results, color=None, **kwargs):
     if color is None:
         color = pg.intColor(self.browser.topLevelItemCount() % 8)
     return self.plot_widget.new_curve(results, color=color, **kwargs)
Exemplo n.º 54
0
view.nextRow()
w3 = view.addPlot(title="residual Sugar vs Density in red Wines")
w4 = view.addPlot(title="residual Sugar vs Density in white Wines")
print("Generating data, this takes a few seconds...")

# 1: pH vs Alcohol red wines  (color = quality)
s1 = pg.ScatterPlotItem(size=10, pxMode=True)
spots1 = []
n = len(data['alcohol'])
x_var1 = data['alcohol']
y_var1 = data['pH']
scale = data['quality']
for i in range(n):
    spots1.append({
        'pos': (x_var1[i], y_var1[i]),
        'brush': pg.intColor(scale[i] * 10, 100)
    })
s1.addPoints(spots1)
w1.addItem(s1)

# 2: pH vs Alcohol  white(color = quality)
s2 = pg.ScatterPlotItem(size=10, pxMode=True)
spots2 = []
n = len(data2['alcohol'])
x_var2 = data2['alcohol']
y_var2 = data2['pH']
scale2 = data2['quality']
for i in range(n):
    spots2.append({
        'pos': (x_var2[i], y_var2[i]),
        'brush': pg.intColor(scale2[i] * 10, 100)
Exemplo n.º 55
0
    def updatePlot(self, *args):

        rawIndex = self.rawCB.currentIndex()
        trajIndex = self.trajCB.currentIndex()

        # get current acquisition if data or trajectory plot enabled
        if rawIndex != 0 or trajIndex != 0:
            # get currently selected row from table view
            row = self.tableView.currentIndex().row()

            # read corresponding acquisiton from table model buffer
            aq = ismrmrd.Acquisition(
                self.tableModel.rbuffer.getCell(row)['head'])

        # update raw data plot
        if rawIndex != 0:
            # get the data
            data = self.tableModel.rbuffer.getCell(row)['data'].view(
                np.complex64).reshape(
                    (aq.active_channels, aq.number_of_samples))[:]

            # modifiy data depending on selected visualization
            if self.rawCB.currentText() == 'Real':
                dataOut = np.real(data)
            elif self.rawCB.currentText() == 'Imag':
                dataOut = np.imag(data)
            elif self.rawCB.currentText() == 'FFT (magnitude)':
                dataOut = abs(np.fft.fftshift(np.fft.fft(data)))
            elif self.rawCB.currentText() == 'Phase':
                dataOut = np.angle(data)
            elif self.rawCB.currentText() == 'Phase (unwrapped)':
                dataOut = np.unwrap(np.angle(data))
            else:
                dataOut = abs(data)

            # remove old plots and legend entries
            for item in self.rawPlot.items():
                self.rawPlot.removeItem(item)
            try:
                self.rawPlot.legend.scene().removeItem(self.rawPlot.legend)
            except Exception as e:
                print(e)

            #self.plotWidget.rawPlot.clear()
            self.rawPlot.setTitle('Coil data')
            self.rawPlot.legend = self.rawPlot.addLegend()

            for ind in range(0, len(dataOut)):
                color = pg.intColor(ind)
                self.rawPlot.plot(dataOut[ind, :],
                                  pen=pg.mkPen(color),
                                  name=' Channel ' + str(ind))

            self.rawPlot.show()
        else:
            self.rawPlot.hide()

        # update trajectory plot
        if self.trajCB.currentIndex() != 0 and aq.traj.size > 0:
            # get the data
            data = self.tableModel.rbuffer.getCell(row)['traj'].reshape(
                (aq.number_of_samples, aq.trajectory_dimensions))[:]

            # modifiy data depending on selected visualization
            if self.trajCB.currentText() == 'FFT (magnitude)':
                dataOut = abs(np.fft.fft(data))
            else:
                dataOut = data

            # remove old plots and legend entries
            for item in self.trajPlot.items():
                self.trajPlot.removeItem(item)
            try:
                self.trajPlot.legend.scene().removeItem(self.trajPlot.legend)
            except Exception as e:
                print(e)

            #self.plotWidget.trajPlot.clear()
            self.trajPlot.setTitle('Trajectory data')
            self.trajPlot.legend = self.trajPlot.addLegend()

            for ind in range(0, dataOut.shape[1]):
                color = pg.intColor(ind)
                self.trajPlot.plot(dataOut[:, ind],
                                   pen=pg.mkPen(color),
                                   name=' Channel ' + str(ind))

            self.trajPlot.show()
        else:
            self.trajPlot.hide()
Exemplo n.º 56
0
    def update_scater_plot():
        global number_of_spikes
        global tsne_spots
        global spike_info

        scatter_item.clear()
        scatter_selected_item.clear()

        number_of_spikes = len(spike_info)

        progdialog = QtWidgets.QProgressDialog()
        progdialog.setGeometry(500, 500, 400, 40)
        progdialog.setWindowTitle('Loading t-sne plot')
        progdialog.setMinimum(0)
        progdialog.setMaximum(5)
        progdialog.setWindowModality(QtCore.Qt.WindowModal)

        progdialog.setLabelText(
            'Generating colors _____________________________________')
        progdialog.show()
        progdialog.setValue(0)
        QtWidgets.QApplication.processEvents()

        color = [
            pg.intColor(spike_info['template_after_sorting'].iloc[i],
                        hues=50,
                        values=1,
                        maxValue=255,
                        minValue=150,
                        maxHue=360,
                        minHue=0,
                        sat=255,
                        alpha=255) for i in range(number_of_spikes)
        ]

        progdialog.setLabelText(
            'Generating brushes ____________________________________')
        progdialog.setValue(1)

        brush = [pg.mkBrush(color[i]) for i in range(number_of_spikes)]

        progdialog.setLabelText(
            'Generating positions __________________________________')
        progdialog.setValue(2)

        tsne_spots = [{
            'pos':
            [spike_info['tsne_x'].iloc[i], spike_info['tsne_y'].iloc[i]],
            'data':
            1,
            'brush':
            brush[i]
        } for i in range(number_of_spikes)]

        progdialog.setLabelText(
            'Adding points to plot __________________________________')
        progdialog.setValue(3)

        scatter_item.addPoints(tsne_spots)

        progdialog.setLabelText(
            'Generating symbols ... Almost done ______________________')
        progdialog.setValue(4)

        symbol = []
        for i in range(number_of_spikes):
            symbol.append(
                hf.symbol_from_type(spike_info['type_after_sorting'].iloc[i]))

        scatter_item.setSymbol(symbol)

        progdialog.setValue(5)
        progdialog.close()
Exemplo n.º 57
0
 def add_data(self,x,y,yerr=None,name=None,fit=False,color=None):
     """
     Adds data into the plot where:
     x=Array of x-values
     y=Array of y-values
     yerr=Array of yerr-values. If None yerr will be set to sqrt(y)
     name=any string to be used for the key to put the data
     fit= True if the data corresponds to a fit
     """
     if not (isinstance(yerr,list) or isinstance(yerr,np.ndarray)):
         yerr=np.ones_like(y)
     x=np.array(x)
     y=np.array(y)
     if len(x)==len(y) and len(y)==len(yerr):
         if name is None:
             dname=str(self.data_num)
         else:
             dname=name
         if np.all(yerr==1):
             self.yerr[dname]=False
         else:
             self.yerr[dname]=True
         self.fit[dname]=fit
         if dname in self.data.keys():
             if color is None:
                 color=self.data[dname].opts['symbolPen'].color()
             pen=pg.mkPen(color=color,width=float(self.lineWidthLineEdit.text()))
             symbol='o'
             if self.fit[dname]:
                 symbol=None
             self.data[dname].setData(x,y,pen=pen,symbol=symbol,symbolSize=float(self.pointSizeLineEdit.text()),symbolPen=pg.mkPen(color=color),symbolBrush=pg.mkBrush(color=color))
             #self.data[dname].setPen(pg.mkPen(color=pg.intColor(np.random.choice(range(0,210),1)[0]),width=int(self.lineWidthLineEdit.text())))
             #if self.errorbarCheckBox.isChecked():
             # self.dataErrPos[dname].setData(x,np.where(y+yerr/2.0>0,y+yerr/2.0,y))
             # self.dataErrNeg[dname].setData(x,np.where(y-yerr/2.0>0,y-yerr/2.0,y))
             self.err[dname]= yerr
             self.dataErr[dname].setData(x=x, y=y, top=self.err[dname], bottom=self.err[dname], pen='w')# beam=min(np.abs(x))*0.01*float(self.pointSizeLineEdit.text()),pen='w')
         #self.dataErr[dname].setCurves(self.dataErrPos[dname],self.dataErrNeg[dname])
         else:
             if color is None:
                 color=pg.intColor(np.random.choice(range(0,210),1)[0])
             #color=self.data[dname].opts['pen'].color()
             pen=pg.mkPen(color=color,width=float(self.lineWidthLineEdit.text()))
             symbol='o'
             if self.fit[dname]:
                 symbol=None
             self.data[dname]=pg.PlotDataItem(x,y,pen=pen,symbol=symbol,symbolSize=float(self.pointSizeLineEdit.text()),symbolPen=pg.mkPen(color=color),symbolBrush=pg.mkBrush(color=color))
             self.dataErr[dname] = pg.ErrorBarItem()
             self.err[dname]=yerr
             self.dataErr[dname].setData(x=x,y=y,top=self.err[dname],bottom=self.err[dname], pen='w')# beam=min(np.abs(x))*0.01*float(self.pointSizeLineEdit.text()),pen='w')
             self.data[dname].curve.setClickable(True,width=10)
             self.data[dname].sigClicked.connect(self.colorChanged)
             #if self.errorbarCheckBox.isChecked():
             # self.dataErrPos[dname]=pg.PlotDataItem(x,np.where(y+yerr/2.0>0,y+yerr/2.0,y))
             # self.dataErrNeg[dname]=pg.PlotDataItem(x,np.where(y-yerr/2.0>0,y-yerr/2.0,y))
             #self.dataErr[dname]=pg.FillBetweenItem(curve1=self.dataErrPos[dname],curve2=self.dataErrNeg[dname],brush=pg.mkBrush(color=pg.hsvColor(1.0,sat=0.0,alpha=0.2)))
             self.data_num+=1
             #if len(x)>1:
             self.Plot([dname])
         return True
     else:
         QMessageBox.warning(self,'Data error','The dimensions of x, y or yerr are not matching',QMessageBox.Ok)
         return False
Exemplo n.º 58
0
    def on_tsne_color_scheme_combo_box_change(index):
        global number_of_spikes
        global spike_info

        progdialog = QtWidgets.QProgressDialog()
        progdialog.setGeometry(500, 500, 400, 40)
        progdialog.setWindowTitle('Changing spike color scheme')
        progdialog.setMinimum(0)
        progdialog.setMaximum(2)
        progdialog.setWindowModality(QtCore.Qt.WindowModal)

        progdialog.setLabelText(
            'Generating colors and symbols ...                  ')
        progdialog.show()
        progdialog.setValue(0)
        QtWidgets.QApplication.processEvents()

        spikes_to_change = range(number_of_spikes)

        if index == 0:
            color_scheme = spike_info['template_after_sorting']
            brush = [
                pg.intColor(color_scheme.iloc[i],
                            hues=50,
                            values=1,
                            maxValue=255,
                            minValue=150,
                            maxHue=360,
                            minHue=0,
                            sat=255,
                            alpha=255) for i in spikes_to_change
            ]
            symbol = []
            for i in spikes_to_change:
                symbol.append(
                    hf.symbol_from_type(
                        spike_info['type_after_sorting'].iloc[i]))
        elif index == 1:
            color_scheme = spike_info['template_after_cleaning']
            brush = [
                pg.intColor(color_scheme.iloc[i],
                            hues=50,
                            values=1,
                            maxValue=255,
                            minValue=150,
                            maxHue=360,
                            minHue=0,
                            sat=255,
                            alpha=255) for i in spikes_to_change
            ]
            symbol = []
            for i in spikes_to_change:
                symbol.append(
                    hf.symbol_from_type(
                        spike_info['type_after_cleaning'].iloc[i]))

        progdialog.setValue(1)
        progdialog.setLabelText(
            'Applying colors and symbols ...                   ')
        QtWidgets.QApplication.processEvents()

        scatter_item.setBrush(brush)
        scatter_item.setSymbol(symbol)

        progdialog.setValue(2)
        progdialog.close()
Exemplo n.º 59
0
    def plotResults(self, res, runInfo, somasite=['postsynapticV', 'postsynapticI', 'dendriteV']):
        clist={'axon': 'r', 'heminode': 'g', 'stalk':'y', 'branch': 'g', 'neck': 'b',
                'swelling': 'm', 'tip': 'k', 'parentaxon': '', r'synapse': 'c', 'Soma': 'k',
                'dendrite': 'c', 'dend': 'c'}
        dx = np.array([x for k,x in res['distanceMap'].items()])
        dlen = res['monitor']['postsynapticV'].shape[0]
        dxmax = np.max(dx)

        
        if self.plotmode == 'pg':
            self.plots['Soma'].setLabel('left', 'V')
            self.plots['Soma'].plot(res['monitor']['time'][:dlen], res['monitor']['postsynapticV'],
                pen=pg.mkPen(clist['Soma'], width=0.5), )
            if 'dendriteV' in somasite and self.plots['Dendrite'] is not None and len(res['monitor']['dendriteV']) > 0:
                self.plots['Dendrite'].plot(res['monitor']['time'][:dlen], 
                    res['monitor']['dendriteV'], pen=pg.mkPen(clist['dendrite'], width=0.5), )
                self.plots['Dendrite'].setLabel('left', 'V (mV)')
            if 'vec' in res.keys()and self.plots['p4'] is not None:
                for v in res['vec']:
                    self.plots['p4'].plot(res['monitor']['time'], res['vec'][v],
                                 pen=pg.mkPen(pg.intColor(int(255.*res['distanceMap'][v]/dxmax))),
                                 width=1.5)
            if 'postsynapticI' in somasite and self.plots['Iinj'] is not None:
                vlen = len(res['monitor']['postsynapticI'])
                self.plots['Iinj'].plot(res['monitor']['time'][0:vlen], res['monitor']['postsynapticI'],
                    pen = pg.mkPen('b', width=0.5))
                self.plots['Iinj'].setLabel('left', 'I (inj, nA)')
            if 'vec' in res.keys() and self.plots['p4'] is not None:
                for v in res['vec']:
                    self.plots['p4'].plot(res['monitor']['time'], res['vec'][v],
                                 pen=pg.mkPen(pg.intColor(int(255.*res['distanceMap'][v]/dxmax))),
                                 width=0.5)
            #for c in res['ICa']:
            #     self.plots['Dendrite'].plot(res['monitor']['time'], res['ICa'][c]*1e12, pen=pg.mkPen('b', width=1.5))
            #     self.plots['Iinj'].plot(res['vec']['time'], res['Cai'][c]*1e6, pen=pg.mkPen('g', width=1.5))

                    #p2.set_ylim(-5e-12, 1e-12)
            self.plots['Soma'].setXRange(0., 120., padding=0.2)
            self.plots['Dendrite'].setXRange(0., 120., padding=0.2)
            if self.plots['Iinj'] is not None:
                self.plots['Iinj'].setXRange(0., 120., padding=0.2)
            
            pgPH.cleanAxes([self.plots['Soma'], self.plots['Dendrite'], self.plots['Iinj'], self.plots['p4']])
            pgPH.nice_plot(self.plots['Soma'])
            pgPH.calbar(self.plots['Soma'], [110, -50, 20, 50])
           # pgPH.nice_plot(self.plots['Dendrite'])
        #    pgPH.calbar(self.plots['Dendrite'], [110, 0.1, 20, 1])
            if self.plots['Iinj'] is not None:
                pgPH.nice_plot(self.plots['Iinj'])
                pgPH.calbar(self.plots['Iinj'], [110, -0.1, 20, 1])


        elif self.plotmode == 'mpl':
            self.plots['Soma'].set_ylabel('V')
            self.plots['Soma'].plot(res['monitor']['time'][:dlen], res['monitor']['postsynapticV'],
            color=clist['Soma'], linewidth=0.5)
            if 'dendriteV' in somasite and self.plots['Dendrite'] is not None and len(res['monitor']['dendriteV']) > 0:
                self.plots['Dendrite'].plot(res['monitor']['time'][:dlen], 
                    res['monitor']['dendriteV'], color=clist['dendrite'], linewidth=0.5)
                self.plots['Dendrite'].set_ylabel('V (mV)')
            if 'vec' in res.keys()and self.plots['p4'] is not None:
                for v in res['vec']:
                    self.plots['p4'].plot(res['monitor']['time'], res['vec'][v],
                                 color=[[int(255.*res['distanceMap'][v]/dxmax)]*3],
                                 linewidth=0.75)
            if 'postsynapticI' in somasite and self.plots['Iinj'] is not None:
                vlen = len(res['monitor']['postsynapticI'])
                self.plots['Iinj'].plot(res['monitor']['time'][0:vlen], res['monitor']['postsynapticI'],
                    color='b', linewidth=0.5)
                self.plots['Iinj'].set_ylabel('I (inj, nA)')
            if 'vec' in res.keys() and self.plots['p4'] is not None:
                for v in res['vec']:
                    self.plots['p4'].plot(res['monitor']['time'], res['vec'][v],
                                 color=[[int(255.*res['distanceMap'][v]/dxmax)]*3],
                                 linewidth=0.75)
            #for c in res['ICa']:
            #     self.plots['Dendrite'].plot(res['monitor']['time'], res['ICa'][c]*1e12, pen=pg.mkPen('b', width=1.5))
            #     self.plots['Iinj'].plot(res['vec']['time'], res['Cai'][c]*1e6, pen=pg.mkPen('g', width=1.5))

                    #p2.set_ylim(-5e-12, 1e-12)
            self.plots['Soma'].set_xlim(0., 120.)
            self.plots['Dendrite'].set_xlim(0., 120.)
            if self.plots['Iinj'] is not None:
                self.plots['Iinj'].set_xlim(0., 120.)
            
            PH.cleanAxes([self.plots['Soma'], self.plots['Dendrite'], self.plots['Iinj']])
            PH.nice_plot(self.plots['Soma'])
            PH.calbar(self.plots['Soma'], [110, -50, 20, 50])
            PH.nice_plot(self.plots['Dendrite'])
            PH.calbar(self.plots['Dendrite'], [110, -50, 20, 50])
           # pgPH.nice_plot(self.plots['Dendrite'])
        #    pgPH.calbar(self.plots['Dendrite'], [110, 0.1, 20, 1])
            if self.plots['Iinj'] is not None:
                PH.nice_plot(self.plots['Iinj'])
                PH.calbar(self.plots['Iinj'], [110, -0.1, 20, 1])        
Exemplo n.º 60
0
 def define_pens(self, width=2, max_colors=10):
     self._line_width = width
     self._max_colors = max_colors
     self._brightness_percentage = 90
     self._pens = [pg.mkPen(pg.intColor(i, self._max_colors+1).lighter(self._brightness_percentage), width=self._line_width) for i in range(self._max_colors)]