Esempio n. 1
0
    def __init__(self, plot, **opts):
        opts['type'] = 'bool'
        opts['value'] = True
        if not 'name' in opts.keys():
            opts['name'] = 'Region'
        if 'color' in opts:
            opts['color'] = pg.mkColor(opts['color']).setAlpha(50)
        else:
            opts['color'] = pg.mkColor((255,0,0,50))
            
        parameterTypes.GroupParameter.__init__(self, **opts)


        self.addChild({'name':'Start', 'type':'float', 'value':opts.get('startValue', 0), 'suffix':'s', 'siPrefix':True, 'step':0.1, 'dec':True})
        self.addChild({'name':'End', 'type':'float', 'value': opts.get('endValue', 0.05), 'suffix':'s', 'siPrefix':True, 'step':0.1, 'dec':True})
        self.addChild({'name':'Color', 'type':'color', 'value':opts['color']})
        self.addChild({'name':'Display', 'type':'bool', 'value':True})

        self.rgn = pg.LinearRegionItem(brush=self.child('Color').value())
        self.rgn.setRegion([self.child('Start').value(), self.child('End').value()])
        self.plot = plot
        self.plot.addItem(self.rgn)

        self.child('Start').sigValueChanged.connect(self.regionParamChanged)
        self.child('End').sigValueChanged.connect(self.regionParamChanged)
        self.rgn.sigRegionChangeFinished.connect(self.updateRegionParams)
        self.child('Color').sigValueChanged.connect(self.colorChanged)
        self.child('Display').sigValueChanged.connect(self.displayToggled)
Esempio n. 2
0
    def plotTimeline(self, plot):
        """Create a timeline showing scan mirror usage by each program 
        component.
        """
        self.clearTimeline()
        numSamples = self.program.numSamples
        sampleRate = self.program.sampleRate
        components = self.program.components

        time = np.linspace(0, (numSamples-1) / sampleRate, numSamples)
        for i, component in enumerate(components):
            scanMask = component.scanMask()
            laserMask = component.laserMask()
            color = pg.mkColor((i, len(components)*1.3))
            fill = pg.mkColor(color)
            fill.setAlpha(50)
            plot.addLegend(offset=(-10, 10))
            item = plot.plot(time, scanMask, pen=color, fillLevel=0, fillBrush=fill, name=component.name)
            item.setZValue(i)
            self.masks.append(item)

            fill.setAlpha(100)
            item = plot.plot(time, laserMask, pen=None, fillLevel=0, fillBrush=fill)
            item.setZValue(i+0.5)
            self.masks.append(item)
Esempio n. 3
0
def addLabel(info=None):
    global labelInfo
    create = False
    if info is None:
        create = True
        l = ui.labelSpin.value()
        if l in labelInfo:
            return
        info = {
            'visible': True,
            'name': 'label',
            'color': pg.intColor(len(labelInfo), 16),
            'id': l
        }
    else:
        info = info.copy()
        info['color'] = pg.mkColor(info['color'])

    l = info['id']
    item = Qt.QTreeWidgetItem([str(l), info['name'], ''])
    item.setFlags(item.flags() | Qt.Qt.ItemIsEditable
                  | Qt.Qt.ItemIsUserCheckable)
    if info['visible']:
        item.setCheckState(0, Qt.Qt.Checked)
    else:
        item.setCheckState(0, Qt.Qt.Unchecked)
    btn = pg.ColorButton(color=info['color'])
    ui.labelTree.addTopLevelItem(item)
    ui.labelTree.setItemWidget(item, 2, btn)
    labelInfo[l] = {'item': item, 'btn': btn}
    btn.sigColorChanged.connect(itemChanged)
    btn.sigColorChanging.connect(imageChanged)

    if create:
        writeMeta()
Esempio n. 4
0
def addLabel(info=None):
    global labelInfo
    create = False
    if info is None:
        create = True
        l = ui.labelSpin.value()
        if l in labelInfo:
            return
        info = {
            'visible': True,
            'name': 'label',
            'color': pg.intColor(len(labelInfo), 16),
            'id': l
        }
    else:
        info = info.copy()
        info['color'] = pg.mkColor(info['color'])
    
    l = info['id']
    item = QtGui.QTreeWidgetItem([str(l), info['name'], ''])
    item.setFlags(item.flags() | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsUserCheckable)
    if info['visible']:
        item.setCheckState(0, QtCore.Qt.Checked)
    else:
        item.setCheckState(0, QtCore.Qt.Unchecked)
    btn = pg.ColorButton(color=info['color'])
    ui.labelTree.addTopLevelItem(item)
    ui.labelTree.setItemWidget(item, 2, btn)
    labelInfo[l] = {'item': item, 'btn': btn}
    btn.sigColorChanged.connect(itemChanged)
    btn.sigColorChanging.connect(imageChanged)
    
    if create:
        writeMeta()
