示例#1
0
def peakscale():
    """
    Scale the selected traces in the currently active channel to their mean peak amplitude. 

    """

    # Measure baseline in selected traces
    base = []
    for i in stf.get_selected_indices():
        stf.set_trace(i)
        base.append(stf.get_base())

    # Subtract baseline from selected traces
    stf.subtract_base()

    # Measure peak amplitudes in baseline-subtracted traces
    stf.select_all()
    peak = []
    for i in stf.get_selected_indices():
        stf.set_trace(i)
        peak.append(stf.get_peak())

    # Calculate scale factor to make peak equal to the mean peak amplitude
    scale_factor = peak / np.mean(peak)

    # Scale the traces and apply offset equal to the mean baseline
    scaled_traces = [
        stf.get_trace(i) / scale_factor[i] + np.mean(base)
        for i in stf.get_selected_indices()
    ]

    # Close window of baseline-subtracted traces
    stf.close_this()

    return stf.new_window_list(scaled_traces)
示例#2
0
def peakalign():
    """
    Shift the selected traces in the currently active channel to align the peaks. 

    """

    # Measure peak indices in the selected traces
    pidx = []
    for i in stf.get_selected_indices():
        stf.set_trace(i)
        pidx.append(stf.peak_index())

    # Find the earliest peak
    pref = min(pidx)

    # Align the traces
    j = 0
    shifted_traces = []
    for i in stf.get_selected_indices():
        stf.set_trace(i)
        shift = int(pref - pidx[j])
        shifted_traces.append(np.roll(stf.get_trace(), shift))
        j += 1

    return stf.new_window_list(shifted_traces)
示例#3
0
def normalize():
    """
    Normalize to the peak amplitude of the selected trace and 
    scale all other traces in the currently active channel by 
    the same factor. 

    Ensure that you subtract the baseline before normalizing
    """

    # Find index of the selected trace
    idx = stf.get_selected_indices()
    if len(idx) > 1:
        raise ValueError('More than one trace was selected')
    elif len(idx) < 1:
        raise ValueError('Select one trace to subtract from the others')

    # Measure peak amplitude in the selected trace
    stf.set_trace(idx[0])
    refval = np.abs(stf.get_peak())

    # Apply normalization
    scaled_traces = [
        stf.get_trace(i) / refval for i in range(stf.get_size_channel())
    ]

    return stf.new_window_list(scaled_traces)
示例#4
0
def risealign():
    """
    Shift the selected traces in the currently active channel to align to the rise. 

    """

    # Measure peak indices in the selected traces
    rtidx = []
    for i in stf.get_selected_indices():
        stf.set_trace(i)
        rtidx.append(stf.rtlow_index())

    # Find the earliest peak
    rtref = min(rtidx)

    # Align the traces
    j = 0
    shifted_traces = []
    for i in stf.get_selected_indices():
        stf.set_trace(i)
        shift = int(round(rtref - rtidx[j]))
        shifted_traces.append(np.roll(stf.get_trace(), shift))
        j += 1

    return stf.new_window_list(shifted_traces)
示例#5
0
文件: cshl.py 项目: neurodroid/CSHL
def plot_traces(plotwindow=None, ichannel=0, vchannel=1):
    """
    Show traces in a figure

    Parameters
    ----------
    plotwindow : (float, float), optional
        Plot window (in ms from beginning of trace)
        None for whole trace. Default: None
    ichannel : int, optional
        current channel number. Default: 0
    vchannel : int, optional
        voltage channel number. Default: 1
    """

    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()

    fig = stf.mpl_panel(figsize=(12, 8)).fig
    fig.clear()
    gs = gridspec.GridSpec(4, 1)
    ax_currents = stfio_plot.StandardAxis(
        fig, gs[:3, 0], hasx=False, hasy=False)
    ax_voltages = stfio_plot.StandardAxis(
        fig, gs[3:, 0], hasx=False, hasy=False, sharex=ax_currents)
    if plotwindow is not None:
        istart = int(plotwindow[0]/dt)
        istop = int(plotwindow[1]/dt)
    else:
        istart = 0
        istop = None

    for ntrace in range(stf.get_size_channel()):
        stf.set_trace(ntrace)
        stf.set_channel(ichannel)
        trace = stf.get_trace()[istart:istop]

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

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

    # Reset active channel
    stf.set_channel(ichannel)

    stfio_plot.plot_scalebars(
        ax_currents, xunits=stf.get_xunits(), yunits=stf.get_yunits(channel=0))
    stfio_plot.plot_scalebars(
        ax_voltages, xunits=stf.get_xunits(), yunits=stf.get_yunits(channel=1))
def find_sample_points_of_detected_events(whole_trace_file,
                                          extracted_events_file, sweep_num):
    """takes the window of detected events from stimfit and, for each events, runs through the full trace to pull out time (in samples) of event
	"""
    #open and load trace from whole file
    stf.file_open(whole_trace_file)
    stf.set_trace(sweep_num)
    whole_trace = stf.get_trace()
    sampling_interval = stf.get_sampling_interval()

    #open extracted events file
    stf.file_open(extracted_events_file)

    time_points = []
    for trace in range(stf.get_size_channel()):
        stf.set_trace(trace)
        trace_to_search = stf.get_trace(trace)
        # run find trace with updated search index
        # start at sample = 0 for first run through
        if len(time_points) == 0:
            sample_start = 0
        else:
            sample_start = int(time_points[len(time_points) - 1] /
                               sampling_interval)

        output_index = sub_func_find_trace(trace_to_search, whole_trace,
                                           sample_start)
        time_point = output_index * sampling_interval
        time_points.append(time_point)

    return (time_points)
