Exemplo n.º 1
0
def baseline(browser):
    """ Subtract a baseline from the currently plotted traces.
    Baseline is the average of all datapoints between the 
    current position of the data cursors. 
    
    Options:
    1) keep original traces intact and create processed copies
    """
    plotWidget = browser.ui.dataPlotsWidget
    toolsWidget = browser.ui.toolStackedWidget   
    c1, c2 = aux.get_cursors(plotWidget) 

    # Check selected options
    for option in toolsWidget.baselineToolOptions:
        if option.isChecked():
            if option.text()=='Keep original data':
                aux.make_data_copy(browser, plotWidget)

    # Get the data now, in case we are working on a copy
    plotWidget.clear()    
    data = aux.get_data(browser)
    
    # Get dt list
    dt = aux.get_attr(plotWidget.plotDataItems, 'dt')[0]

    # Make average between cursors and subract for each trace 
    for item in plotWidget.plotDataItems:
        bsl = np.mean(item.data[c1/dt:c2/dt])
        item.data = item.data - bsl

    # Re-plot data
    pgplot.replot(browser, plotWidget)
    pgplot.replot_cursors(browser, plotWidget)    
Exemplo n.º 2
0
    def func(self, browser):
        """ Subtract a baseline from the currently plotted traces.
        Baseline is the average of all datapoints between the 
        current position of the data cursors. 
    
        Options:
        1) keep original traces intact and create processed copies
        """

        ############################################
        # ANALYSIS FUNCTION

        plotWidget = browser.ui.dataPlotsWidget
        toolsWidget = browser.ui.oneDimToolStackedWidget

        # Copy data if required
        if self.keepData.isChecked():
            aux.make_data_copy(browser, plotWidget)

        # Get dt
        dt = aux.get_attr(plotWidget.plotDataItems, 'dt')[0]

        # Make average between cursors and subract for each trace
        for item in plotWidget.plotDataItems:
            bslData, c1 = aux.get_dataRange(plotWidget, item)
            bsl = np.mean(bslData)
            item.data = item.data - bsl
            item.analysis['baselineStart'] = c1
            item.analysis['baselineEnd'] = c1 + len(bslData)

        # Re-plot data
        pgplot.replot(browser, plotWidget)
Exemplo n.º 3
0
    def func(self, browser):
        """ Subtract a baseline from the currently plotted traces.
        Baseline is the average of all datapoints between the 
        current position of the data cursors. 
    
        Options:
        1) keep original traces intact and create processed copies
        """
    
        ############################################
        # ANALYSIS FUNCTION
        
        plotWidget = browser.ui.dataPlotsWidget
        toolsWidget = browser.ui.oneDimToolStackedWidget   

        # Copy data if required
        if self.keepData.isChecked():
            aux.make_data_copy(browser, plotWidget)
    
        # Get dt
        dt = aux.get_attr(plotWidget.plotDataItems, 'dt')[0]

        # Make average between cursors and subract for each trace 
        for item in plotWidget.plotDataItems:                        
            bslData, c1 = aux.get_dataRange(plotWidget, item)             
            bsl = np.mean(bslData)
            item.data = item.data - bsl
            item.analysis['baselineStart'] = c1 
            item.analysis['baselineEnd'] = c1+len(bslData)
            
        # Re-plot data
        pgplot.replot(browser, plotWidget)     
Exemplo n.º 4
0
def baseline(browser):
    """ Subtract a baseline from the currently plotted traces.
    Baseline is the average of all datapoints between the 
    current position of the data cursors. 
    
    Options:
    1) keep original traces intact and create processed copies
    """
    plotWidget = browser.ui.dataPlotsWidget
    toolsWidget = browser.ui.toolStackedWidget
    c1, c2 = aux.get_cursors(plotWidget)

    # Check selected options
    for option in toolsWidget.baselineToolOptions:
        if option.isChecked():
            if option.text() == 'Keep original data':
                aux.make_data_copy(browser, plotWidget)

    # Get the data now, in case we are working on a copy
    plotWidget.clear()
    data = aux.get_data(browser)

    # Get dt list
    dt = aux.get_attr(plotWidget.plotDataItems, 'dt')[0]

    # Make average between cursors and subract for each trace
    for item in plotWidget.plotDataItems:
        bsl = np.mean(item.data[c1 / dt:c2 / dt])
        item.data = item.data - bsl

    # Re-plot data
    pgplot.replot(browser, plotWidget)
    pgplot.replot_cursors(browser, plotWidget)