Esempio n. 5
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)
    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])
Esempio n. 7
0
    def roi_changed(self, roi):
        if self.ignore_roi_change:
            return

        # Update other ROI to match
        roi1, roi2 = self.rois
        try:
            if roi is not None:
                self.ignore_roi_change = True
                other_roi = roi2 if roi is roi1 else roi1
                pos1 = roi.pos()
                pos2 = other_roi.pos()
                pos2.setY(pos1.y())
                other_roi.setPos(pos2)
                other_roi.setSize(roi.size())
        finally:
            self.ignore_roi_change = False

        for item in self.plt1_items:
            self.plt1.removeItem(item)

        for i, img_data in enumerate(self.img_arrays):
            color = self.seqColors[i]
            color2 = pg.mkColor(color)
            color2.setAlpha(40)

            rgn1 = roi1.getArrayRegion(img_data, self.img1,
                                       axes=(2, 3)).mean(axis=2).mean(axis=2)
            rgn2 = roi2.getArrayRegion(img_data, self.img1,
                                       axes=(2, 3)).mean(axis=2).mean(axis=2)
            dif = rgn1 - rgn2

            difmean = dif.mean(axis=0)
            baseline = np.median(difmean[:10])
            # plot individual examples only for last parameter
            if i == len(self.img_arrays) - 1:
                for j in range(dif.shape[0]):
                    offset = baseline - np.median(dif[j, :10])
                    self.plt1_items.append(
                        self.plt1.plot(self.img_t,
                                       dif[j] + offset,
                                       pen=color2,
                                       antialias=True))
            # plot average
            self.plt1_items.append(
                self.plt1.plot(self.img_t, difmean, pen=color, antialias=True))
            self.plt1_items[-1].setZValue(10)

        self.update_sequence_analysis()
    def roi_changed(self, roi):
        if self.ignore_roi_change:
            return
        
        # Update other ROI to match
        roi1, roi2 = self.rois
        try:
            if roi is not None:
                self.ignore_roi_change = True
                other_roi = roi2 if roi is roi1 else roi1
                pos1 = roi.pos()
                pos2 = other_roi.pos()
                pos2.setY(pos1.y())
                other_roi.setPos(pos2)
                other_roi.setSize(roi.size())            
        finally:
            self.ignore_roi_change = False
        
        
        for item in self.plt1_items:
            self.plt1.removeItem(item)

        
        for i, img_data in enumerate(self.img_arrays):
            color = self.seqColors[i]
            color2 = pg.mkColor(color)
            color2.setAlpha(40)

            rgn1 = roi1.getArrayRegion(img_data, self.img1, axes=(2, 3)).mean(axis=2).mean(axis=2)
            rgn2 = roi2.getArrayRegion(img_data, self.img1, axes=(2, 3)).mean(axis=2).mean(axis=2)
            dif = rgn1 - rgn2
            
            difmean = dif.mean(axis=0)
            baseline = np.median(difmean[:10])
            # plot individual examples only for last parameter
            if i == len(self.img_arrays)-1:
                for j in range(dif.shape[0]):
                    offset = baseline - np.median(dif[j, :10])
                    self.plt1_items.append(self.plt1.plot(self.img_t, dif[j] + offset, pen=color2, antialias=True))
            # plot average
            self.plt1_items.append(self.plt1.plot(self.img_t, difmean, pen=color, antialias=True))
            self.plt1_items[-1].setZValue(10)
            
        self.update_sequence_analysis()
Esempio n. 9
0
    def updateParam(self, param, mode):
        param.blockSignals(
            True)  # Never trigger callbacks because of color changes
        try:
            if mode == 'fixed':
                param.setReadonly(False)
                bg = (200, 200, 255)
            elif mode == 'autoFixable':
                param.child('fixed').setValue(False)
                param.child('fixed').setReadonly(True)
                bg = (200, 230, 230)
            elif mode == 'incomplete':
                param.setReadonly(True)
                param.child('fixed').setReadonly(False)
                bg = (255, 255, 200)
            elif mode == 'unconstrained':
                bg = (255, 200, 200)
            elif mode == 'auto':
                bg = (200, 255, 200)

            for item in param.items:
                item.setBackground(0, pg.mkColor(bg))
        finally:
            param.blockSignals(False)
