Пример #1
0
def ppr_peak():
    # Get function values
    decay_func = stf.leastsq(0)

    # Create time from fit start to next peak
    x = np.arange(stf.get_fit_start(), stf.peak_index())

    # Create fitted curve up until peak
    trace = [(decay_func['Offset'] + decay_func['Amp_0'] * np.exp(-(ind/10.0)/decay_func['Tau_0'])) for ind, val in enumerate(x)]
    
    # Find peak value
    peak_val = stf.get_peak()-stf.get_base()
    print('The measured peak is {0} pA'.format(peak_val))

    # Find value of fit at peak
    fit_peak = trace[-1] - stf.get_base()
    print('Tau is {0} pA'.format(decay_func['Tau_0']))
    print('The fitted peak is {0} pA'.format(fit_peak))
    print('The baseline is {0} pA'.format(stf.get_base()))
    # stf.new_window(trace)

    final_peak = peak_val - fit_peak
    print('The final peak is {0} pA'.format(final_peak))

    return True
Пример #2
0
def preliminary():
    """Creates a preliminary template"""
    stf.set_peak_start(209900)
    stf.set_peak_end(210500)
    stf.set_fit_start(209900)
    stf.set_fit_end(210400)
    stf.set_peak_mean(3)
    stf.set_base_start(209600)
    stf.set_base_end(209900)
    stf.measure()
    return stf.leastsq(5)
Пример #3
0
def final():
    """Creates a final template"""
    stf.set_peak_start(100)
    stf.set_peak_end(599)
    stf.set_fit_start(100)
    stf.set_fit_end(599)
    stf.set_peak_mean(3)
    stf.set_base_start(0)
    stf.set_base_end(100)
    stf.measure()
    return stf.leastsq(5)
Пример #4
0
def preliminary():
    """Creates a preliminary template"""
    stf.set_peak_start(209900)
    stf.set_peak_end(210500)
    stf.set_fit_start(209900)
    stf.set_fit_end(210400)
    stf.set_peak_mean(3)
    stf.set_base_start(209600)
    stf.set_base_end(209900)
    stf.measure()
    return stf.leastsq(5)
Пример #5
0
def final():
    """Creates a final template"""
    stf.set_peak_start(100)
    stf.set_peak_end(599)
    stf.set_fit_start(100)
    stf.set_fit_end(599)
    stf.set_peak_mean(3)
    stf.set_base_start(0)
    stf.set_base_end(100)
    stf.measure()
    return stf.leastsq(5)
Пример #6
0
def final():
    """
    Sets peak, base and fit cursors around a synaptic event
    and performs a biexponetial fit to create the final template
    for event detection.
    """
    stf.base.cursor_index = (000, 100)
    stf.peak.cursor_index = (100, 599)
    stf.fit.cursor_index = (100, 599)

    stf.set_peak_mean(3)

    stf.measure()  # update cursors

    return stf.leastsq(5)
Пример #7
0
def preliminary():
    """
    Sets peak, base and fit cursors around a synaptic event
    and performs a biexponential fit to create the preliminary template
    for event detection.
    """
    stf.base.cursor_index = (209600, 209900)
    stf.peak.cursor_index = (209900, 210500)
    stf.fit.cursor_index = (209900, 210400)

    stf.set_peak_mean(3)

    stf.measure()  # update cursors

    return stf.leastsq(5)
Пример #8
0
def fit_experiment(params, pulse_length, function_to_fit):

    num_sweeps = stf.get_size_channel()
    stf.set_channel(0)
    stf.set_trace(0)

    #jjm_analysis.set_params(params);
    #stf.measure();
    #this is in samples
    #peak_index = stf.peak_index();
    #stf.set_fit_start(peak_index, is_time=False);
    #fit_start_time = peak_index*stf.get_sampling_interval();
    #stf.set_fit_end(fit_start_time+pulse_length-(10*stf.get_sampling_interval()), is_time=True);
    #fit_func = stf.leastsq(function_to_fit);
    #fit_func['Baseline(pA)']=stf.get_base();
    #fit_df = pd.DataFrame(fit_func, index=[0]);

    fits = []
    traces = []
    for x in range(0, num_sweeps):
        stf.set_trace(x)
        jjm_analysis.set_params(params)
        stf.measure()
        #this is in samples
        peak_index = stf.peak_index()
        stf.set_fit_start(peak_index, is_time=False)
        fit_start_time = peak_index * stf.get_sampling_interval()
        stf.set_fit_end(fit_start_time + pulse_length -
                        (10 * stf.get_sampling_interval()),
                        is_time=True)
        sweep_fit = stf.leastsq(function_to_fit)
        sweep_fit['Baseline(pA)'] = stf.get_base()
        fits.append(sweep_fit)
        traces.append(x)

    fit_df = pd.DataFrame(fits)
    return (fit_df)
