Exemplo n.º 1
0
    def step(self):
        # decide how much to advance preview
        data = self.data
        now = pg.ptime.time()
        dt = (now - self.lastTime) * self.rate
        index = self.index + dt * self.sampleRate
        npts = data.shape[0]
        end = min(index, npts-1)
        va = data[:end]

        self.index = index
        self.lastTime = now

        # draw path
        self.path.setData(va[:,0], va[:,1])
        self.timeline.setValue(end / self.sampleRate)
        self.spot.setPos(va[-1,0], va[-1,1])
        if self.laserMask[end]:
            self.spot.setBrush(pg.mkBrush('y'))
        else:
            self.spot.setBrush(pg.mkBrush('k'))

        # Stop preview and delete path data if we reached the end
        if end >= npts-1:
            self.timer.stop()
            self.data = None
            self.laserMask = None
Exemplo n.º 2
0
 def paint(self, p, *args):
     p.setRenderHint(p.Antialiasing)
     w, h = self._pxLen
     p.setPen(pg.mkPen('y'))
     p.setBrush(pg.mkBrush(255, 255, 0, 100))
     p.scale(w, h)
     p.drawPath(self._path)
Exemplo n.º 3
0
 def __init__(self):
     pg.GraphicsObject.__init__(self)
     self.times = []
     self.yRange = (0.1, 0.2)
     self.xRange = [float('inf'), float('-inf')]
     self.pen = pg.mkPen(None)
     self.brush = pg.mkBrush((200, 200, 255, 200))
Exemplo n.º 4
0
 def __init__(self):
     pg.GraphicsObject.__init__(self)
     self.times = []
     self.yRange=(0.1, 0.2)
     self.xRange=[float('inf'), float('-inf')]
     self.pen = pg.mkPen(None)
     self.brush = pg.mkBrush((200,200,255,200))
Exemplo n.º 5
0
    def paintEvent(self, event):
        p = QtGui.QPainter(self)
        brush = pg.mkBrush(0.0)
        p.fillRect(self.rect(), brush)

        center = self.rect().center()
        r = QtCore.QPoint(70, 30)
        self.cancelRect = QtCore.QRect(center-r, center+r)
        p.setPen(pg.mkPen(150, 0, 0))
        f = p.font()
        f.setPointSize(18)
        p.setFont(f)
        if self.cancelPressed:
            p.fillRect(self.cancelRect, pg.mkBrush(80, 0, 0))
        p.drawRect(self.cancelRect)
        p.drawText(self.cancelRect, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter, "Cancel")
        p.end()
Exemplo n.º 6
0
    def update_sequence_analysis(self):
        xvals = []
        yvals = []
        brushes = []
        avg_x = []
        avg_y = []

        noise_values = []

        for i in range(len(self.img_data)):

            img_data = self.img_arrays[i]
            img_t = self.img_data[i][0].xvals('Time')
            base_starti, base_stopi, test_starti, test_stopi = self.time_indices(
                img_t)

            base = img_data[:, base_starti:base_stopi]
            base_mean = base.mean(axis=1)
            test = img_data[:, test_starti:test_stopi]
            test_mean = test.mean(axis=1)

            roi1, roi2 = self.rois  # roi1 is signal, roi2 is background
            base_rgn1 = roi1.getArrayRegion(base_mean, self.img1, axes=(1, 2))
            base_rgn2 = roi2.getArrayRegion(base_mean, self.img1, axes=(1, 2))
            test_rgn1 = roi1.getArrayRegion(test_mean, self.img1, axes=(1, 2))
            test_rgn2 = roi2.getArrayRegion(test_mean, self.img1, axes=(1, 2))

            # Use the temporal profile in roi2 in order to remove changes in LED brightness over time
            # Then use the difference between baseline and test time regions to determine change in fluorescence
            baseline1 = base_rgn1.mean(axis=1).mean(axis=1)
            signal1 = test_rgn1.mean(axis=1).mean(axis=1)
            baseline2 = base_rgn2.mean(axis=1).mean(axis=1)
            signal2 = test_rgn2.mean(axis=1).mean(axis=1)
            dff = ((signal1 - signal2) -
                   (baseline1 - baseline2)) / (baseline1 - baseline2)

            x = self.seqParams[0][1][i]
            xvals.extend([x] * len(dff))
            yvals.extend(list(dff))
            color = pg.mkColor(self.seqColors[i])
            color.setAlpha(50)
            brushes.extend([pg.mkBrush(color)] * len(dff))
            avg_x.append(x)
            avg_y.append(dff.mean())

        self.plt3.clear()
        if self.seqParams[0][0] is None:
            self.plt3.plot(range(len(xvals)), yvals, pen='w')
        else:
            self.plt3.plot(xvals,
                           yvals,
                           symbol='o',
                           pen=None,
                           symbolBrush=brushes,
                           symbolPen=None)
            self.plt3.plot(avg_x, avg_y, pen='w', antialias=True)