Esempio n. 10
0
    def _load_data(self, seqDir):
        man = getManager()
        model = man.dataModel

        # read all image data
        self.img_data = model.buildSequenceArray(
            seqDir, lambda dh: dh['Camera']['frames.ma'].read(),
            join=False).asarray()
        seqParams = list(model.listSequenceParams(seqDir).items())
        if self.img_data.ndim == 1:
            self.img_data = self.img_data[np.newaxis, :]
            seqParams.insert(0, (None, [0]))

        transpose = seqParams[0][0] == ('protocol', 'repetitions')
        if transpose:
            self.img_data = np.swapaxes(self.img_data, 0, 1)
            seqParams = seqParams[::-1]
        self.seqParams = seqParams

        if seqParams[0][0] is None:
            self.seqColors = [pg.mkColor('w')]
        else:
            nSeq = len(seqParams[0][1])
            if nSeq == 2:
                # Special case: add in difference between two sequence trials
                seqParams[0] = (seqParams[0][0], list(seqParams[0][1]) +
                                [np.mean(seqParams[0][1])])
                nSeq = 3
                img_data = np.empty((3, ) + self.img_data.shape[1:],
                                    dtype=self.img_data.dtype)
                img_data[:2] = self.img_data
                for i in range(img_data.shape[1]):
                    minlen = min(self.img_data[0, i].shape[0],
                                 self.img_data[1, i].shape[0])
                    img_data[2, i] = self.img_data[0, i][:minlen].copy()
                    img_data[2, i]._data = self.img_data[
                        0, i][:minlen].asarray().astype(
                            'float') - self.img_data[1, i][:minlen].asarray()
                self.img_data = img_data

            self.seqColors = [pg.intColor(i, nSeq * 1.6) for i in range(nSeq)]

        # cull out truncated recordings :(
        self.img_data = [[
            d['Time':0:200e-3] for d in row if d.xvals('Time')[-1] > 150e-3
        ] for row in self.img_data]

        # crop / concatenate
        img_len = min(
            [min([d.shape[0] for d in row]) for row in self.img_data])
        self.img_data = [[d[:img_len] for d in row] for row in self.img_data]
        self.img_arrays = [
            np.concatenate([d.asarray()[np.newaxis, ...] for d in row], axis=0)
            for row in self.img_data
        ]

        # average
        self.img_mean = [img_arr.mean(axis=0) for img_arr in self.img_arrays]

        for p in self.clamp_plots:
            self.plt2.removeItem(p)

        # read all clamp data
        first_subdir = seqDir[seqDir.ls()[0]]
        clamp_name = 'Clamp1'
        if not first_subdir[clamp_name + '.ma'].exists():
            clamp_name = 'Clamp2'

        clamp_file = first_subdir[clamp_name + '.ma']
        if clamp_file.exists():
            self.clamp_mode = model.getClampMode(clamp_file)
            chan = 'command' if self.clamp_mode == 'VC' else 'primary'
            self.clamp_data = model.buildSequenceArray(
                seqDir,
                lambda dh: dh[clamp_name + '.ma'].read()['Channel':chan],
                join=False).asarray()
            if self.clamp_data.ndim == 1:
                self.clamp_data = self.clamp_data[np.newaxis, :]
            if transpose:
                self.clamp_data = np.swapaxes(self.clamp_data, 0, 1)

            self.plt2.setLabels(left=('Vm', 'V'))

            for i in range(self.clamp_data.shape[0]):
                for j in range(self.clamp_data.shape[1]):
                    trace = self.clamp_data[i, j]
                    pen = self.seqColors[i]
                    p = self.plt2.plot(trace.xvals('Time'),
                                       trace.asarray(),
                                       antialias=True,
                                       pen=pen)
                    self.clamp_plots.append(p)
            self.plt2.show()
        else:
            self.clamp_mode = None
            self.plt2.hide()

        self.img_t = self.img_data[0][0].xvals('Time')

        self.img1.setImage(self.img_mean[-1].mean(axis=0))

        self.roi_changed(None)
        self.time_rgn_changed(None)
        self.update_sequence_analysis()
Esempio n. 11
0
man = acq4.Manager.getManager()
initialized = False

def __reload__(old):  ## re-use existing objects if module is reloaded
    global initialized, w, v, atlas
    initialized = True
    w = old['w']
    v = old['v']
    atlas = old['atlas']

if not initialized:
    atlas = cn.CochlearNucleus()
    w = pg.GraphicsWindow()
    w.setRenderHints(Qt.QPainter.Antialiasing | Qt.QPainter.TextAntialiasing | Qt.QPainter.SmoothPixmapTransform)
    w.setBackground(pg.mkColor('w'))
    v = w.addViewBox()
    v.setAspectLocked()
    v.invertY()
    w.show()
    initialized = True