Exemplo n.º 5
0
    def func(self, browser):
        """ Calculate average trace from currently plotted traces.

        Options:
        1) create new entry in Working Data tree with the result
        2) plot average with orginal traces
        """
    
        ############################################
        # ANALYSIS FUNCTION
        
        plotWidget = browser.ui.dataPlotsWidget
        toolsWidget = browser.ui.oneDimToolStackedWidget   

        # Clear plot and get data
        plotWidget.clear()    
        data = aux.get_data(browser)
    
        # Get dt and 
        dt = aux.get_attr(plotWidget.plotDataItems, 'dt')[0]

        # Calculate average
        avgData = np.mean(data,0)

        # Check selected options
        for option in self.toolOptions:
            if option.isChecked():
                if option.text()=='Store result':
                    results = []                                    
                    # Get attributes from plotted items
                    item = plotWidget.plotDataItems[0]
                    attrs = item.attrs           
 
                    # Store data     
                    results.append(['avg_trace', avgData, attrs])
                    aux.save_results(browser, item.parent().text(0)+'_average', results) 
             
                if option.text()=='Show traces':
                    pgplot.replot(browser, plotWidget)

        # Plot average
        item = aux.make_h5item('avg', avgData, plotWidget.plotDataItems[0].attrs)
        pgplot.browse_singleData(browser, plotWidget, item, clear=False, color='r')
        if browser.ui.actionShowCursors.isChecked(): pgplot.replot_cursors(browser, plotWidget)      
Exemplo n.º 6
0
def average_traces(browser):
    """ Calculate average trace from currently plotted traces.

    Options:
    1) create new entry in Working Data tree with the result
    2) plot average with orginal traces
    """
    plotWidget = browser.ui.dataPlotsWidget
    toolsWidget = browser.ui.toolStackedWidget
    plotWidget.clear()
    data = aux.get_data(browser)

    # Get dt list (at this stage they will all be the same
    # because otherwise get_data would have thrown an error
    dt = aux.get_attr(plotWidget.plotDataItems, 'dt')[0]

    # Calculate average
    avgData = np.mean(data, 0)

    # Check selected options
    for option in toolsWidget.avgToolOptions:
        if option.isChecked():
            if option.text() == 'Store result':
                results = []
                # Get attributes from plotted items
                item = plotWidget.plotDataItems[0]
                attrs = item.attrs

                # Store data
                results.append(['avg_trace', avgData, attrs])
                aux.save_results(browser,
                                 item.parent().text(0) + '_average', results)

            if option.text() == 'Show traces':
                pgplot.replot(browser, plotWidget)

    # Plot average
    x = np.arange(0, len(avgData) * dt, dt)
    plotWidget.plot(x, avgData, pen=pg.mkPen('#CF1C04', width=2))
    if browser.ui.actionShowCursors.isChecked():
        pgplot.replot_cursors(browser, plotWidget)