Exemplo n.º 7
0
 def __init__(self, **opts):
     if 'scale' not in opts:
         opts['scale'] = [20e-6, 20e-6]
     item = QtGui.QGraphicsEllipseItem(-0.5, -0.5, 1., 1.)
     item.setPen(pg.mkPen((255, 255, 255)))
     item.setBrush(pg.mkBrush((0, 100, 255)))
     opts.setdefault('scalable', False)
     opts.setdefault('rotatable', False)
     CanvasItem.__init__(self, item, **opts)
     self.selectBox.addTranslateHandle([0.5, 0.5])
Exemplo n.º 8
0
 def paint(self, p, *args):
     p.setRenderHint(p.Antialiasing)
     w, h = self._pxLen
     # r = QtCore.QRectF(-w, -h, w*2, h*2)
     p.setPen(pg.mkPen('y'))
     p.setBrush(pg.mkBrush(255, 255, 0, 100))
     # p.drawEllipse(r)
     # p.drawLine(pg.Point(-w*2, 0), pg.Point(w*2, 0))
     # p.drawLine(pg.Point(0, -h*2), pg.Point(0, h*2))
     p.scale(w, h)
     p.drawPath(self._path)
Exemplo n.º 9
0
 def __init__(self, **opts):
     if 'scale' not in opts:
         opts['scale'] = [20e-6, 20e-6]
         #opts['size'] = [20e-6, 20e-6]
         #opts['scale'] = [1., 1.]
     item = QtGui.QGraphicsEllipseItem(-0.5, -0.5, 1., 1.)
     item.setPen(pg.mkPen((255,255,255)))
     item.setBrush(pg.mkBrush((0,100,255)))
     opts['scalable'] = False
     opts['rotatable'] = False
     CanvasItem.__init__(self, item, **opts)
     self.selectBox.addTranslateHandle([0.5,0.5])
Exemplo n.º 10
0
    def update_sequence_analysis(self):
        analysis = self.params['sequence', 'analysis']
        xvals = []
        yvals = []
        noise = []
        brushes = []
        avg_x = []
        avg_y = []
        avg_noise = []

        for i in range(len(self.img_data)):

            img_data = self.img_arrays[i]
            img_t = self.img_data[i][0].xvals('Time')
            base_starti, base_stopi, test_starti, test_stopi, noise_starti, noise_stopi = self.time_indices(img_t)
            dff = self.measure_dff(img_data, img_t, (base_starti, base_stopi, test_starti, test_stopi))
            
            x = self.seqParams[0][1][i]
            xvals.extend([x] * len(dff))
            
            yvals.extend(list(dff))
            
            if analysis in ('SNR', 'noise'):
                noise_dff = self.measure_dff(img_data, img_t, (base_starti, base_stopi, noise_starti, noise_stopi))
                noise.extend(list(noise_dff))
                avg_noise.append(noise_dff.mean())
            
            color = pg.mkColor(self.seqColors[i])
            color.setAlpha(50)
            brushes.extend([pg.mkBrush(color)] * len(dff))
            avg_x.append(x)
            avg_y.append(dff.mean())

        if analysis == 'SNR':
            noise = np.std(noise)
            yvals = np.array(yvals) / noise
            avg_y = np.array(avg_y) / noise
        elif analysis == 'noise':
            yvals = noise
            avg_y = avg_noise


        self.plt3.clear()
        self.plt3.setLabels(left=analysis)
        if self.seqParams[0][0] is None:
            self.plt3.plot(range(len(xvals)), yvals, pen='w')
        else:
            self.plt3.plot(xvals, yvals, symbol='o', pen=None, symbolBrush=brushes, symbolPen=None)
            self.plt3.plot(avg_x, avg_y, pen='w', antialias=True)
            
            lin = stats.linregress(avg_x, avg_y)
            self.plt3.setTitle("slope: %0.2g" % lin[0])