Пример #9
0
def glu_iv(pulses=13, subtract_base=True):
    """Calculates an iv from a repeated series of fast application and
    voltage pulses. 

    Keyword arguments:
    pulses        -- Number of pulses for the iv.
    subtract_base -- If True (default), baseline will be subtracted.
    
    Returns:
    True if successful.
    """

    # Some ugly definitions for the time being
    # Cursors are in ms here.
    gFitEnd = 330.6  # fit end cursor is variable
    gFSelect = 0  # Monoexp
    gDictSize = stf.leastsq_param_size(
        gFSelect) + 2  # Parameters, chisqr, peak value
    gBaseStart = 220.5  # Start and end of the baseline before the control pulse, in ms
    gBaseEnd = 223.55
    gPeakStart = 223.55  # Start and end of the peak cursors for the control pulse, in ms
    gPeakEnd = 253.55

    if (gDictSize < 0):
        print('Couldn\'t retrieve function id=%d, aborting now.' % gFSelect)
        return False

    if (not (stf.check_doc())):
        print('Couldn\'t find an open file; aborting now.')
        return False

    # analyse iv, subtract baseline if requested:
    ivtools.analyze_iv(pulses)
    if (subtract_base == True):
        if (not (stf.set_base_start(gBaseStart, True))): return False
        if (not (stf.set_base_end(gBaseEnd, True))): return False
        stf.measure()
        stf.select_all()
        stf.subtract_base()

    # set cursors:
    if (not (stf.set_peak_start(gPeakStart, True))): return False
    if (not (stf.set_peak_end(gPeakEnd, True))): return False
    if (not (stf.set_base_start(gBaseStart, True))): return False
    if (not (stf.set_base_end(gBaseEnd, True))): return False
    if (not (stf.set_fit_end(gFitEnd, True))): return False

    if (not (stf.set_peak_mean(3))): return False
    if (not (stf.set_peak_direction("both"))): return False

    # A list for dictionary keys and values:
    dict_keys = []
    dict_values = np.empty((gDictSize, stf.get_size_channel()))
    firstpass = True
    for n in range(0, stf.get_size_channel()):
        if (stf.set_trace(n) == False):
            print('Couldn\'t set a new trace; aborting now.')
            return False

        print('Analyzing trace %d of %d' % (n + 1, stf.get_size_channel()))
        # set the fit window cursors:
        if (not (stf.set_fit_start(stf.peak_index()))): return False

        # Least-squares fitting:
        p_dict = stf.leastsq(gFSelect)

        if (p_dict == 0):
            print('Couldn\'t perform a fit; aborting now.')
            return False

        # Create an empty list:
        tempdict_entry = []
        row = 0
        for k, v in p_dict.iteritems():
            if (firstpass == True):
                dict_keys.append(k)
            dict_values[row][n] = v
            row = row + 1

        if (firstpass):
            dict_keys.append("Peak amplitude")
        dict_values[row][n] = stf.get_peak() - stf.get_base()

        firstpass = False

    retDict = dict()
    # Create the dictionary for the table:
    entry = 0
    for elem in dict_keys:
        retDict[elem] = dict_values[entry].tolist()
        entry = entry + 1

    return stf.show_table_dictlist(retDict)