Exemplo n.º 7
0
def average_traces(browser):
    """ Calculate average trace from currently plotted traces.

    Options:
    1) create new entry in Working Data tree with the result
    2) plot average with orginal traces
    """
    plotWidget = browser.ui.dataPlotsWidget
    toolsWidget = browser.ui.toolStackedWidget
    plotWidget.clear()
    data = aux.get_data(browser)   

    # Get dt list (at this stage they will all be the same 
    # because otherwise get_data would have thrown an error
    dt = aux.get_attr(plotWidget.plotDataItems, 'dt')[0]
    
    # Calculate average
    avgData = np.mean(data,0)

    # Check selected options
    for option in toolsWidget.avgToolOptions:
        if option.isChecked():
            if option.text()=='Store result':
                results = []                
                # Get attributes from plotted items
                item = plotWidget.plotDataItems[0]
                attrs = item.attrs           
 
                # Store data     
                results.append(['avg_trace', avgData, attrs])
                aux.save_results(browser, item.parent().text(0)+'_average', results) 
            
            if option.text()=='Show traces':
                pgplot.replot(browser, plotWidget)
        
    # Plot average
    x = np.arange(0, len(avgData)*dt, dt)
    plotWidget.plot(x, avgData, pen=pg.mkPen('#CF1C04', width=2))
    if browser.ui.actionShowCursors.isChecked(): pgplot.replot_cursors(browser, plotWidget)      
Exemplo n.º 8
0
    def func(self, browser):
        """ Get rid of spikes in the tracking traces, using the derivative
        to identify them. Substitute the corresponding point in the trace
        with the mean of the previous and following point.        

        Options:
        1) Threshold for the position derivative
        """

        ############################################
        # ANALYSIS FUNCTION      
    
        # Read options
        derivativeThs = float(self.plotWidget.derivativeCursorThsPos)
        nPoints = int(self.nPoints.text())

        # Get plotted data
        items = self.plotWidget.plotDataItems
        
        # Set up detection function
        if derivativeThs<0:         
            comp = lambda a, b: a < b
        else: 
            comp = lambda a, b: a > b
            
        # Go through traces    
        for item in items:
            # Detect spikes
            dtrace = np.diff(item.data)
            i = 0
            while i<len(dtrace):
                if comp(dtrace[i], derivativeThs):
                    item.data[i-nPoints:i+nPoints] = (item.data[i-nPoints]+item.data[i+nPoints])/2.           
                i+=1     

        # Replot data
        pgplot.replot(self.browser, self.plotWidget)