Exemplo n.º 11
0
 def addScan(self, scanDict):
     plot = pg.ScatterPlotItem(pen=QtGui.QPen(QtCore.Qt.NoPen), brush=pg.mkBrush((255, 255, 255, 100)))
     self.plot.addItem(plot)
     plot.sigClicked.connect(self.plotClicked)
     
     if not isinstance(scanDict, dict):
         scanDict = {'key':scanDict}
     #print "Adding:", scan.name
     for scan in scanDict.values():
         item = QtGui.QTreeWidgetItem([scan.name()])
         item.setCheckState(0, QtCore.Qt.Checked)
         item.scan = scan
         self.scanList.addTopLevelItem(item)
         self.scans[scan] = [plot, item, False]
         self.updateScan(scan)
         scan.sigEventsChanged.connect(self.invalidateScan)
Exemplo n.º 12
0
    def addScan(self, scanDict):
        plot = pg.ScatterPlotItem(pen=QtGui.QPen(QtCore.Qt.NoPen),
                                  brush=pg.mkBrush((255, 255, 255, 100)))
        self.plot.addItem(plot)
        plot.sigClicked.connect(self.plotClicked)

        if not isinstance(scanDict, dict):
            scanDict = {'key': scanDict}
        #print "Adding:", scan.name
        for scan in scanDict.values():
            item = QtGui.QTreeWidgetItem([scan.name()])
            item.setCheckState(0, QtCore.Qt.Checked)
            item.scan = scan
            self.scanList.addTopLevelItem(item)
            self.scans[scan] = [plot, item, False]
            self.updateScan(scan)
            scan.sigEventsChanged.connect(self.invalidateScan)
Exemplo n.º 13
0
    def paint(self, p, *args):
        p.setRenderHint(p.Antialiasing)
        px = self.pixelLength(pg.Point(1, 0))
        py = self.pixelLength(pg.Point(0, 1))
        w = 5 * px
        h = 5 * py
        r = QtCore.QRectF(-w, -h, w * 2, h * 2)
        p.setPen(pg.mkPen('y'))
        p.setBrush(pg.mkBrush(0, 0, 255, 100))
        p.drawEllipse(r)
        p.drawLine(pg.Point(-w * 2, 0), pg.Point(w * 2, 0))
        p.drawLine(pg.Point(0, -h * 2), pg.Point(0, h * 2))

        if self.label is not None:
            angle = self.labelAngle * np.pi / 180.
            pos = p.transform().map(QtCore.QPointF(
                0, 0)) + 15 * QtCore.QPointF(np.cos(angle), -np.sin(angle))
            p.resetTransform()
            p.drawText(QtCore.QRectF(pos.x() - 10,
                                     pos.y() - 10, 20, 20),
                       QtCore.Qt.AlignCenter | QtCore.Qt.AlignVCenter,
                       self.label)