示例#7
0
def jjm_count(start, delta, threshold=0, up=True, trace=None, mark=True):
	""" Counts the number of events (e.g action potentials (AP)) in the current trace.
	Arguments:
	start -- starting time (in ms) to look for events.
	delta -- time interval (in ms) to look for events.
	threshold -- (optional) detection threshold (default = 0).
	up -- (optional) True (default) will look for upward events, False downwards.
	trace -- (optional) zero-based index of the trace in the current channel,
	if None, the current trace is selected.
	mark -- (optional) if True (default), set a mark at the point of threshold crossing
	Returns:
	An integer with the number of events.
	Examples:
	count_events(500,1000) returns the number of events found between t=500 ms and t=1500 ms
	above 0 in the current trace and shows a stf marker.
	count_events(500,1000,0,False,-10,i) returns the number of events found below -10 in the 
	trace i and shows the corresponding stf markers. """
	# sets the current trace or the one given in trace.
	if trace is None:
		sweep = stf.get_trace_index()
	else:
		if type(trace) !=int:
			print "trace argument admits only integers"
			return False
		sweep = trace
	# set the trace described in sweep
	stf.set_trace(sweep)
	# transform time into sampling points
	dt = stf.get_sampling_interval()
	pstart = int( round(start/dt) )
	pdelta = int( round(delta/dt) )
	# select the section of interest within the trace
	selection = stf.get_trace()[pstart:(pstart+pdelta)]
	# algorithm to detect events
	EventCounter,i = 0,0 # set counter and index to zero
	# list of sample points
	sample_points = []
	# choose comparator according to direction:
	if up:
		comp = lambda a, b: a > b
	else:
		comp = lambda a, b: a < b
	# run the loop
	while i<len(selection):
		if comp(selection[i],threshold):
			EventCounter +=1
			if mark:
				sample_point = pstart+i; 
				sample_points.append(sample_point); 
				stf.set_marker(pstart+i, selection[i])
			while i<len(selection) and comp(selection[i],threshold):
				i+=1 # skip values if index in bounds AND until the value is below/above threshold again
		else:
			i+=1
	
	time_points = [sample_point*dt for sample_point in sample_points];
	return (EventCounter, sample_points, time_points)
示例#8
0
文件: analysis.py 项目: acp29/penn
def subtract_base():
    """
    """
    subtracted_traces = []
    for i in range(stf.get_size_channel()):
        stf.set_trace(i)
        subtracted_traces.append(stf.get_trace() - stf.get_base())
    stf.new_window_list(subtracted_traces)

    return
示例#9
0
文件: analysis.py 项目: acp29/penn
def yvalue(origin, interval):

    stf.set_fit_start(origin, True)
    stf.set_fit_end(origin + interval, True)
    stf.measure()
    x = int(stf.get_fit_end(False))
    y = []
    for i in range(stf.get_size_channel()):
        stf.set_trace(i)
        y.append(stf.get_trace(i)[x])

    return y
def analyze_file(baseline_start, baseline_end, cap_trans_start, cap_trans_end,
                 amplitude, EPSC1_s, EPSC1_e, EPSC2_s, EPSC2_e, sweep_start,
                 sweep_end):
    """inputs: (baseline_start, baseline_end, cap_trans_start, cap_trans_end, amplitude, EPSC1_s, EPSC1_e, EPSC2_s, EPSC2_e, sweep_start, sweep_end)
	output: numpy array where 1st column is capacitance transient amplitude, 2nd is series resistance, 3rd is 1st EPSC, 4th is 2nd EPCSC
	also writes output to .csv file"""

    num_sweeps = stf.get_size_channel()
    print('there are')
    print(num_sweeps)
    print('sweeps in recording')
    print('analyzing sweeps')
    print(sweep_start)
    print('to')
    print(sweep_end)
    sweeps_to_analyze = sweep_end - sweep_start

    #create array for results
    data_array = np.zeros((sweeps_to_analyze + 1, 4))

    y = 0
    for x in range(sweep_start - 1, sweep_end):
        #moves to next trace
        stf.set_trace(x)

        [cap_trans_amplitude,
         series_resistance] = jjm_resistance(baseline_start, baseline_end,
                                             cap_trans_start, cap_trans_end,
                                             amplitude)
        data_array[y][0] = cap_trans_amplitude
        data_array[y][1] = series_resistance
        EPSC_1 = jjm_peak(baseline_start, baseline_end, EPSC1_s, EPSC1_e)
        data_array[y][2] = EPSC_1
        EPSC_2 = jjm_peak(baseline_start, baseline_end, EPSC2_s, EPSC2_e)
        data_array[y][3] = EPSC_2
        pp_40 = float(float(EPSC_2) / float(EPSC_1))

        y += 1

    #print first few entries to check accuracy
    print(data_array[:3])

    #make csv file with data
    file_name = stf.get_filename()
    #expt = file_name[-12:].rstrip('.abf');
    np.savetxt(file_name + '_stimfitanalysis.csv',
               data_array,
               delimiter=',',
               newline='\n')

    return (data_array)
    def get_time_points(self):
        #need to get specified sweep of the whole trace to an array
        stf.file_open(self.whole_trace_file)
        stf.set_trace(self.sweep_number)
        trace_array = stf.get_trace()

        #runs program to find sample indicies of selected EPSCs and converts to times
        stf.file_open(self.event_file)
        event_samples_list = find_sample_points_of_detected_events(trace_array)
        sampling_interval = stf.get_sampling_interval()
        event_times_list = [(sample * sampling_interval)
                            for sample in event_samples_list]

        return (event_times_list)