Exemplo n.º 9
0
    def func(self, browser):
        """ Measure selected properties or statistics in the region defined
        by the data cursors.
    
        Rise time and onset are calculated by finding the peak and walking
        back until the limits are crossed. Onset limit is baseline mean; if
        no baseline has been set, it is taken as the mean value of the first
        1 ms of data.
    
        Options:
        1) create new entries in Working Data tree with the results
        """
    
        ############################################
        # ANALYSIS FUNCTION
        
        # Get widgets
        plotWidget = browser.ui.dataPlotsWidget
        toolsWidget = browser.ui.oneDimToolStackedWidget

        # Replot data to clear previous measure plot points
        pgplot.replot(browser, plotWidget)

        # Iterate through traces
        dataMin, dataMax, dataMean, dataMedian, dataSEM = [], [], [], [], []
        dataRiseTime, dataOnset, dataDecay = [], [], []
        for item in plotWidget.plotDataItems:
            
            # Get dt and data range
            dt = item.attrs['dt']
            data, c1, cx1, cx2 = aux.get_dataRange(plotWidget, item, cursors=True)

            # Check baseline
            if 'baselineStart' in item.analysis:
                bsl = 0  # the mean of the baseline will always be 0
            else:
                bsl = np.mean(data[0:round(1./dt)]) 
            
            # Measure selected parameters
            if self.minBox.isChecked():
                y = np.min(data)
                x = np.argmin(data)
                dataMin.append(y)
                aux.plot_point(plotWidget, c1, x, y, dt)                

            if self.maxBox.isChecked():
                y = np.max(data)
                x = np.argmax(data)
                dataMax.append(y)
                aux.plot_point(plotWidget, c1, x, y, dt)  

            if self.meanBox.isChecked():
                y = np.mean(data)
                dataMean.append(y)
                plotWidget.plot([cx1,cx2], [y,y], pen=pg.mkPen('#CF1C04', width=1))  

            if self.medianBox.isChecked():
                y = np.median(data)
                dataMedian.append(y)
                plotWidget.plot([cx1,cx2], [y,y], pen=pg.mkPen('#CF1C04', width=1))  

            if self.semBox.isChecked():
                y = np.std(data)/np.sqrt(len(data))
                dataSEM.append(y)
                plotWidget.plot([cx1,cx2], [y,y], pen=pg.mkPen('#CF1C04', width=1))  

            if self.riseTimeBox.isChecked():
                try:
                    lowerLimit = float(self.riseLowerLimit.text())/100
                    upperLimit = float(self.riseUpperLimit.text())/100
                except ValueError:
                    aux.error_box('Invalid limits')
                    return                                   
                # Get peak
                xPeak, yPeak = self.get_peak(data)
                # Get limits
                lowerLimit = lowerLimit*(yPeak-bsl)+bsl
                upperLimit = upperLimit*(yPeak-bsl)+bsl
                # Find limit crosses
                lowerCrossed, upperCrossed = False, False
                i = 0
                while lowerCrossed==False or upperCrossed==False:
                    if (upperCrossed==False) and self.comp(data[xPeak-i],upperLimit): 
                        xUpper = xPeak-i
                        upperCrossed = True
                    if self.comp(data[xPeak-i], lowerLimit):
                        xLower = xPeak-i
                        lowerCrossed = True
                    i+=1
                dataRiseTime.append((xUpper-xLower)*dt)
                # Plot points 
                aux.plot_point(plotWidget, c1, xLower, lowerLimit, dt) 
                aux.plot_point(plotWidget, c1, xUpper, upperLimit, dt)                 

            if self.onsetBox.isChecked():
                xPeak, yPeak = self.get_peak(data)
                bslCrossed = False
                i = 0
                while bslCrossed==False:
                    if self.comp(data[xPeak-i], bsl):
                        onset = xPeak-i
                        bslCrossed = True
                    i+=1
                aux.plot_point(plotWidget, c1, onset, bsl, dt)
                dataOnset.append(onset*dt)

            if self.decayTimeBox.isChecked():
                try:
                    decayLimit = float(self.decayLimit.text())/100
                except ValueError:
                    aux.error_box('Invalid limits')
                    return       
                xPeak, yPeak = self.get_peak(data)
                yDecay = decayLimit*(yPeak-bsl)+bsl
                decayCrossed = False
                i = 0
                while decayCrossed==False:
                    if self.comp(data[xPeak+i], yDecay):
                        decayTime = xPeak+i
                        decayCrossed = True
                    i+=1
                aux.plot_point(plotWidget, c1, decayTime, yDecay, dt)
                dataDecay.append(decayTime*dt)

        # Store results
        results = []
        if self.storeBox.isChecked():
            if self.minBox.isChecked(): results.append(['Minimum', np.array(dataMin)])
            if self.maxBox.isChecked(): results.append(['Maximum', np.array(dataMax)])
            if self.meanBox.isChecked(): results.append(['Mean', np.array(dataMean)])
            if self.medianBox.isChecked(): results.append(['Median', np.array(dataMedian)])
            if self.semBox.isChecked(): results.append(['SEM', np.array(dataSEM)])
            if self.riseTimeBox.isChecked(): results.append(['RiseTime', np.array(dataRiseTime)])
            if self.onsetBox.isChecked(): results.append(['Onset', np.array(dataOnset)])
            if self.decayTimeBox.isChecked(): results.append(['Decay', np.array(dataDecay)])
            aux.save_results(browser, 'Measurements', results)             