Exemplo n.º 14
0
def showMap(dh=None):
    """
    Display a graphic of an input map for the currently selected cell
    """
    
    global v, g, atlas
    if dh is None:
        dh = man.currentFile
    db = man.getModule('Data Manager').currentDatabase()
    v.clear()
    
    cd = dh
    sd = cd.parent()
    atlas.loadState(sd)
    
    g = atlas.schematicGraphicsItems(contours=False, sliceScale=10, cellDir=cd)
    v.addItem(g)
    
    cellGroup = pg.ItemGroup()
    g.cellGroup = cellGroup
    cellScale = 10.
    cellGroup.scale(cellScale, cellScale)
    cellGroup.setParentItem(g)
    
    g.atlasScale.hide()
    g.arrowGroup.hide()
    
    ## reposition/rescale atlas group
    b1 = g.atlasGroup.mapRectToParent(g.atlasGroup.childrenBoundingRect())
    b2 = g.sliceClip.mapRectToParent(g.sliceClip.boundingRect())
    g.atlasGroup.setPos(b2.right()-b1.left()+0.001, b2.top()-b1.top())
    
    b1 = g.atlasGroup.mapRectToParent(g.atlasGroup.childrenBoundingRect())    
    bounds = b1 | b2
    
    if cd.exists('morphology.png'):
        ## small image to go over slice schematic
        imgf = cd['morphology.png']
        imgd = pg.colorToAlpha(imgf.read(), np.array([255,255,255]))
        mimg1 = pg.ImageItem(imgd)
        tr = pg.SRTTransform(imgf.info()['userTransform'])
        mimg1.setTransform(tr)
        mimg1.setParentItem(g.sliceGroup)
        mimg1.setZValue(100)
        g.cellImg1 = mimg1
        
        ## larger image to be displayed above
        mimg2 = pg.ImageItem(imgd)
        mimg2.setParentItem(cellGroup)
        mimg2.setTransform(tr * g.sliceGroup.transform())
        mimg2.scale(1.0 / g.sliceScaleFactor, 1.0 / g.sliceScaleFactor)
        #angle = pg.SRTTransform(g.sliceGroup.transform()).getRotation()
        #mimg2.rotate(angle)
        g.cellImg2 = mimg2
        cellGroup.scale(5,5)
        
        ## reposition next to slice schematic
        imgBounds = g.mapRectFromItem(mimg2, mimg2.boundingRect())
        pos = pg.Point(bounds.right()-imgBounds.left(), bounds.bottom()-imgBounds.bottom()) 
        cellGroup.setPos(pos)
    
        ## add scale bar
        sbLength = 50e-6
        g.cellScale = pg.QtGui.QGraphicsLineItem(0.0, 0.0, sbLength, 0.0)
        g.cellScale.setPen(pg.mkPen(color=0.0, width=5))
        g.cellScale.setZValue(10)
        g.cellScale.text = pg.TextItem(u"%d µm" % int(sbLength*1e6), anchor=(0.5, 1), color=(0,0,0))
        g.cellScale.text.setParentItem(g.cellScale)
        g.cellScale.text.setPos(sbLength*0.5, -50e-6/cellScale)
        #g.cellScale = pg.ScaleBar(sbLength)
        g.cellScale.setParentItem(cellGroup)
        corner = mimg2.mapToParent(mimg2.boundingRect()).boundingRect().bottomRight()
        g.cellScale.setPos(corner + pg.Point(-sbLength/2., -sbLength/3.))
    pos = pg.SRTTransform(cd.info()['userTransform']).map(pg.Point(0,0))
    size = pg.Point(30e-6, 30e-6)
    g.cellMarker = pg.QtGui.QGraphicsEllipseItem(pg.QtCore.QRectF(pos-size, pos+size))
    g.cellMarker.setBrush(pg.mkBrush(100,100,255,150))
    g.cellMarker.setPen(pg.mkPen('k', width=0.5))
    g.cellMarker.setParentItem(g.sliceGroup)
    g.cellMarker.setZValue(90)
        
    sites = db.select('map_site_view', ['ProtocolDir', 'HasInput'], where={'CellDir': cd})
    if len(sites) > 0:
        tr = sites[0]['ProtocolDir'].parent().info().get('userTransform', None)
        if tr is None:
            tr = pg.SRTTransform()
        else:
            tr = pg.SRTTransform(tr)
            
        pos = []
        size = sites[0]['ProtocolDir'].info()['Scanner']['spotSize']
        brushes = []
        for site in sites:
            pd = site['ProtocolDir']
            x,y = pd.info()['Scanner']['position']
            p2 = tr.map(pg.Point(x,y))
            pos.append((p2.x(), p2.y()))
            if site['HasInput']:
                brushes.append(pg.mkBrush('w'))
            else:
                brushes.append(pg.mkBrush(None))
        inputMap = pg.ScatterPlotItem(pos=np.array(pos), size=size, brush=brushes, pen=(0,0,0,50), pxMode=False, antialias=True)
        g.sliceGroup.addItem(inputMap)
        g.inputMap = inputMap
        inputMap.setZValue(50)
    
    
    cell = dh
    sl = cell.parent()
    day = sl.parent()
    name = day.shortName() + "_" + sl.shortName() + "_" + cell.shortName()
    rec = db.select('DirTable_Cell', '*', where={'Dir': cd})[0]
    
    name += "\nType: " + str(rec['CellType']) + "   Temp: " + str(rec['Temperature']) + "   Internal: " + str(rec['Internal']) + "   Age:" + str(rec['Age']) + "   Raccess: " + str(rec['AccessResistance'])
    name += "\nDirect Area: %s>0pA %s>20pA %s>100pA" % (str(rec['DirectAreaGt0']), str(rec['DirectAreaGt20']), str(rec['DirectAreaGt100']))
    name += "   Direct n spikes: " + str(rec['DirectNSpikes'])
    name += "\nSpont Ex Decay: %s   Spont In Decay: %s" % (str(rec['SpontExDecay1']), str(rec['SpontInDecay']))
    name += "\nExcitatory input" if (rec['EvokedExDecay'] is not None or rec['EvokedExAmp'] is not None) else ""
    print rec
    #name += '\nDirect Slow Decay: %s %s' % (str(rec['DirectAreaGT0']), str(rec['DirectAreaGT0']))
    
    
    
    g.cellName = pg.TextItem(name, color=(0,0,0))
    g.cellName.setParentItem(g)
    g.cellName.setPos(0, bounds.bottom())