示例#12
0
def get_amplitude(base, peak, delta, trace=None):
    """ Calculates the amplitude deviation (peak-base) in units of the Y-axis

    Arguments:
    base        -- Starting point (in ms) of the baseline cursor.
    peak        -- Starting point (in ms) of the peak cursor.
    delta       -- Time interval to calculate baseline/find the peak.
    trace       -- Zero-based index of the trace to be processed, if None then current
                    trace is computed.


    Returns:
    A float with the variation of the amplitude. False if

    Example:
    get_amplitude(980,1005,10,i) returns the variation of the Y unit of the
        trace i between
    peak value (10050+10) msec and baseline (980+10) msec
    """

    # sets the current trace or the one given in trace
    if trace is None:
        sweep = stf.get_trace_index()
    else:
        if type(trace) != int:
            print('trace argument admits only intergers')
            return False
        sweep = trace


    # set base cursors:
    if not(stf.set_base_start(base, True)): 
        return False # out-of range
    if not(stf.set_base_end(base+delta, True)): 
        return False

    # set peak cursors:
    if not(stf.set_peak_start(peak, True)): 
        return False # out-of range
    if not(stf.set_peak_end(peak+delta, True)): 
        return False

    # update measurements
    stf.set_trace(sweep)

    amplitude = stf.get_peak()-stf.get_base()

    return amplitude
示例#13
0
文件: spells.py 项目: yueqiw/stimfit
def get_amplitude(base, peak, delta, trace=None):
    """ Calculates the amplitude deviation (peak-base) in units of the Y-axis

    Arguments:
    base        -- Starting point (in ms) of the baseline cursor.
    peak        -- Starting point (in ms) of the peak cursor.
    delta       -- Time interval to calculate baseline/find the peak.
    trace       -- Zero-based index of the trace to be processed, if None then current
                    trace is computed.


    Returns:
    A float with the variation of the amplitude. False if

    Example:
    get_amplitude(980,1005,10,i) returns the variation of the Y unit of the
        trace i between
    peak value (10050+10) msec and baseline (980+10) msec
    """

    # sets the current trace or the one given in trace
    if trace is None:
        sweep = stf.get_trace_index()
    else:
        if type(trace) != int:
            print('trace argument admits only intergers')
            return False
        sweep = trace

    # set base cursors:
    if not (stf.set_base_start(base, True)):
        return False  # out-of range
    if not (stf.set_base_end(base + delta, True)):
        return False

    # set peak cursors:
    if not (stf.set_peak_start(peak, True)):
        return False  # out-of range
    if not (stf.set_peak_end(peak + delta, True)):
        return False

    # update measurements
    stf.set_trace(sweep)

    amplitude = stf.get_peak() - stf.get_base()

    return amplitude
def return_base_for_file(start_sweep, end_sweep):

    #dict_to_return = {}
    baselines = []
    for sweep in range(start_sweep, end_sweep):
        stf.set_trace(sweep)
        stf.set_base_start(100, is_time=True)
        stf.set_base_end(125, is_time=True)
        baselines.append(stf.get_base())
    file_baseline = np.mean(baselines)
    #dict_to_return[stf.get_filename()] = file_baseline

    #df_out = pd.DataFrame(dict_to_return)
    #file_name = stf.get_filename()
    #df_out.to_excel('/Users/johnmarshall/Documents/Analysis/eCB_paper/'+str(file_name)+'holding_current.xlsx')

    return (file_baseline)
示例#15
0
def batch_integration():
    """
    Perform batch integration between the decay/fit cursors of all traces
    in the active window
    """
    n = int(stf.get_fit_end() + 1 - stf.get_fit_start())
    x = [i * stf.get_sampling_interval() for i in range(n)]
    dictlist = []
    for i in range(stf.get_size_channel()):
        stf.set_trace(i)
        y = stf.get_trace()[int(stf.get_fit_start()):int(stf.get_fit_end() +
                                                         1)]
        auc = np.trapz(y - stf.get_base(), x)
        dictlist += [("%i" % (i + 1), auc)]
    retval = dict(dictlist)
    stf.show_table(retval, "Area Under Curve")
    stf.set_trace(0)

    return
示例#16
0
def get_amplitude_select_NMDA(amplithresh):
    stf.unselect_all()
    stf.set_peak_direction('both')
    # total number of traces
    traces = stf.get_size_channel()
    selectedtraces, i = 0, 0

    while i < traces:
        stf.set_trace(i)
        amplitude = stf.get_peak() - stf.get_base()
        if amplitude < amplithresh and amplitude > 0:
            # print(i)
            stf.select_trace(i)
            i += 1
            selectedtraces += 1
        else:
            i += 1

    return selectedtraces
def compile_amplitudes_in_trace():

    # for each trace in file run find_baseline_amplitudes
    output_array = np.array(['baseline', 'peak', 'peak_from_baseline'])

    for trace in range(stf.get_size_channel()):

        stf.set_trace(trace)

        fba_output = find_baseline_amplitude(10)

        output_array = np.vstack([output_array, fba_output])

    output_df = pd.DataFrame(output_array[1:],
                             columns=output_array[0],
                             dtype=float)

    output_df.to_excel(str(stf.get_filename()[-40:-3]) + '.xlsx')

    return (output_df)