def show(dh=None):
    """
    Display a graphic of the currently selected slice / cell
    """
    
    global v, g, atlas
    if dh is None:
        dh = man.currentFile
    v.clear()
    def _load_data(self, seqDir):
        man = getManager()
        model = man.dataModel

        # read all image data
        self.img_data = model.buildSequenceArray(
            seqDir, 
            lambda dh: dh['Camera']['frames.ma'].read(),
            join=False).asarray()
        seqParams = list(model.listSequenceParams(seqDir).items())
        if self.img_data.ndim == 1:
            self.img_data = self.img_data[np.newaxis, :]
            seqParams.insert(0, (None, [0]))

        transpose = seqParams[0][0] == ('protocol', 'repetitions')
        if transpose:
            self.img_data = np.swapaxes(self.img_data, 0, 1)
            seqParams = seqParams[::-1]
        self.seqParams = seqParams

        if seqParams[0][0] is None:
            self.seqColors = [pg.mkColor('w')]
        else:
            nSeq = len(seqParams[0][1])
            if nSeq == 2:
                # Special case: add in difference between two sequence trials
                seqParams[0] = (seqParams[0][0], list(seqParams[0][1]) + [np.mean(seqParams[0][1])])
                nSeq = 3
                img_data = np.empty((3,) + self.img_data.shape[1:], dtype=self.img_data.dtype)
                img_data[:2] = self.img_data
                for i in range(img_data.shape[1]):
                    minlen = min(self.img_data[0,i].shape[0], self.img_data[1,i].shape[0])
                    img_data[2,i] = self.img_data[0,i][:minlen].copy()
                    img_data[2,i]._data = self.img_data[0,i][:minlen].asarray().astype('float') - self.img_data[1,i][:minlen].asarray()
                self.img_data = img_data
                
                
            self.seqColors = [pg.intColor(i, nSeq*1.6) for i in range(nSeq)]

        # cull out truncated recordings :(
        self.img_data = [[d['Time':0:200e-3] for d in row if d.xvals('Time')[-1] > 150e-3] for row in self.img_data]

        # crop / concatenate
        img_len = min([min([d.shape[0] for d in row]) for row in self.img_data])
        self.img_data = [[d[:img_len] for d in row] for row in self.img_data]
        self.img_arrays = [np.concatenate([d.asarray()[np.newaxis, ...] for d in row], axis=0) for row in self.img_data]

        # average
        self.img_mean = [img_arr.mean(axis=0) for img_arr in self.img_arrays]

        for p in self.clamp_plots:
            self.plt2.removeItem(p)
            
        # read all clamp data
        first_subdir = seqDir[seqDir.ls()[0]]
        clamp_name = 'Clamp1'
        if not first_subdir[clamp_name + '.ma'].exists():
            clamp_name = 'Clamp2'
        
        clamp_file = first_subdir[clamp_name + '.ma']
        if clamp_file.exists():
            self.clamp_mode = model.getClampMode(clamp_file)
            chan = 'command' if self.clamp_mode == 'VC' else 'primary'
            self.clamp_data = model.buildSequenceArray(
                seqDir, 
                lambda dh: dh[clamp_name + '.ma'].read()['Channel': chan],
                join=False).asarray()
            if self.clamp_data.ndim == 1:
                self.clamp_data = self.clamp_data[np.newaxis, :]
            if transpose:
                self.clamp_data = np.swapaxes(self.clamp_data, 0, 1)

            self.plt2.setLabels(left=('Vm', 'V'))
            
            for i in range(self.clamp_data.shape[0]):
                for j in range(self.clamp_data.shape[1]):
                    trace = self.clamp_data[i,j]
                    pen = self.seqColors[i]
                    p = self.plt2.plot(trace.xvals('Time'), trace.asarray(), antialias=True, pen=pen)
                    self.clamp_plots.append(p)
            self.plt2.show()
        else:
            self.clamp_mode = None
            self.plt2.hide()

        self.img_t = self.img_data[0][0].xvals('Time')

        self.img1.setImage(self.img_mean[-1].mean(axis=0))

        self.roi_changed(None)
        self.time_rgn_changed(None)
        self.update_sequence_analysis()
Esempio n. 13
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])
Esempio n. 14
0
man = acq4.Manager.getManager()
initialized = False

def __reload__(old):  ## re-use existing objects if module is reloaded
    global initialized, w, v, atlas
    initialized = True
    w = old['w']
    v = old['v']
    atlas = old['atlas']

if not initialized:
    atlas = cn.CochlearNucleus()
    w = pg.GraphicsWindow()
    w.setRenderHints(pg.QtGui.QPainter.Antialiasing | pg.QtGui.QPainter.TextAntialiasing | pg.QtGui.QPainter.SmoothPixmapTransform)
    w.setBackground(pg.mkColor('w'))
    v = w.addViewBox()
    v.setAspectLocked()
    v.invertY()
    w.show()
    initialized = True

def show(dh=None):
    """
    Display a graphic of the currently selected slice / cell
    """
    
    global v, g, atlas
    if dh is None:
        dh = man.currentFile
    v.clear()