Пример #10
0
def timeconstants(fitwindow, pulsewindow, ichannel=0, vchannel=1):
    """
    Compute and plot decay time constants

    Parameters
    ----------
    fitwindow : (float, float), optional
        Window for fitting time constant (time in ms from beginning of sweep)
        None for current cursor settings. Default: None
    pulsewindow : (float, float), optional
        Window for voltage pulse measurement (time in ms from beginning of sweep)
        None for current cursor settings. Default: None
    ichannel : int, optional
        current channel number. Default: 0
    vchannel : int, optional
        voltage channel number. Default: 1

    Returns
    -------
    v_commands : numpy.ndarray
        Command voltages
    taus : numpy.ndarray
        Time constants
    """

    import stf
    if not stf.check_doc():
        return None

    nchannels = stf.get_size_recording()
    if nchannels < 2:
        sys.stderr.write(
            "Function requires 2 channels (0: current; 1: voltage)\n")
        return

    dt = stf.get_sampling_interval()

    v_commands = []
    taus = []

    fig = stf.mpl_panel(figsize=(12, 8)).fig
    fig.clear()
    gs = gridspec.GridSpec(4, 8)
    ax_currents = stfio_plot.StandardAxis(fig,
                                          gs[:3, :4],
                                          hasx=False,
                                          hasy=False)
    ax_voltages = stfio_plot.StandardAxis(fig,
                                          gs[3:, :4],
                                          hasx=False,
                                          hasy=False,
                                          sharex=ax_currents)
    for ntrace in range(stf.get_size_channel()):
        stf.set_trace(ntrace)
        stf.set_channel(ichannel)
        trace = stf.get_trace()

        ax_currents.plot(np.arange(len(trace)) * dt, trace)

        if fitwindow is not None:
            stf.fit.cursor_time = fitwindow
        res = stf.leastsq(0, False)
        taus.append(res['Tau_0'])

        # Measure pulse amplitude
        stf.set_channel(vchannel)
        trace = stf.get_trace()
        ax_voltages.plot(np.arange(len(trace)) * dt, trace)

        stf.set_peak_direction("up")
        stf.set_peak_mean(-1)
        if pulsewindow is not None:
            stf.peak.cursor_time = pulsewindow
        stf.measure()
        v_commands.append(stf.peak.value)

    stfio_plot.plot_scalebars(ax_currents,
                              xunits=stf.get_xunits(),
                              yunits=stf.get_yunits(channel=ichannel))
    stfio_plot.plot_scalebars(ax_voltages,
                              xunits=stf.get_xunits(),
                              yunits=stf.get_yunits(channel=vchannel))

    v_commands = np.array(v_commands)
    taus = np.array(taus)

    ax_taus = plot_iv(taus, v_commands, "ms", stf.get_yunits(channel=vchannel),
                      fig, 122)

    # Reset peak computation to single sampling point
    stf.set_peak_mean(1)

    # Reset active channel
    stf.set_channel(ichannel)

    # Compute conductances:
    stf.show_table_dictlist({
        "Voltage ({0})".format(stf.get_yunits(channel=vchannel)):
        v_commands.tolist(),
        "Taus (ms)":
        taus.tolist(),
    })

    return v_commands, taus