示例#18
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)
def scan_through_train(start_params, train_increment, num_stims, train_trace):
    """scans through a tran of length "num_stims" in time increments of "train_increment", saves peak 
	amplitudes to an array peak_values (1st output) and sweep segments of peak regions for viewing are in peak_arrays"""

    stf.set_trace(train_trace)

    baseline_s = start_params[0]
    baseline_e = start_params[1]
    params_ = start_params

    len_trace_in_samples = len(stf.get_trace(train_trace))
    peak_values = np.zeros(num_stims)
    len_peak_region_in_samples = round(
        (start_params[3] - start_params[2]) / stf.get_sampling_interval())
    peak_arrays = np.zeros((num_stims, (len_peak_region_in_samples)))

    stim_count = 1
    while stim_count <= num_stims:

        peak_start = params_[2]
        peak_end = params_[3]

        print(peak_start, peak_end)
        peak = jjm_peak(baseline_s, baseline_e, peak_start, peak_end)
        print(peak)

        peak_values[stim_count - 1] = peak

        peak_region_slice = slice_peak_region(params_, train_trace)

        peak_arrays[stim_count - 1] = peak_region_slice

        params_ = increment_peak(params_, True, train_increment)

        stim_count += 1

    return (peak_values, peak_arrays)
def return_holding_current(selected_wb, raw_wb):

    wb_ = xlrd.open_workbook(selected_wb)
    sheets = [
        str(sheet.name) for sheet in wb_.sheets()
        if 'normalized' in str(sheet.name)
    ]
    sheets_to_load_from_raw = [
        sheet.strip('normalized') + 'iled_files' for sheet in sheets
    ]
    wb_raw = xlrd.open_workbook(raw_wb)
    raw_sheets = [
        str(sheet.name) for sheet in wb_raw.sheets()
        if 'compiled_files' in str(sheet.name)
    ]
    baseline_files = []
    exp_files = []
    for raw_sheet in raw_sheets:

        try:
            df = pd.read_excel(wb_raw,
                               engine='xlrd',
                               sheetname=str(raw_sheet),
                               index_col=[0, 1])

            files_in_experiment = df.index.levels[0].values[:2]

            baseline_files.append(files_in_experiment[0])
            exp_files.append(files_in_experiment[1])
        except:
            pass

    print(baseline_files)

    baseline_files_to_load = []
    exp_files_to_load = []
    rootsearchdir = '/Users/johnmarshall/Documents/Analysis/RecordingData/'
    for fname, efname in zip(baseline_files, exp_files):
        try:
            if 'TSeries' in fname:
                dir_data = search_dir_iterative_for_extension_tupleoutput(
                    rootsearchdir, str(fname + 'vrecd_loaded.csv'))
            else:
                dir_data = search_dir_iterative_for_extension_tupleoutput(
                    rootsearchdir, fname)
                baseline_files_to_load.append(dir_data[1][1] + '/' +
                                              dir_data[1][0])
                dir_data = search_dir_iterative_for_extension_tupleoutput(
                    rootsearchdir, efname)
                exp_files_to_load.append(dir_data[1][1] + '/' + dir_data[1][0])
        except IndexError:
            print('could not find:', fname)
        pass

    print(baseline_files_to_load)
    dict_to_return = {}
    holding_current_time_series = {}
    for f, ef in zip(baseline_files_to_load, exp_files_to_load):
        currents = []
        print(f)

        if f.endswith('.abf'):
            stf.file_open(f)
        else:
            if 'TSeries' in f:
                sweeps_compiled_from_pv_tseries = pv.import_t_series_episodic(
                    f.strip('vrecd_loaded.csv'))
                pv.plot_episodic_array(sweeps_compiled_from_pv_tseries)

        baselines = []
        for sweep in range((stf.get_size_channel() - 30),
                           stf.get_size_channel()):
            stf.set_trace(sweep)
            stf.set_base_start(100, is_time=True)
            stf.set_base_end(100, is_time=True)
            baselines.append(stf.get_base())
        file_baseline = np.mean(baselines)
        currents.append(file_baseline)
        holding_current_time_series[f] = baselines

        stf.file_open(ef)
        baselines = []
        for sweep in range((stf.get_size_channel() - 15),
                           stf.get_size_channel()):
            stf.set_trace(sweep)
            stf.set_base_start(100, is_time=True)
            stf.set_base_end(100, is_time=True)
            baselines.append(stf.get_base())
        file_baseline = np.mean(baselines)
        currents.append(file_baseline)
        dict_to_return[f] = currents

    df_out = pd.DataFrame(dict_to_return)
    time_series_df = pd.DataFrame(holding_current_time_series)

    df_out.to_excel(
        '/Users/johnmarshall/Documents/Analysis/eCB_paper/holding_current.xlsx'
    )
    time_series_df.to_excel(
        '/Users/johnmarshall/Documents/Analysis/eCB_paper/holding_current_time_series.xlsx'
    )

    return (df_out)