Exemplo n.º 15
0
Arquivo: Imager.py Projeto: ablot/acq4
 def paintEvent(self, event):
     p = QtGui.QPainter(self)
     brush = pg.mkBrush(0.0)
     p.fillRect(self.rect(), brush)
     p.end()
Exemplo n.º 16
0
    pw1.setLabel('left', 'Amplitude', 'A')
    pw1.setLabel('bottom', 'Decay Tau', 's')

    spl2 = Qt.QSplitter()
    spl2.setOrientation(Qt.Qt.Horizontal)
    spl1.addWidget(spl2)

    pw2 = pg.PlotWidget(labels={'bottom': ('time', 's')})
    spl2.addWidget(pw2)

    tab = Qt.QTabWidget()
    spl2.addWidget(tab)

    ## For viewing cell morphology
    gv = pg.GraphicsView()
    gv.setBackgroundBrush(pg.mkBrush('w'))
    image = pg.ImageItem()
    gv.addItem(image)
    gv.enableMouse()
    gv.setAspectLocked(True)
    tab.addTab(gv, 'Morphology')

    ## 3D atlas
    import acq4.analysis.atlas.CochlearNucleus as CN
    atlas = CN.CNAtlasDisplayWidget()
    atlas.showLabel('DCN')
    atlas.showLabel('AVCN')
    atlas.showLabel('PVCN')
    tab.addTab(atlas, 'Atlas')

    atlasPoints = gl.GLScatterPlotItem()
Exemplo n.º 17
0
 def setBrush(self, brush):
     brush = pg.mkBrush(brush)
     self.brush = brush
     for t in self.times:
         t.setBrush(brush)