Exemplo n.º 10
0
    def func(self, browser):
        """ Perform some operations on selected traces. 
    
        Options:
        1) keep original traces intact and create processed copies
        2) delete the data points between the cursors
        3) offset the start of the trace by a number of X-axis points (adds NaNs)
        """
    
        ############################################
        # ANALYSIS FUNCTION
        
        # Get widgets
        plotWidget = browser.ui.dataPlotsWidget
        toolsWidget = browser.ui.oneDimToolStackedWidget

        # Get options
        if self.offsetBox.isChecked():
          try:    
            nOffsetPoints = float(self.offsetPoints.text())
          except ValueError:
            aux.error_box('Invalid number of points')
            return

        if self.scaleBox.isChecked():
          try:    
            vScale = float(self.scaleValue.text())
          except ValueError:
            aux.error_box('Invalid scale entry')
            return

        # Copy data if required
        if self.keepData.isChecked():
            aux.make_data_copy(browser, plotWidget)

        # Iterate through traces
        i = 0
        for item in plotWidget.plotDataItems:
            
            # Get dt and data range
            dt = item.attrs['dt']
            data, c1, cx1, cx2 = aux.get_dataRange(plotWidget, item, cursors=True)

            # Check baseline
            if 'baselineStart' in item.analysis:
                bsl = 0  # the mean of the baseline will always be 0
            else:
                bsl = np.mean(item.data[0:round(1./dt)]) 
            
            # Scale data
            if self.scaleBox.isChecked():
                item.data = item.data * vScale

            if self.normalizeBox.isChecked():
                peakDirection = str(self.peakComboBox.currentText())
                if peakDirection=='Positive peak':
                    peak = np.max(data)
                else:
                    peak = -np.min(data)
                item.data = item.data / peak               

            # Delete points
            if self.delPointsBox.isChecked():
                item.data = np.delete(item.data, np.s_[c1:c1+len(data)+1])

            # Add offset
            if self.offsetBox.isChecked():
                offset = int(nOffsetPoints/dt)
                item.data = np.insert(item.data, 0, np.zeros(offset) + np.nan)          

            # Operation against selected data (currently only works for one selected data item)
            if self.selectedBox.isChecked():
                operation = str(self.selectedComboBox.currentText())
                if operation=='Subtract':
                    op = lambda a, b: a - b
                if operation=='Add':
                    op = lambda a, b: a + b
                try:
                    selectedItem = browser.ui.workingDataTree.selectedItems()[i]               
                    item.data = op(item.data, selectedItem.data)                
                except IndexError:
                    aux.error_box('Number of selected data items does not match number of plotted traces')
                    return
            i+=1                     

        # Re-plot data
        pgplot.replot(browser, plotWidget) 