示例#21
0
def count_events(start, delta, threshold=0, up=True, trace=None, mark=True):
    """
    Counts the number of events (e.g action potentials (AP)) in the current trace.

    Arguments:

    start       -- starting time (in ms) to look for events.
    delta       -- time interval (in ms) to look for events.
    threshold   -- (optional) detection threshold (default = 0).
    up          -- (optional) True (default) will look for upward events,
                    False downwards.
    trace       -- (optional) zero-based index of the trace in the current 
                    channel, if None, the current trace is selected.
    mark        -- (optional) if True (default), set a mark at the point 
                    of threshold crossing
    Returns:
    An integer with the number of events.

    Examples:
    count_events(500,1000) returns the number of events found between t=500
         ms and t=1500 ms above 0 in the current trace and shows a stf 
         marker.
    count_events(500,1000,0,False,-10,i) returns the number of events found
         below -10 in the trace i and shows the corresponding stf markers.
    """

    # sets the current trace or the one given in trace.
    if trace is None:
        sweep = stf.get_trace_index()
    else:
        if type(trace) !=int:
            print('trace argument admits only integers')
            return False
        sweep = trace

    # set the trace described in sweep
    stf.set_trace(sweep)

    # transform time into sampling points
    dt = stf.get_sampling_interval()

    pstart = int( round(start/dt) )
    pdelta = int( round(delta/dt) )

    # select the section of interest within the trace
    selection = stf.get_trace()[pstart:(pstart+pdelta)]

    # algorithm to detect events
    event_counter, i = 0, 0 # set counter and index to zero

    # choose comparator according to direction:
    if up:
        comp = lambda a, b: a > b
    else:
        comp = lambda a, b: a < b

    # run the loop
    while i < len(selection):
        if comp(selection[i], threshold):
            event_counter += 1
            if mark:
                stf.set_marker(pstart+i, selection[i])
            while i < len(selection) and comp(selection[i], threshold):
                i += 1 # skip  until value is below/above threshold
        else:
            i += 1

    return event_counter
示例#22
0
def loadmat():
    """
    Load electrophysiology recordings from ephysIO
    HDF5-based Matlab v7.3 (.mat) files 
    """

    # Import required modules for file IO
    from Tkinter import Tk
    import tkFileDialog
    from gc import collect

    # Use file open dialog to obtain file path
    root = Tk()
    opt = dict(defaultextension='.mat',
               filetypes=[('MATLAB v7.3 (HDF5) file', '*.mat'),
                          ('All files', '*.*')])
    if 'loadcwd' not in globals():
        global loadcwd
    else:
        opt['initialdir'] = loadcwd
    filepath = tkFileDialog.askopenfilename(**opt)
    root.withdraw()

    if filepath != '':

        # Move to file directory and check file version
        loadcwd = filepath.rsplit('/', 1)[0]
        from os import chdir
        print filepath
        chdir(loadcwd)

        # Load data into python
        import ephysIO
        data = ephysIO.MATload(filepath)

        # Display data in Stimfit
        import stf
        if data.get('xdiff') > 0:
            if data.get('yunit') == "V":
                stf.new_window_list(1.0e+3 * np.array(data.get('array')[1::]))
                stf.set_yunits('m' + data.get('yunit'))
            elif data.get('yunit') == "A":
                stf.new_window_list(1.0e+12 * data.get('array')[1::])
                stf.set_yunits('p' + data.get('yunit'))
            else:
                stf.new_window_list(data.get('array')[1::])
                stf.set_yunits(data.get('yunit'))
            stf.set_sampling_interval(1.0e+3 * data.get('xdiff'))
            stf.set_xunits('m' + data.get('xunit'))
            stf.set_trace(0)
            stf.set_recording_comment('\n'.join(data['notes']))
            if data['saved'] != '':
                date = data['saved'][0:8]
                date = tuple(map(int, (date[0:4], date[4:6], date[6:8])))
                stf.set_recording_date('%s-%s-%s' % date)
                time = data['saved'][9::]
                time = tuple(map(int, (time[0:2], time[2:4], time[4:6])))
                stf.set_recording_time('%i-%i-%i' % time)
        elif data.get('xdiff') == 0:
            raise ValueError("Sample interval is not constant")

    else:

        data = {}

    collect()

    return
示例#23
0
def loadacq4(channel=1):
    """
    Load electrophysiology recording data from acq4 hdf5 (.ma) files.
    By default the primary recording channel is loaded.  
    
    If the file is in a folder entitled 000, loadacq4 will load
    the recording traces from all sibling folders (000,001,002,...)
    """

    # Import required modules for file IO
    from Tkinter import Tk
    import tkFileDialog
    from gc import collect

    # Use file open dialog to obtain file path
    root = Tk()
    opt = dict(defaultextension='.ma',
               filetypes=[('ACQ4 (HDF5) file', '*.ma'), ('All files', '*.*')])
    if 'loadcwd' not in globals():
        global loadcwd
    else:
        opt['initialdir'] = loadcwd
    filepath = tkFileDialog.askopenfilename(**opt)
    root.withdraw()

    if filepath != '':

        # Load data into python
        loadcwd = filepath.rsplit('/', 1)[0]
        import ephysIO
        data = ephysIO.MAload(filepath, channel)
        print filepath

        # Display data in Stimfit
        import stf
        if data.get('yunit') == 'A':
            stf.new_window_list(1.0e+12 * data.get('array')[1::])
            stf.set_yunits('p' + data.get('yunit'))
        elif data.get('yunit') == 'V':
            stf.new_window_list(1.0e+3 * data.get('array')[1::])
            stf.set_yunits('m' + data.get('yunit'))
        stf.set_sampling_interval(1.0e+3 * data['xdiff'])
        stf.set_xunits('m' + data.get('xunit'))
        stf.set_trace(0)

        # Import metadata into stimfit
        stf.set_recording_comment('\n'.join(data['notes']))
        date = data['saved'][0:8]
        date = tuple(map(int, (date[0:4], date[4:6], date[6:8])))
        stf.set_recording_date('%s-%s-%s' % date)
        time = data['saved'][9::]
        time = tuple(map(int, (time[0:2], time[2:4], time[4:6])))
        stf.set_recording_time('%i-%i-%i' % time)

    else:

        data = {}

    collect()

    return