Пример #11
0
    def psc_analysis(self):

        self.psc_data = self.metadata[self.metadata.recording_type == 'psc']
        self.psc_data['ch1_self_psc'] = [False for _ in self.psc_data]
        self.psc_data['ch1_other_psc'] = [False for _ in self.psc_data]
        self.psc_data['ch2_self_psc'] = [False for _ in self.psc_data]
        self.psc_data['ch2_other_psc'] = [False for _ in self.psc_data]
        self.psc_data['ch1_self_tau'] = [False for _ in self.psc_data]
        self.psc_data['ch1_other_tau'] = [False for _ in self.psc_data]
        self.psc_data['ch2_self_tau'] = [False for _ in self.psc_data]
        self.psc_data['ch2_other_tau'] = [False for _ in self.psc_data]

        for idx, abffiles in enumerate(self.psc_data):
            # Initialize Channel 1
            data = AbfFile(abffiles, self.path)
            stf.new_window_matrix(data.channel1.signal)

            # Cell 1 to Self
            advance_var = input("Cell 1: Select the traces to use, set the Peak, Baseline, and fit cursors for self.\n"
                                "If no connection exists, type 'no connection'\n"
                                "Type 'y' to advance to the next trace:\t")

            while advance_var is not 'y' or advance_var is not 'no connection':
                advance_var = input("You must type 'y' or 'no connection' to advance:\t")

            if advance_var == 'no connection':
                self.psc_data['ch1_self_psc'][idx] = None
                self.psc_data['ch1_self_tau'][idx] = None
            else:
                peaks = np.array(
                    [np.min(trace[stf.get_peak_start():stf.get_peak_end()]) for trace in data.channel1.signal]
                )
                bases = np.array(
                    [np.mean(trace[stf.get_base_start():stf.get_base_end()]) for trace in data.channel1.signal]
                )
                peak = np.mean(peaks - bases)
                fit = stf.leastsq(0)
                self.psc_data['ch1_self_psc'][idx] = peak
                self.psc_data['ch1_self_tau'][idx] = fit['Tau_0']

            # Cell 2 to Cell 1
            advance_var = input("Great, now do the same for Cell 2 onto Cell 1.\n"
                                "Type 'y' to advance to the next trace:\t")

            while advance_var is not 'y' or advance_var is not 'no connection':
                advance_var = input("You must type 'y' or 'no connection' to advance:\t")

            if advance_var == 'no connection':
                self.psc_data['ch2_other_psc'][idx] = None
                self.psc_data['ch2_other_tau'][idx] = None
            else:
                peaks = np.array(
                    [np.min(trace[stf.get_peak_start():stf.get_peak_end()]) for trace in data.channel1.signal]
                )
                bases = np.array(
                    [np.mean(trace[stf.get_base_start():stf.get_base_end()]) for trace in data.channel1.signal]
                )
                peak = np.mean(peaks - bases)
                fit = stf.leastsq(0)
                self.psc_data['ch2_other_psc'][idx] = peak
                self.psc_data['ch2_other_tau'][idx] = fit['Tau_0']

            # Initialize Channel 2
            data = AbfFile(abffiles, self.path)
            stf.new_window_matrix(data.channel1.signal)

            # Cell 2 to Self
            advance_var = input("Cell 2: Select the traces to use, set the Peak, Baseline, and fit cursors for self.\n"
                                "If no connection exists, type 'no connection'\n"
                                "Type 'y' to advance to the next trace:\t")

            while advance_var is not 'y' or advance_var is not 'no connection':
                advance_var = input("You must type 'y' or 'no connection' to advance:\t")

            if advance_var == 'no connection':
                self.psc_data['ch2_self_psc'][idx] = None
                self.psc_data['ch2_self_tau'][idx] = None
            else:
                peaks = np.array([np.min(trace[stf.get_peak_start():stf.get_peak_end()]) for trace in data.channel1.signal])
                bases = np.array(
                    [np.mean(trace[stf.get_base_start():stf.get_base_end()]) for trace in data.channel1.signal])
                peak = np.mean(peaks - bases)
                fit = stf.leastsq(0)
                self.psc_data['ch2_self_psc'][idx] = peak
                self.psc_data['ch2_self_tau'][idx] = fit['Tau_0']

            # Cell 2 to Cell 1
            advance_var = input("Great, now do the same for Cell 2 onto Cell 1.\n"
                                "Type 'y' to advance to the next trace:\t")

            while advance_var is not 'y' or advance_var is not 'no connection':
                advance_var = input("You must type 'y' or 'no connection' to advance:\t")

            if advance_var == 'no connection':
                self.psc_data['ch1_other_psc'][idx] = None
                self.psc_data['ch1_other_tau'][idx] = None
            else:
                peaks = np.array([np.min(trace[stf.get_peak_start():stf.get_peak_end()]) for trace in data.channel1.signal])
                bases = np.array(
                    [np.mean(trace[stf.get_base_start():stf.get_base_end()]) for trace in data.channel1.signal])
                peak = np.mean(peaks - bases)
                fit = stf.leastsq(0)
                self.psc_data['ch1_other_psc'][idx] = peak
                self.psc_data['ch1_other_tau'][idx] = fit['Tau_0']

        self.psc_data.to_csv(os.path.join(self.path, '.stimpy', 'psc_data.csv'))
Пример #12
0
def glu_iv( pulses = 13, subtract_base=True ):
    """Calculates an iv from a repeated series of fast application and
    voltage pulses. 

    Keyword arguments:
    pulses        -- Number of pulses for the iv.
    subtract_base -- If True (default), baseline will be subtracted.
    
    Returns:
    True if successful.
    """

    # Some ugly definitions for the time being
    # Cursors are in ms here.
    gFitEnd = 330.6 # fit end cursor is variable
    gFSelect  =  0 # Monoexp
    gDictSize =  stf.leastsq_param_size( gFSelect ) + 2 # Parameters, chisqr, peak value
    gBaseStart  = 220.5 # Start and end of the baseline before the control pulse, in ms
    gBaseEnd    = 223.55
    gPeakStart  = 223.55 # Start and end of the peak cursors for the control pulse, in ms
    gPeakEnd = 253.55 
    
    if ( gDictSize < 0 ):
        print('Couldn\'t retrieve function id=%d, aborting now.'%gFSelect)
        return False        
    
    if ( not(stf.check_doc()) ):
        print('Couldn\'t find an open file; aborting now.')
        return False
    
    # analyse iv, subtract baseline if requested:
    ivtools.analyze_iv( pulses )
    if ( subtract_base == True ):
        if ( not(stf.set_base_start( gBaseStart, True )) ): return False
        if ( not(stf.set_base_end( gBaseEnd, True )) ): return False
        stf.measure()
        stf.select_all()
        stf.subtract_base()
    
    # set cursors:
    if ( not(stf.set_peak_start( gPeakStart, True )) ): return False
    if ( not(stf.set_peak_end( gPeakEnd, True )) ): return False
    if ( not(stf.set_base_start( gBaseStart, True )) ): return False
    if ( not(stf.set_base_end( gBaseEnd, True )) ): return False
    if ( not(stf.set_fit_end( gFitEnd, True )) ): return False
    
    if ( not(stf.set_peak_mean( 3 )) ): return False
    if ( not(stf.set_peak_direction( "both" )) ): return False

    # A list for dictionary keys and values:
    dict_keys = []
    dict_values = np.empty( (gDictSize, stf.get_size_channel()) )
    firstpass = True
    for n in range( 0, stf.get_size_channel() ):
        if ( stf.set_trace( n ) == False ):
            print('Couldn\'t set a new trace; aborting now.')
            return False
        
        print('Analyzing trace %d of %d'%( n+1, stf.get_size_channel() ) )
        # set the fit window cursors:
        if ( not(stf.set_fit_start( stf.peak_index() )) ): return False
        
        # Least-squares fitting:
        p_dict = stf.leastsq( gFSelect )
        
        if ( p_dict == 0 ):
            print('Couldn\'t perform a fit; aborting now.')
            return False
            
        # Create an empty list:
        tempdict_entry = []
        row = 0
        for k, v in p_dict.iteritems():
            if ( firstpass == True ):
                dict_keys.append( k )
            dict_values[row][n] = v 
            row = row+1
        
        if ( firstpass ):
            dict_keys.append( "Peak amplitude" )
        dict_values[row][n] = stf.get_peak()-stf.get_base()
        
        firstpass = False
    
    retDict = dict()
    # Create the dictionary for the table:
    entry = 0
    for elem in dict_keys:
        retDict[ elem ] = dict_values[entry].tolist()
        entry = entry+1
   
    return stf.show_table_dictlist( retDict )