Exemplo n.º 11
0
    def func(self, browser):
        """ Measure selected properties or statistics in the region defined
        by the data cursors.
    
        Rise time and onset are calculated by finding the peak and walking
        back until the limits are crossed. Onset limit is baseline mean; if
        no baseline has been set, it is taken as the mean value of the first
        1 ms of data.
    
        Options:
        1) create new entries in Working Data tree with the results
        """

        ############################################
        # ANALYSIS FUNCTION

        # Get widgets
        plotWidget = browser.ui.dataPlotsWidget
        toolsWidget = browser.ui.oneDimToolStackedWidget

        # Replot data to clear previous measure plot points
        pgplot.replot(browser, plotWidget)

        # Iterate through traces
        dataMin, dataMax, dataMean, dataMedian, dataSEM = [], [], [], [], []
        dataRiseTime, dataOnset, dataDecay = [], [], []
        for item in plotWidget.plotDataItems:

            # Get dt and data range
            dt = item.attrs['dt']
            data, c1, cx1, cx2 = aux.get_dataRange(plotWidget,
                                                   item,
                                                   cursors=True)

            # Check baseline
            if 'baselineStart' in item.analysis:
                bsl = 0  # the mean of the baseline will always be 0
            else:
                bsl = np.mean(data[0:round(1. / dt)])

            # Measure selected parameters
            if self.minBox.isChecked():
                y = np.min(data)
                x = np.argmin(data)
                dataMin.append(y)
                aux.plot_point(plotWidget, c1, x, y, dt)

            if self.maxBox.isChecked():
                y = np.max(data)
                x = np.argmax(data)
                dataMax.append(y)
                aux.plot_point(plotWidget, c1, x, y, dt)

            if self.meanBox.isChecked():
                y = np.mean(data)
                dataMean.append(y)
                plotWidget.plot([cx1, cx2], [y, y],
                                pen=pg.mkPen('#CF1C04', width=1))

            if self.medianBox.isChecked():
                y = np.median(data)
                dataMedian.append(y)
                plotWidget.plot([cx1, cx2], [y, y],
                                pen=pg.mkPen('#CF1C04', width=1))

            if self.semBox.isChecked():
                y = np.std(data) / np.sqrt(len(data))
                dataSEM.append(y)
                plotWidget.plot([cx1, cx2], [y, y],
                                pen=pg.mkPen('#CF1C04', width=1))

            if self.riseTimeBox.isChecked():
                try:
                    lowerLimit = float(self.riseLowerLimit.text()) / 100
                    upperLimit = float(self.riseUpperLimit.text()) / 100
                except ValueError:
                    aux.error_box('Invalid limits')
                    return
                # Get peak
                xPeak, yPeak = self.get_peak(data)
                # Get limits
                lowerLimit = lowerLimit * (yPeak - bsl) + bsl
                upperLimit = upperLimit * (yPeak - bsl) + bsl
                # Find limit crosses
                lowerCrossed, upperCrossed = False, False
                i = 0
                while lowerCrossed == False or upperCrossed == False:
                    if (upperCrossed == False) and self.comp(
                            data[xPeak - i], upperLimit):
                        xUpper = xPeak - i
                        upperCrossed = True
                    if self.comp(data[xPeak - i], lowerLimit):
                        xLower = xPeak - i
                        lowerCrossed = True
                    i += 1
                dataRiseTime.append((xUpper - xLower) * dt)
                # Plot points
                aux.plot_point(plotWidget, c1, xLower, lowerLimit, dt)
                aux.plot_point(plotWidget, c1, xUpper, upperLimit, dt)

            if self.onsetBox.isChecked():
                xPeak, yPeak = self.get_peak(data)
                bslCrossed = False
                i = 0
                while bslCrossed == False:
                    if self.comp(data[xPeak - i], bsl):
                        onset = xPeak - i
                        bslCrossed = True
                    i += 1
                aux.plot_point(plotWidget, c1, onset, bsl, dt)
                dataOnset.append(onset * dt)

            if self.decayTimeBox.isChecked():
                try:
                    decayLimit = float(self.decayLimit.text()) / 100
                except ValueError:
                    aux.error_box('Invalid limits')
                    return
                xPeak, yPeak = self.get_peak(data)
                yDecay = decayLimit * (yPeak - bsl) + bsl
                decayCrossed = False
                i = 0
                while decayCrossed == False:
                    if self.comp(data[xPeak + i], yDecay):
                        decayTime = xPeak + i
                        decayCrossed = True
                    i += 1
                aux.plot_point(plotWidget, c1, decayTime, yDecay, dt)
                dataDecay.append(decayTime * dt)

        # Store results
        results = []
        if self.storeBox.isChecked():
            if self.minBox.isChecked():
                results.append(['Minimum', np.array(dataMin)])
            if self.maxBox.isChecked():
                results.append(['Maximum', np.array(dataMax)])
            if self.meanBox.isChecked():
                results.append(['Mean', np.array(dataMean)])
            if self.medianBox.isChecked():
                results.append(['Median', np.array(dataMedian)])
            if self.semBox.isChecked():
                results.append(['SEM', np.array(dataSEM)])
            if self.riseTimeBox.isChecked():
                results.append(['RiseTime', np.array(dataRiseTime)])
            if self.onsetBox.isChecked():
                results.append(['Onset', np.array(dataOnset)])
            if self.decayTimeBox.isChecked():
                results.append(['Decay', np.array(dataDecay)])
            aux.save_results(browser, 'Measurements', results)