示例#24
0
文件: charlie.py 项目: yueqiw/stimfit
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)
示例#25
0
文件: cshl.py 项目: neurodroid/CSHL
def iv(peakwindow=None, basewindow=None, pulsewindow=None,
       erev=None, peakmode="both", ichannel=0, vchannel=1,
       exclude=None):
    """
    Compute and plot an IV curve for currents

    Parameters
    ----------
    peakwindow : (float, float), optional
        Window for peak measurement (time in ms from beginning of sweep)
        None for current cursor settings. Default: None
    basewindow : (float, float), optional
        Window for baseline measurement (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
    erev : float, optional
        End of v clamp pulse in ms or None to determine automatically.
        Default: None
    peakmode : string, optional
        Peak direction - one of "up", "down", "both" or "mean". Default: "up"
    ichannel : int, optional
        current channel number. Default: 0
    vchannel : int, optional
        voltage channel number. Default: 1
    exclude : list of ints, optional
        List of trace indices to be excluded from the analysis. Default: None

    Returns
    -------
    v_commands : numpy.ndarray
        Command voltages
    ipeaks : numpy.ndarray
        Peak currents
    gpeaks : numpy.ndarray
        Peak normalized conductances
    g_fit : numpy.ndarray
        Half-maximal voltage and slope of best-fit Boltzmann function
    """

    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()
    olddirection = stf.get_peak_direction()

    v_commands = []
    ipeaks = []
    if basewindow is not None:
        stf.base.cursor_time = basewindow

    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()):
        if exclude is not None:
            if ntrace in exclude:
                continue

        stf.set_trace(ntrace)
        stf.set_channel(ichannel)
        trace = stf.get_trace()

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

        # Measure only downward peaks (inward currents)
        if peakmode is "mean":
            stf.set_peak_direction("up")
            stf.set_peak_mean(-1)
        else:
            stf.set_peak_direction(peakmode)
            # Set peak computation to single sampling point
            stf.set_peak_mean(1)

        if peakwindow is not None:
            stf.peak.cursor_time = peakwindow
        stf.measure()
        if basewindow is not None:
            ipeaks.append(stf.peak.value-stf.base.value)
        else:
            ipeaks.append(stf.peak.value)

        # 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=0))
    stfio_plot.plot_scalebars(
        ax_voltages, xunits=stf.get_xunits(), yunits=stf.get_yunits(channel=1))

    v_commands = np.array(v_commands)
    ipeaks = np.array(ipeaks)

    if erev is None:
        # Find first zero crossing in ipeaks:
        for npulse in range(ipeaks.shape[0]-1):
            if np.sign(ipeaks[npulse]) != np.sign(ipeaks[npulse+1]):
                # linear interpolation
                m1 = (ipeaks[npulse+1]-ipeaks[npulse]) / (
                    v_commands[npulse+1]-v_commands[npulse])
                c1 = ipeaks[npulse] - m1*v_commands[npulse]
                erev = -c1/m1
                break
        if erev is None:
            sys.stderr.write(
                "Could not determine reversal potential. Aborting now\n")
            return None

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

    # Reset active channel
    stf.set_channel(ichannel)

    # Compute conductances:
    gpeaks, g_fit = gv(ipeaks, v_commands, erev)

    ax_ipeaks = plot_iv(
        ipeaks, v_commands, stf.get_yunits(channel=ichannel),
        stf.get_yunits(channel=1), fig, 222)

    ax_ipeaks.set_title("Peak current")

    ax_gpeaks = plot_gv(
        gpeaks, v_commands, stf.get_yunits(channel=vchannel),
        g_fit, fig, 224)
    ax_gpeaks.set_title("Peak conductance")

    stf.show_table_dictlist({
        "Voltage ({0})".format(
            stf.get_yunits(channel=vchannel)): v_commands.tolist(),
        "Peak current ({0})".format(
            stf.get_yunits(channel=ichannel)): ipeaks.tolist(),
        "Peak conductance (g/g_max)": gpeaks.tolist(),
    })

    return v_commands, ipeaks, gpeaks, g_fit