Пример #13
0
def timeconstants(fitwindow, pulsewindow, ichannel=0, vchannel=1):
    """
    Compute and plot decay time constants

    Parameters
    ----------
    fitwindow : (float, float), optional
        Window for fitting time constant (time in ms from beginning of sweep)
        None for current cursor settings. Default: None
    pulsewindow : (float, float), optional
        Window for voltage pulse measurement (time in ms from beginning of sweep)
        None for current cursor settings. Default: None
    ichannel : int, optional
        current channel number. Default: 0
    vchannel : int, optional
        voltage channel number. Default: 1

    Returns
    -------
    v_commands : numpy.ndarray
        Command voltages
    taus : numpy.ndarray
        Time constants
    """

    import stf
    if not stf.check_doc():
        return None

    nchannels = stf.get_size_recording()
    if nchannels < 2:
        sys.stderr.write(
            "Function requires 2 channels (0: current; 1: voltage)\n")
        return

    dt = stf.get_sampling_interval()

    v_commands = []
    taus = []

    fig = stf.mpl_panel(figsize=(12, 8)).fig
    fig.clear()
    gs = gridspec.GridSpec(4, 8)
    ax_currents = stfio_plot.StandardAxis(
        fig, gs[:3, :4], hasx=False, hasy=False)
    ax_voltages = stfio_plot.StandardAxis(
        fig, gs[3:, :4], hasx=False, hasy=False, sharex=ax_currents)
    for ntrace in range(stf.get_size_channel()):
        stf.set_trace(ntrace)
        stf.set_channel(ichannel)
        trace = stf.get_trace()

        ax_currents.plot(np.arange(len(trace))*dt, trace)

        if fitwindow is not None:
            stf.fit.cursor_time = fitwindow
        res = stf.leastsq(0, False)
        taus.append(res['Tau_0'])

        # Measure pulse amplitude
        stf.set_channel(vchannel)
        trace = stf.get_trace()
        ax_voltages.plot(np.arange(len(trace))*dt, trace)

        stf.set_peak_direction("up")
        stf.set_peak_mean(-1)
        if pulsewindow is not None:
            stf.peak.cursor_time = pulsewindow
        stf.measure()
        v_commands.append(stf.peak.value)

    stfio_plot.plot_scalebars(
        ax_currents, xunits=stf.get_xunits(),
        yunits=stf.get_yunits(channel=ichannel))
    stfio_plot.plot_scalebars(
        ax_voltages, xunits=stf.get_xunits(),
        yunits=stf.get_yunits(channel=vchannel))

    v_commands = np.array(v_commands)
    taus = np.array(taus)

    ax_taus = plot_iv(
        taus, v_commands, "ms",
        stf.get_yunits(channel=vchannel), fig, 122)

    # Reset peak computation to single sampling point
    stf.set_peak_mean(1)

    # Reset active channel
    stf.set_channel(ichannel)

    # Compute conductances:
    stf.show_table_dictlist({
        "Voltage ({0})".format(
            stf.get_yunits(channel=vchannel)): v_commands.tolist(),
        "Taus (ms)": taus.tolist(),
    })

    return v_commands, taus