Exemplo n.º 12
0
    def func(self, browser):
        """ Perform some operations on selected traces. 
    
        Options:
        1) keep original traces intact and create processed copies
        2) delete the data points between the cursors
        3) offset the start of the trace by a number of X-axis points (adds NaNs)
        """

        ############################################
        # ANALYSIS FUNCTION

        # Get widgets
        plotWidget = browser.ui.dataPlotsWidget
        toolsWidget = browser.ui.oneDimToolStackedWidget

        # Get options
        if self.offsetBox.isChecked():
            try:
                nOffsetPoints = float(self.offsetPoints.text())
            except ValueError:
                aux.error_box('Invalid number of points')
                return

        if self.scaleBox.isChecked():
            try:
                vScale = float(self.scaleValue.text())
            except ValueError:
                aux.error_box('Invalid scale entry')
                return

        # Copy data if required
        if self.keepData.isChecked():
            aux.make_data_copy(browser, plotWidget)

        # Iterate through traces
        i = 0
        for item in plotWidget.plotDataItems:

            # Get dt and data range
            dt = item.attrs['dt']
            data, c1, cx1, cx2 = aux.get_dataRange(plotWidget,
                                                   item,
                                                   cursors=True)

            # Check baseline
            if 'baselineStart' in item.analysis:
                bsl = 0  # the mean of the baseline will always be 0
            else:
                bsl = np.mean(item.data[0:round(1. / dt)])

            # Scale data
            if self.scaleBox.isChecked():
                item.data = item.data * vScale

            if self.normalizeBox.isChecked():
                peakDirection = str(self.peakComboBox.currentText())
                if peakDirection == 'Positive peak':
                    peak = np.max(data)
                else:
                    peak = -np.min(data)
                item.data = item.data / peak

            # Delete points
            if self.delPointsBox.isChecked():
                item.data = np.delete(item.data, np.s_[c1:c1 + len(data) + 1])

            # Add offset
            if self.offsetBox.isChecked():
                offset = int(nOffsetPoints / dt)
                item.data = np.insert(item.data, 0, np.zeros(offset) + np.nan)

            # Operation against selected data (currently only works for one selected data item)
            if self.selectedBox.isChecked():
                operation = str(self.selectedComboBox.currentText())
                if operation == 'Subtract':
                    op = lambda a, b: a - b
                if operation == 'Add':
                    op = lambda a, b: a + b
                try:
                    selectedItem = browser.ui.workingDataTree.selectedItems(
                    )[i]
                    item.data = op(item.data, selectedItem.data)
                except IndexError:
                    aux.error_box(
                        'Number of selected data items does not match number of plotted traces'
                    )
                    return
            i += 1

        # Re-plot data
        pgplot.replot(browser, plotWidget)