示例#26
0
def find_AP_peak_ADP_trace(*argv):
    """ count number of APs, find ADPs and thesholds in indicated trace with current injection/gradually increasing steps
	inputs: (time (msec) to start search, length of search region, starting current value, 
	current delta between traces, threshold value, deflection direction ('up'/'down'), mark traces (True/False))"""
    ##if times are input, use those, otherwise use peak cursor settings
    #TO DO: optional change to threshold_values and deflection_direction
    if len(argv) > 0:
        trace_selection = argv[0]
        threshold_value = float(argv[1])
        deflection_direction = argv[2]
        mark_option = argv[3]
        start_msec = float(argv[4])
        delta_msec = float(argv[5])
    else:
        trace_selection = stf.get_trace_index()
        threshold_value = 0
        deflection_direction = 'up'
        mark_option = True
        start_msec = float(stf.get_peak_start(True))
        delta_msec = float(stf.get_peak_end(True) - start_msec)

    stf.set_trace(trace_selection)
    ##gets AP counts and sample points in current trace
    if deflection_direction == 'up':
        direction_input = True
    else:
        direction_input = False

    ##count function will return number of APs in trace and sample points for subsequent functions
    trace_count, trace_sample_points_absolute = jjm_count(
        start_msec,
        delta_msec,
        threshold=threshold_value,
        up=direction_input,
        trace=trace_selection,
        mark=mark_option)

    ##finds afterdepolarizations--minimums between peaks
    trace_ADP_values, trace_ADP_indicies = find_ADPs(
        trace_sample_points_absolute)
    trace_si = stf.get_sampling_interval()
    trace_ADP_times = [sample * trace_si for sample in trace_ADP_indicies]
    trace_AP_values, trace_AP_indicies = find_ADPs(
        trace_sample_points_absolute)
    trace_si = stf.get_sampling_interval()
    trace_ADP_times = [sample * trace_si for sample in trace_AP_indicies]
    trace_thresholds_indicies = find_thresholds(stf.get_trace(trace_selection),
                                                trace_si, trace_ADP_indicies)
    trace_threshold_values = [
        stf.get_trace(trace_selection)[index]
        for index in trace_thresholds_indicies
    ]
    trace_threshold_times = [
        sample * trace_si for sample in trace_thresholds_indicies
    ]
    for sample, mv in zip(trace_thresholds_indicies, trace_threshold_values):
        stf.set_marker(sample, mv)

    for x in range(len(trace_threshold_values)):
        if trace_threshold_values[
                x] > threshold_value or trace_threshold_values[
                    x] < trace_ADP_values[x]:
            trace_threshold_values[x] = 'NaN'

    #arrays for output
    ADP_out_array = np.transpose(np.array([trace_ADP_times, trace_ADP_values]))
    threshold_out_array = np.transpose(
        np.array([trace_threshold_times, trace_threshold_values]))
    out_array = np.hstack([ADP_out_array, threshold_out_array])
    df_out = pd.DataFrame(
        out_array,
        columns=['ADP time', 'ADP (mV)', 'threshold time', 'threshold (mV)'])

    return (trace_count, df_out)
示例#27
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
示例#28
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 )
示例#29
0
def iv(peakwindow=None,
       basewindow=None,
       pulsewindow=None,
       erev=None,
       peakmode="both",
       ichannel=0,
       vchannel=1,
       exclude=None):
    """
    Compute and plot an IV curve for currents

    Parameters
    ----------
    peakwindow : (float, float), optional
        Window for peak measurement (time in ms from beginning of sweep)
        None for current cursor settings. Default: None
    basewindow : (float, float), optional
        Window for baseline measurement (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
    erev : float, optional
        End of v clamp pulse in ms or None to determine automatically.
        Default: None
    peakmode : string, optional
        Peak direction - one of "up", "down", "both" or "mean". Default: "up"
    ichannel : int, optional
        current channel number. Default: 0
    vchannel : int, optional
        voltage channel number. Default: 1
    exclude : list of ints, optional
        List of trace indices to be excluded from the analysis. Default: None

    Returns
    -------
    v_commands : numpy.ndarray
        Command voltages
    ipeaks : numpy.ndarray
        Peak currents
    gpeaks : numpy.ndarray
        Peak normalized conductances
    g_fit : numpy.ndarray
        Half-maximal voltage and slope of best-fit Boltzmann function
    """

    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()
    olddirection = stf.get_peak_direction()

    v_commands = []
    ipeaks = []
    if basewindow is not None:
        stf.base.cursor_time = basewindow

    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()):
        if exclude is not None:
            if ntrace in exclude:
                continue

        stf.set_trace(ntrace)
        stf.set_channel(ichannel)
        trace = stf.get_trace()

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

        # Measure only downward peaks (inward currents)
        if peakmode is "mean":
            stf.set_peak_direction("up")
            stf.set_peak_mean(-1)
        else:
            stf.set_peak_direction(peakmode)
            # Set peak computation to single sampling point
            stf.set_peak_mean(1)

        if peakwindow is not None:
            stf.peak.cursor_time = peakwindow
        stf.measure()
        if basewindow is not None:
            ipeaks.append(stf.peak.value - stf.base.value)
        else:
            ipeaks.append(stf.peak.value)

        # 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=0))
    stfio_plot.plot_scalebars(ax_voltages,
                              xunits=stf.get_xunits(),
                              yunits=stf.get_yunits(channel=1))

    v_commands = np.array(v_commands)
    ipeaks = np.array(ipeaks)

    if erev is None:
        # Find first zero crossing in ipeaks:
        for npulse in range(ipeaks.shape[0] - 1):
            if np.sign(ipeaks[npulse]) != np.sign(ipeaks[npulse + 1]):
                # linear interpolation
                m1 = (ipeaks[npulse + 1] - ipeaks[npulse]) / (
                    v_commands[npulse + 1] - v_commands[npulse])
                c1 = ipeaks[npulse] - m1 * v_commands[npulse]
                erev = -c1 / m1
                break
        if erev is None:
            sys.stderr.write(
                "Could not determine reversal potential. Aborting now\n")
            return None

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

    # Reset active channel
    stf.set_channel(ichannel)

    # Compute conductances:
    gpeaks, g_fit = gv(ipeaks, v_commands, erev)

    ax_ipeaks = plot_iv(ipeaks, v_commands, stf.get_yunits(channel=ichannel),
                        stf.get_yunits(channel=1), fig, 222)

    ax_ipeaks.set_title("Peak current")

    ax_gpeaks = plot_gv(gpeaks, v_commands, stf.get_yunits(channel=vchannel),
                        g_fit, fig, 224)
    ax_gpeaks.set_title("Peak conductance")

    stf.show_table_dictlist({
        "Voltage ({0})".format(stf.get_yunits(channel=vchannel)):
        v_commands.tolist(),
        "Peak current ({0})".format(stf.get_yunits(channel=ichannel)):
        ipeaks.tolist(),
        "Peak conductance (g/g_max)":
        gpeaks.tolist(),
    })

    return v_commands, ipeaks, gpeaks, g_fit