Exemplo n.º 18
0
def showMap(dh=None):
    """
    Display a graphic of an input map for the currently selected cell
    """
    
    global v, g, atlas
    if dh is None:
        dh = man.currentFile
    db = man.getModule('Data Manager').currentDatabase()
    v.clear()
    
    cd = dh
    sd = cd.parent()
    atlas.loadState(sd)
    
    g = atlas.schematicGraphicsItems(contours=False, sliceScale=10, cellDir=cd)
    v.addItem(g)
    
    cellGroup = pg.ItemGroup()
    g.cellGroup = cellGroup
    cellScale = 10.
    cellGroup.scale(cellScale, cellScale)
    cellGroup.setParentItem(g)
    
    g.atlasScale.hide()
    g.arrowGroup.hide()
    
    ## reposition/rescale atlas group
    b1 = g.atlasGroup.mapRectToParent(g.atlasGroup.childrenBoundingRect())
    b2 = g.sliceClip.mapRectToParent(g.sliceClip.boundingRect())
    g.atlasGroup.setPos(b2.right()-b1.left()+0.001, b2.top()-b1.top())
    
    b1 = g.atlasGroup.mapRectToParent(g.atlasGroup.childrenBoundingRect())    
    bounds = b1 | b2
    
    if cd.exists('morphology.png'):
        ## small image to go over slice schematic
        imgf = cd['morphology.png']
        imgd = pg.colorToAlpha(imgf.read(), np.array([255,255,255]))
        mimg1 = pg.ImageItem(imgd)
        tr = pg.SRTTransform(imgf.info()['userTransform'])
        mimg1.setTransform(tr)
        mimg1.setParentItem(g.sliceGroup)
        mimg1.setZValue(100)
        g.cellImg1 = mimg1
        
        ## larger image to be displayed above
        mimg2 = pg.ImageItem(imgd)
        mimg2.setParentItem(cellGroup)
        mimg2.setTransform(tr * g.sliceGroup.transform())
        mimg2.scale(1.0 / g.sliceScaleFactor, 1.0 / g.sliceScaleFactor)
        #angle = pg.SRTTransform(g.sliceGroup.transform()).getRotation()
        #mimg2.rotate(angle)
        g.cellImg2 = mimg2
        cellGroup.scale(5,5)
        
        ## reposition next to slice schematic
        imgBounds = g.mapRectFromItem(mimg2, mimg2.boundingRect())
        pos = pg.Point(bounds.right()-imgBounds.left(), bounds.bottom()-imgBounds.bottom()) 
        cellGroup.setPos(pos)
    
        ## add scale bar
        sbLength = 50e-6
        g.cellScale = Qt.QGraphicsLineItem(0.0, 0.0, sbLength, 0.0)
        g.cellScale.setPen(pg.mkPen(color=0.0, width=5))
        g.cellScale.setZValue(10)
        g.cellScale.text = pg.TextItem(u"%d µm" % int(sbLength*1e6), anchor=(0.5, 1), color=(0,0,0))
        g.cellScale.text.setParentItem(g.cellScale)
        g.cellScale.text.setPos(sbLength*0.5, -50e-6/cellScale)
        #g.cellScale = pg.ScaleBar(sbLength)
        g.cellScale.setParentItem(cellGroup)
        corner = mimg2.mapToParent(mimg2.boundingRect()).boundingRect().bottomRight()
        g.cellScale.setPos(corner + pg.Point(-sbLength/2., -sbLength/3.))
    pos = pg.SRTTransform(cd.info()['userTransform']).map(pg.Point(0,0))
    size = pg.Point(30e-6, 30e-6)
    g.cellMarker = Qt.QGraphicsEllipseItem(Qt.QRectF(pos-size, pos+size))
    g.cellMarker.setBrush(pg.mkBrush(100,100,255,150))
    g.cellMarker.setPen(pg.mkPen('k', width=0.5))
    g.cellMarker.setParentItem(g.sliceGroup)
    g.cellMarker.setZValue(90)
        
    sites = db.select('map_site_view', ['ProtocolDir', 'HasInput'], where={'CellDir': cd})
    if len(sites) > 0:
        tr = sites[0]['ProtocolDir'].parent().info().get('userTransform', None)
        if tr is None:
            tr = pg.SRTTransform()
        else:
            tr = pg.SRTTransform(tr)
            
        pos = []
        size = sites[0]['ProtocolDir'].info()['Scanner']['spotSize']
        brushes = []
        for site in sites:
            pd = site['ProtocolDir']
            x,y = pd.info()['Scanner']['position']
            p2 = tr.map(pg.Point(x,y))
            pos.append((p2.x(), p2.y()))
            if site['HasInput']:
                brushes.append(pg.mkBrush('w'))
            else:
                brushes.append(pg.mkBrush(None))
        inputMap = pg.ScatterPlotItem(pos=np.array(pos), size=size, brush=brushes, pen=(0,0,0,50), pxMode=False, antialias=True)
        g.sliceGroup.addItem(inputMap)
        g.inputMap = inputMap
        inputMap.setZValue(50)
    
    
    cell = dh
    sl = cell.parent()
    day = sl.parent()
    name = day.shortName() + "_" + sl.shortName() + "_" + cell.shortName()
    rec = db.select('DirTable_Cell', '*', where={'Dir': cd})[0]
    
    name += "\nType: " + str(rec['CellType']) + "   Temp: " + str(rec['Temperature']) + "   Internal: " + str(rec['Internal']) + "   Age:" + str(rec['Age']) + "   Raccess: " + str(rec['AccessResistance'])
    name += "\nDirect Area: %s>0pA %s>20pA %s>100pA" % (str(rec['DirectAreaGt0']), str(rec['DirectAreaGt20']), str(rec['DirectAreaGt100']))
    name += "   Direct n spikes: " + str(rec['DirectNSpikes'])
    name += "\nSpont Ex Decay: %s   Spont In Decay: %s" % (str(rec['SpontExDecay1']), str(rec['SpontInDecay']))
    name += "\nExcitatory input" if (rec['EvokedExDecay'] is not None or rec['EvokedExAmp'] is not None) else ""
    print(rec)
    #name += '\nDirect Slow Decay: %s %s' % (str(rec['DirectAreaGT0']), str(rec['DirectAreaGT0']))
    
    
    
    g.cellName = pg.TextItem(name, color=(0,0,0))
    g.cellName.setParentItem(g)
    g.cellName.setPos(0, bounds.bottom())