Exemplo n.º 13
0
    def func(self, browser):
        """ Fit data traces within cursor-defined range
    
        Options:
        1) Equation
        2) Initial guesses
        """

        ############################################
        # ANALYSIS FUNCTION

        # Get widgets
        plotWidget = browser.ui.dataPlotsWidget
        toolsWidget = browser.ui.oneDimToolStackedWidget

        # Replot data to clear previous measure plot points
        pgplot.replot(browser, plotWidget)

        # Get parent text of plotted items
        try:
            parentText = plotWidget.plotDataItems[0].parent().text(
                0)  # Assumes all plotted data have the same parent
        except AttributeError:  # Parent = None
            parentText = 'Data'

        # Get current function
        currentFuncmap = self.dataFit.fitfuncmap[str(
            self.comboBox.currentText())]

        # Read initial guesses
        pInit = []
        try:
            nParam = len(currentFuncmap[2])
            for n in range(nParam):
                pInit.append(float(self.p[n].text()))
        except ValueError:
            aux.error_box('Invalid value in initial guess')
            return

        # Fit data
        fitResults, fitTraces, fitTracesAttrs = [], [], []
        for item in plotWidget.plotDataItems:

            # Get data range to fit
            dt = item.attrs['dt']
            fitTracesAttrs.append(item.attrs)
            yData, c1, cx1, cx2 = aux.get_dataRange(plotWidget,
                                                    item,
                                                    cursors=True)
            xRange = pgplot.make_xvector(yData, dt) + cx1
            self.dataFit.c1 = cx1

            # Fit
            func = currentFuncmap[0]
            fitParams = self.dataFit.fit(func, xRange, yData, pInit)
            fitResults.append(fitParams)
            print fitParams

            # Plot fitted function over trace
            if self.extendBox.isChecked():
                xRange = pgplot.make_xvector(item.data, dt)
                #xRange = np.arange(plotWidget.viewBox.viewRange()[0][0], plotWidget.viewBox.viewRange()[0][1], dt)
            fittedTrace = func(xRange, *fitParams)
            plotWidget.plot(xRange, fittedTrace, pen=pg.mkPen('r', width=1))
            fitTraces.append(fittedTrace)

        # Store results
        if self.storeBox.isChecked():
            fitResults = np.array(fitResults)
            results = []
            for n in range(np.shape(fitResults)[1]):
                results.append([str(self.plabels[n].text()), fitResults[:, n]])
            for n in range(len(fitTraces)):
                results.append(
                    ['fitTraces_' + str(n), fitTraces[n], fitTracesAttrs[n]])
            aux.save_results(browser, parentText + '_fit', results)
Exemplo n.º 14
0
    def func(self, browser):
        """ Fit data traces within cursor-defined range
    
        Options:
        1) Equation
        2) Initial guesses
        """
    
        ############################################
        # ANALYSIS FUNCTION
        
        # Get widgets
        plotWidget = browser.ui.dataPlotsWidget
        toolsWidget = browser.ui.oneDimToolStackedWidget

        # Replot data to clear previous measure plot points
        pgplot.replot(browser, plotWidget)
    
        # Get parent text of plotted items
        try:
            parentText = plotWidget.plotDataItems[0].parent().text(0) # Assumes all plotted data have the same parent
        except AttributeError:   # Parent = None
            parentText = 'Data'

        # Get current function
        currentFuncmap = self.dataFit.fitfuncmap[str(self.comboBox.currentText())]

        # Read initial guesses
        pInit = []
        try:        
            nParam = len(currentFuncmap[2])
            for n in range(nParam): pInit.append(float(self.p[n].text()))
        except ValueError:
            aux.error_box('Invalid value in initial guess')
            return              

        # Fit data
        fitResults, fitTraces, fitTracesAttrs = [], [], []
        for item in plotWidget.plotDataItems:  

            # Get data range to fit        
            dt = item.attrs['dt']
            fitTracesAttrs.append(item.attrs)
            yData, c1, cx1, cx2 = aux.get_dataRange(plotWidget, item, cursors=True)
            xRange = pgplot.make_xvector(yData, dt)+cx1
            self.dataFit.c1 = cx1   

            # Fit
            func = currentFuncmap[0]
            fitParams = self.dataFit.fit(func, xRange, yData, pInit) 
            fitResults.append(fitParams)
            print fitParams            
        
            # Plot fitted function over trace
            if self.extendBox.isChecked():
                xRange = pgplot.make_xvector(item.data, dt)
                #xRange = np.arange(plotWidget.viewBox.viewRange()[0][0], plotWidget.viewBox.viewRange()[0][1], dt)
            fittedTrace = func(xRange, *fitParams)
            plotWidget.plot(xRange, fittedTrace, pen=pg.mkPen('r', width=1))
            fitTraces.append(fittedTrace)

        # Store results
        if self.storeBox.isChecked():
            fitResults = np.array(fitResults)
            results = []
            for n in range(np.shape(fitResults)[1]):    
                results.append([str(self.plabels[n].text()), fitResults[:,n]])
            for n in range(len(fitTraces)):
                results.append(['fitTraces_'+str(n), fitTraces[n], fitTracesAttrs[n]])     
            aux.save_results(browser, parentText+'_fit', results)