示例#30
0
文件: analysis.py 项目: acp29/penn
def EPSPtrains(latency=200,
               numStim=4,
               intvlList=[1, 0.8, 0.6, 0.4, 0.2, 0.1, 0.08, 0.06, 0.04, 0.02]):

    # Initialize
    numTrains = len(intvlList)  # Number of trains
    intvlArray = np.array(intvlList) * 1000  # Units in ms
    si = stf.get_sampling_interval()  # Units in ms

    # Background subtraction
    traceBaselines = []
    subtractedTraces = []
    k = 1e-4
    x = [i * stf.get_sampling_interval() for i in range(stf.get_size_trace())]
    for i in range(numTrains):
        stf.set_trace(i)
        z = x
        y = stf.get_trace()
        traceBaselines.append(y)
        ridx = []
        if intvlArray[i] > 500:
            for j in range(numStim):
                ridx += range(
                    int(round(((intvlArray[i] * j) + latency - 1) / si)),
                    int(round(
                        ((intvlArray[i] * (j + 1)) + latency - 1) / si)) - 1)
        else:
            ridx += range(
                int(round((latency - 1) / si)),
                int(
                    round(((intvlArray[i] *
                            (numStim - 1)) + latency + 500) / si)) - 1)
        ridx += range(int(round(4999 / si)), int(round(5199 / si)))
        z = np.delete(z, ridx, 0)
        y = np.delete(y, ridx, 0)
        yi = np.interp(x, z, y)
        yf = signal.symiirorder1(yi, (k**2), 1 - k)
        traceBaselines.append(yf)
        subtractedTraces.append(stf.get_trace() - yf)
    stf.new_window_list(traceBaselines)
    stf.new_window_list(subtractedTraces)

    # Measure depolarization
    # Initialize variables
    a = []
    b = []

    # Set baseline start and end cursors
    stf.set_base_start(np.round(
        (latency - 50) / si))  # Average during 50 ms period before stimulus
    stf.set_base_end(np.round(latency / si))

    # Set fit start cursor
    stf.set_fit_start(np.round(latency / si))
    stf.set_fit_end(
        np.round(((intvlArray[1] * (numStim - 1)) + latency + 1000) /
                 si))  # Include a 1 second window after last stimulus

    # Start AUC calculations
    for i in range(numTrains):
        stf.set_trace(i)
        stf.measure()
        b.append(stf.get_base())
        n = int(stf.get_fit_end() + 1 - stf.get_fit_start())
        x = np.array([k * stf.get_sampling_interval() for k in range(n)])
        y = stf.get_trace()[int(stf.get_fit_start()):int(stf.get_fit_end() +
                                                         1)]
        a.append(np.trapz(y - b[i], x))  # Units in V.s

    return a
示例#31
0
def plot_traces(plotwindow=None, ichannel=0, vchannel=1):
    """
    Show traces in a figure

    Parameters
    ----------
    plotwindow : (float, float), optional
        Plot window (in ms from beginning of trace)
        None for whole trace. Default: None
    ichannel : int, optional
        current channel number. Default: 0
    vchannel : int, optional
        voltage channel number. Default: 1
    """

    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()

    fig = stf.mpl_panel(figsize=(12, 8)).fig
    fig.clear()
    gs = gridspec.GridSpec(4, 1)
    ax_currents = stfio_plot.StandardAxis(fig,
                                          gs[:3, 0],
                                          hasx=False,
                                          hasy=False)
    ax_voltages = stfio_plot.StandardAxis(fig,
                                          gs[3:, 0],
                                          hasx=False,
                                          hasy=False,
                                          sharex=ax_currents)
    if plotwindow is not None:
        istart = int(plotwindow[0] / dt)
        istop = int(plotwindow[1] / dt)
    else:
        istart = 0
        istop = None

    for ntrace in range(stf.get_size_channel()):
        stf.set_trace(ntrace)
        stf.set_channel(ichannel)
        trace = stf.get_trace()[istart:istop]

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

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

    # Reset active channel
    stf.set_channel(ichannel)

    stfio_plot.plot_scalebars(ax_currents,
                              xunits=stf.get_xunits(),
                              yunits=stf.get_yunits(channel=0))
    stfio_plot.plot_scalebars(ax_voltages,
                              xunits=stf.get_xunits(),
                              yunits=stf.get_yunits(channel=1))
示例#32
0
文件: cshl.py 项目: neurodroid/CSHL
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