Exemplo n.º 19
0
    def update_sequence_analysis(self):
        analysis = self.params['sequence', 'analysis']
        xvals = []
        yvals = []
        noise = []
        brushes = []
        avg_x = []
        avg_y = []
        avg_noise = []

        for i in range(len(self.img_data)):

            img_data = self.img_arrays[i]
            img_t = self.img_data[i][0].xvals('Time')
            base_starti, base_stopi, test_starti, test_stopi, noise_starti, noise_stopi = self.time_indices(
                img_t)
            dff = self.measure_dff(
                img_data, img_t,
                (base_starti, base_stopi, test_starti, test_stopi))

            x = self.seqParams[0][1][i]
            xvals.extend([x] * len(dff))

            yvals.extend(list(dff))

            if analysis in ('SNR', 'noise'):
                noise_dff = self.measure_dff(
                    img_data, img_t,
                    (base_starti, base_stopi, noise_starti, noise_stopi))
                noise.extend(list(noise_dff))
                avg_noise.append(noise_dff.mean())

            color = pg.mkColor(self.seqColors[i])
            color.setAlpha(50)
            brushes.extend([pg.mkBrush(color)] * len(dff))
            avg_x.append(x)
            avg_y.append(dff.mean())

        if analysis == 'SNR':
            noise = np.std(noise)
            yvals = np.array(yvals) / noise
            avg_y = np.array(avg_y) / noise
        elif analysis == 'noise':
            yvals = noise
            avg_y = avg_noise

        self.plt3.clear()
        self.plt3.setLabels(left=analysis)
        if self.seqParams[0][0] is None:
            self.plt3.plot(range(len(xvals)), yvals, pen='w')
        else:
            self.plt3.plot(xvals,
                           yvals,
                           symbol='o',
                           pen=None,
                           symbolBrush=brushes,
                           symbolPen=None)
            self.plt3.plot(avg_x, avg_y, pen='w', antialias=True)

            lin = stats.linregress(avg_x, avg_y)
            self.plt3.setTitle("slope: %0.2g" % lin[0])
Exemplo n.º 20
0
    def mapErrors(self,
                  nSteps=(5, 5, 7),
                  stepSize=(50e-6, 50e-6, 50e-6),
                  padding=60e-6,
                  threshold=0.4,
                  speed='slow',
                  show=False,
                  intermediateDist=60e-6):
        """Move pipette tip randomly to locations in a grid and measure the position error
        at each location.

        All tip locations must be within the field of view.
        """
        startTime = time.time()
        start = np.array(self.dev.globalPosition())
        npts = nSteps[0] * nSteps[1] * nSteps[2]
        inds = np.mgrid[0:nSteps[0], 0:nSteps[1], 0:nSteps[2]].reshape(
            (3, npts)).transpose()
        order = np.arange(npts)
        np.random.shuffle(order)

        err = np.zeros(nSteps + (3, ))

        stepSize = np.array(stepSize)

        if show:
            imv = pg.image()
            mark1 = pg.QtGui.QGraphicsEllipseItem(
                pg.QtCore.QRectF(-5, -5, 10, 10))
            mark1.setBrush(pg.mkBrush(255, 255, 0, 100))
            mark1.setZValue(100)
            imv.addItem(mark1)
            mark2 = pg.QtGui.QGraphicsEllipseItem(
                pg.QtCore.QRectF(-5, -5, 10, 10))
            mark2.setBrush(pg.mkBrush(255, 0, 0, 100))
            mark2.setZValue(100)
            imv.addItem(mark2)

        # loop over all points in random order, and such that we do heavy computation while
        # pipette is moving.
        images = []
        offsets = []
        try:
            with pg.ProgressDialog("Acquiring error map...", 0,
                                   len(order)) as dlg:
                for i in range(len(order) + 1):
                    if i > 0:
                        lastPos = pos
                    if i < len(order):
                        ind = inds[order[i]]
                        pos = start.copy() + (stepSize * ind)

                        # Jump to position + a random 20um offset to avoid hysteresis
                        offset = np.random.normal(size=3)
                        offset *= intermediateDist / (offset**2).sum()**0.5
                        offsets.append(offset)

                        mfut = self.dev._moveToGlobal(pos + offset, speed)
                        ffut = self.dev.scopeDevice().setFocusDepth(
                            pos[2], speed)
                    if i > 0:
                        ind = inds[order[i - 1]]

                        print("Frame: %d %s" % (i - 1, lastPos))
                        err[tuple(ind)] = self.measureError(
                            padding=padding,
                            threshold=threshold,
                            frame=frame,
                            pos=lastPos)
                        print("    error: %s" % err[tuple(ind)])
                        dlg += 1

                        if show:
                            imv.setImage(frame.data()[0])
                            p1 = frame.globalTransform().inverted()[0].map(
                                pg.Vector(lastPos))
                            p2 = frame.globalTransform().inverted()[0].map(
                                pg.Vector(lastPos + err[tuple(ind)]))
                            mark1.setPos(p1.x(), p1.y())
                            mark2.setPos(p2.x(), p2.y())

                    # wait for previous moves to complete
                    mfut.wait(updates=True)
                    ffut.wait(updates=True)

                    # step back to actual target position
                    self.dev._moveToGlobal(pos, speed).wait(updates=True)

                    frame = self.takeFrame()

                    if dlg.wasCanceled():
                        return None
        finally:
            self.dev._moveToGlobal(start, 'fast')
            self.dev.scopeDevice().setFocusDepth(start[2], 'fast')

        self.errorMap = {
            'err': err,
            'nSteps': nSteps,
            'stepSize': stepSize,
            'order': order,
            'inds': inds,
            'offsets': offsets,
            'time': time.time() - startTime,
        }

        filename = self.dev.configFileName('error_map.np')
        np.save(open(filename, 'wb'), self.errorMap)

        return self.errorMap
Exemplo n.º 21
0
 def setBrush(self, brush):
     brush = pg.mkBrush(brush)
     self.brush = brush
     for t in self.times:
         t.setBrush(brush)
Exemplo n.º 22
0
    pw1.setLabel('bottom', 'Decay Tau', 's')

    spl2 = QtGui.QSplitter()
    spl2.setOrientation(QtCore.Qt.Horizontal)
    spl1.addWidget(spl2)

    pw2 = pg.PlotWidget(labels={'bottom': ('time', 's')})
    spl2.addWidget(pw2)
    
    tab = QtGui.QTabWidget()
    spl2.addWidget(tab)
    
    
    ## For viewing cell morphology
    gv = pg.GraphicsView()
    gv.setBackgroundBrush(pg.mkBrush('w'))
    image = pg.ImageItem()
    gv.addItem(image)
    gv.enableMouse()
    gv.setAspectLocked(True)
    tab.addTab(gv, 'Morphology')

    ## 3D atlas
    import acq4.analysis.atlas.CochlearNucleus as CN
    atlas = CN.CNAtlasDisplayWidget()
    atlas.showLabel('DCN')
    atlas.showLabel('AVCN')
    atlas.showLabel('PVCN')
    tab.addTab(atlas, 'Atlas')
    
    atlasPoints = gl.GLScatterPlotItem()