コード例 #1
0
ファイル: embedded_mpl.py プロジェクト: yueqiw/stimfit
    def plot_screen(self):
        import stf

        tsl = []
        try:
            l = stf.get_selected_indices()
            for idx in l:
                tsl.append(
                    stfio_plot.Timeseries(stf.get_trace(idx),
                                          stf.get_sampling_interval(),
                                          yunits=stf.get_yunits(),
                                          color='0.2'))
                fit = stf.get_fit(idx)
                if fit is not None:
                    self.axes.plot(fit[0],
                                   fit[1],
                                   color='0.4',
                                   alpha=0.5,
                                   lw=5.0)
        except:
            pass

        tsl.append(
            stfio_plot.Timeseries(stf.get_trace(),
                                  stf.get_sampling_interval(),
                                  yunits=stf.get_yunits()))
        if stf.get_size_recording() > 1:
            tsl2 = [
                stfio_plot.Timeseries(
                    stf.get_trace(trace=-1,
                                  channel=stf.get_channel_index(False)),
                    stf.get_sampling_interval(),
                    yunits=stf.get_yunits(
                        trace=-1, channel=stf.get_channel_index(False)),
                    color='r',
                    linestyle='-r')
            ]
            stfio_plot.plot_traces(tsl,
                                   traces2=tsl2,
                                   ax=self.axes,
                                   textcolor2='r',
                                   xmin=stf.plot_xmin(),
                                   xmax=stf.plot_xmax(),
                                   ymin=stf.plot_ymin(),
                                   ymax=stf.plot_ymax(),
                                   y2min=stf.plot_y2min(),
                                   y2max=stf.plot_y2max())
        else:
            stfio_plot.plot_traces(tsl,
                                   ax=self.axes,
                                   xmin=stf.plot_xmin(),
                                   xmax=stf.plot_xmax(),
                                   ymin=stf.plot_ymin(),
                                   ymax=stf.plot_ymax())
        fit = stf.get_fit()
        if fit is not None:
            self.axes.plot(fit[0], fit[1], color='0.2', alpha=0.5, lw=5.0)
コード例 #2
0
def detect(template, mode, th, min_int):
    """
    Detect events using the given template and the algorithm specified in
    'mode' with a threshold 'th' and a minimal interval of 'min_int' between
    events. Returns amplitudes and interevent intervals.
    """
    import stf

    # Compute criterium
    crit = stf.detect_events(template,
                             mode=mode,
                             norm=False,
                             lowpass=0.1,
                             highpass=0.001)

    dt = stf.get_sampling_interval()

    # Find event onset times (corresponding to peaks in criteria)
    onsets_i = stf.peak_detection(crit, th, int(min_int / dt))

    trace = stf.get_trace()

    # Use event onset times to find event amplitudes (negative for epscs)
    peak_window_i = min_int / dt
    amps_i = np.array([
        int(np.argmin(trace[onset_i:onset_i + peak_window_i]) + onset_i)
        for onset_i in onsets_i
    ],
                      dtype=np.int)

    amps = trace[amps_i]
    onsets = onsets_i * dt

    return amps, onsets, crit
コード例 #3
0
ファイル: analysis.py プロジェクト: acp29/penn
def hpfilter(n):
    """
    Perform median smoothing filter on the active trace.
    Computationally this is achieved by a central simple moving
    median over a sliding window of n points. The function then
    subtracts the smoothed trace from the original trace.
    The function uses reflect (or bounce) end corrections
    """

    # Check that the number of points in the sliding window is odd

    n = int(n)
    if n % 2 != 1:
        raise ValueError('The filter rank must be an odd integer')
    elif n <= 1:
        raise ValueError('The filter rank must > 1')

    # Apply smoothing filter
    filtered_trace = []
    l = stf.get_size_trace()
    padded_trace = np.pad(stf.get_trace(), (n - 1) / 2, 'reflect')
    filtered_trace.append([np.median(padded_trace[j:n + j]) for j in range(l)])

    print "Window width was %g ms" % (stf.get_sampling_interval() * (n - 1))

    # Apply subtraction
    subtracted_trace = stf.get_trace() - np.array(filtered_trace)

    return stf.new_window_list(subtracted_trace)
コード例 #4
0
def get_dv_dt(slice_indicies=(0, 0)):
    """Main function to take 1st derivative of V_trace and return an array with V_values 
    and dv_dt value for plotting
    --input tuple to use slice of trace"""

    #determine if using whole trace or slice

    if slice_indicies != 0:
        sample_start = slice_indicies[0]
        sample_end = slice_indicies[1]

    else:
        sample_start = 0
        sample_end = len(stf.get_trace())

    #get sampling interval to create dt part of dv/dt
    #dt is just sampling interval
    si = stf.get_sampling_interval()

    #read V values from trace,
    V_values = stf.get_trace()[sample_start:sample_end]

    #compute dv and by iterating over voltage vectors
    dv = [V_values[i + 1] - V_values[i] for i in range(len(V_values) - 1)]

    #compute dv/dt
    dv_dt = [(dv[i] / si) for i in range(len(dv))]
    #V values for a dv/dt / V graph is just truncated trace with final sample point removed
    V_plot = V_values[:-1]
    #combine for a plotting function/further manipulation
    V_dv_dt = np.vstack([V_plot, dv_dt])
    stf.new_window(dv_dt)

    return (V_dv_dt)
コード例 #5
0
ファイル: spells.py プロジェクト: 410pfeliciano/stimfit
def count_aps():
    """
    Shows a result table with the number of action potentials (i.e
    events whose potential is above 0 mV) in selected traces.  If
    no trace is selected, then the current trace is analyzed.

    Returns:
    False if document is not open.
    """
    if not stf.check_doc():
        print("Open file first")
        return False
  
    if len( stf.get_selected_indices() )==0: 
        sel_trace = [ stf.get_trace_index()]
    else: 
        sel_trace = stf.get_selected_indices()

    mytable = dict()
    for trace in sel_trace:
        tstart = 0
        tend = stf.get_size_trace(trace)*stf.get_sampling_interval()
        threshold = 0
        spikes = count_events(tstart, tend, threshold, True, trace, True)
        mytable["Trace %.3d" %trace] = spikes

    stf.show_table(mytable)

    return True
コード例 #6
0
ファイル: spells.py プロジェクト: yueqiw/stimfit
def count_aps():
    """
    Shows a result table with the number of action potentials (i.e
    events whose potential is above 0 mV) in selected traces.  If
    no trace is selected, then the current trace is analyzed.

    Returns:
    False if document is not open.
    """
    if not stf.check_doc():
        print("Open file first")
        return False

    if len(stf.get_selected_indices()) == 0:
        sel_trace = [stf.get_trace_index()]
    else:
        sel_trace = stf.get_selected_indices()

    mytable = dict()
    for trace in sel_trace:
        tstart = 0
        tend = stf.get_size_trace(trace) * stf.get_sampling_interval()
        threshold = 0
        spikes = count_events(tstart, tend, threshold, True, trace, True)
        mytable["Trace %.3d" % trace] = spikes

    stf.show_table(mytable)

    return True
コード例 #7
0
def median_filter(n):
    """
    Perform median smoothing filter on the selected traces. 
    Computationally this is achieved by a central simple moving 
    median over a sliding window of n points.

    The function uses reflect (or bounce) end corrections

    """

    # Check that at least one trace was selected
    if not stf.get_selected_indices():
        raise IndexError('No traces were selected')

    # Check that the number of points in the sliding window is odd
    n = int(n)
    if n % 2 != 1:
        raise ValueError('The filter rank must be an odd integer')
    elif n <= 1:
        raise ValueError('The filter rank must > 1')

    # Apply smoothing filter
    filtered_traces = []
    for i in stf.get_selected_indices():
        l = stf.get_size_trace(i)
        padded_trace = np.pad(stf.get_trace(i), (n - 1) / 2, 'reflect')
        filtered_traces.append(
            [np.median(padded_trace[j:n + j]) for j in range(l)])

    print "Window width was %g ms" % (stf.get_sampling_interval() * (n - 1))

    return stf.new_window_list(filtered_traces)
コード例 #8
0
def scan_through_train_expt(params_expt_input, train_increment, num_stims):

    len_peak_region_in_samples = round(
        (params_expt_input[3] - params_expt_input[2]) /
        stf.get_sampling_interval())

    expt_peaks = np.zeros((stf.get_size_channel(), num_stims))
    expt_peak_arrays = np.zeros(
        (stf.get_size_channel(), num_stims, len_peak_region_in_samples))

    trace = 0
    while trace < stf.get_size_channel():

        params_expt = params_expt_input

        [expt_peaks[trace], expt_peak_arrays[trace]
         ] = scan_through_train(params_expt, train_increment, num_stims, trace)
        params_expt[2] = params_expt_input[2] - (train_increment * (num_stims))
        params_expt[3] = params_expt_input[3] - (train_increment * (num_stims))

        trace += 1

    loaded_file = stf.get_filename()[:-3]
    np.savetxt(loaded_file + '_peaks.csv',
               expt_peaks,
               delimiter=',',
               newline='\n')

    return (expt_peaks, expt_peak_arrays)
コード例 #9
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))
コード例 #10
0
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)
コード例 #11
0
ファイル: embedded_mpl.py プロジェクト: 410pfeliciano/stimfit
 def plot_spectrum(self):
     import stf
     Pow, freq = mlab.psd(stf.get_trace(), 
                          Fs=(1.0/stf.get_sampling_interval())*1e3,
                          detrend=mlab.detrend_linear)
     self.axes.plot(freq, 10*np.log10(Pow))
     self.axes.set_xlabel("Frequency (Hz)")
     self.axes.set_ylabel("Power spectral density (dB/Hz)")
コード例 #12
0
ファイル: mintools.py プロジェクト: 410pfeliciano/stimfit
def stf_fit( p0, lsfunc ):
    data = stf.get_trace()[ stf.get_fit_start() : stf.get_fit_end() ]
    dt = stf.get_sampling_interval()
    x = np.arange(0, len(data)*dt, dt)

    plsq = leastsq(leastsq_stf, p0, args=(data, lsfunc, x))
    
    return plsq[0]
コード例 #13
0
ファイル: mintools.py プロジェクト: yueqiw/stimfit
def stf_fit(p0, lsfunc):
    data = stf.get_trace()[stf.get_fit_start():stf.get_fit_end()]
    dt = stf.get_sampling_interval()
    x = np.arange(0, len(data) * dt, dt)

    plsq = leastsq(leastsq_stf, p0, args=(data, lsfunc, x))

    return plsq[0]
コード例 #14
0
def crop():

    si = stf.get_sampling_interval()
    start = stf.get_fit_start() * si
    end = stf.get_fit_end() * si
    spells.cut_sweeps(start, end - start)

    return
コード例 #15
0
ファイル: embedded_mpl.py プロジェクト: yueqiw/stimfit
 def plot_spectrum(self):
     import stf
     Pow, freq = mlab.psd(stf.get_trace(),
                          Fs=(1.0 / stf.get_sampling_interval()) * 1e3,
                          detrend=mlab.detrend_linear)
     self.axes.plot(freq, 10 * np.log10(Pow))
     self.axes.set_xlabel("Frequency (Hz)")
     self.axes.set_ylabel("Power spectral density (dB/Hz)")
コード例 #16
0
def monoexpfit(optimization=True, Tn=20):
    """
    Fits monoexponential function with offset to data between the fit cursors
    in the current trace of the active channel using a Chebyshev-Levenberg-
    Marquardt hybrid algorithm. Optimization requires Scipy. Setting optimization
    to False forces this function to use just the Chebyshev algorithm. The maximum
    order of the Chebyshev polynomials can be set using Tn.
    """

    # Get data
    fit_start = stf.get_fit_start()
    fit_end = stf.get_fit_end()
    y = np.double(stf.get_trace()[fit_start:fit_end])
    si = stf.get_sampling_interval()
    l = len(y)
    t = si * np.arange(0, l, 1, np.double)

    # Define monoexponential function
    def f(t, *p):
        return p[0] + p[1] * np.exp(-t / p[2])

    # Get initial values from Chebyshev transform fit
    init = chebexp(1, Tn)
    p0 = (init.get('Offset'), )
    p0 += (init.get('Amp_0'), )
    p0 += (init.get('Tau_0'), )

    # Optimize (if applicable)
    if optimization == True:
        # Optimize fit using Levenberg-Marquardt algorithm
        options = {"ftol": 2.22e-16, "xtol": 2.22e-16, "gtol": 2.22e-16}
        [p, pcov] = optimize.curve_fit(f, t, y, p0, **options)
    elif optimization == False:
        p = list(p0)
    fit = f(t, *p)

    # Calculate SSE
    SSE = np.sum((y - fit)**2)

    # Plot fit in a new window
    matrix = np.zeros((2, stf.get_size_trace())) * np.nan
    matrix[0, :] = stf.get_trace()
    matrix[1, fit_start:fit_end] = fit
    stf.new_window_matrix(matrix)

    # Create table of results
    retval = [("p0_Offset", p[0])]
    retval += [("p1_Amp_0", p[1])]
    retval += [("p2_Tau_0", p[2])]
    retval += [("SSE", SSE)]
    retval += [("dSSE", 1.0 - np.sum((y - f(t, *p0))**2) / SSE)]
    retval += [("Time fit begins", fit_start * si)]
    retval += [("Time fit ends", fit_end * si)]
    retval = dict(retval)
    stf.show_table(
        retval, "monoexpfit, Section #%i" % float(stf.get_trace_index() + 1))

    return
コード例 #17
0
def automated_search_triexponential(trace_region_to_search, search_period,
                                    threshold, min_btw_events, tau_rise,
                                    tau_1_decay, tau_2_decay):
    """searches section of trace based on a user input triexponential function (tau_rise, tau_1_decay, tau_2_decay)"""
    #converts some inputs to sample points
    min_samples_btw_events = min_btw_events / stf.get_sampling_interval()

    #pull out region to search
    region_to_search = stf.get_trace(
    )[trace_region_to_search[0]:trace_region_to_search[1]]

    #list to store detected events
    event_times = []

    #creates vector of time points
    t = np.linspace(0, 50, (50 / stf.get_sampling_interval()))

    #creates triexponential pattern function
    p_t = [(1 - math.exp(-(t_point - 0) / tau_rise)) *
           (math.exp(-(t_point - 0) / tau_1_decay)) *
           (math.exp(-(t_point - 0) / tau_2_decay)) for t_point in t]

    #slides window along
    pt = 0
    while pt < range(len(region_to_search) - int(min_samples_btw_events)):

        EPSC_test = stf.get_trace()[pt:(
            pt + (search_period / stf.get_sampling_interval()))]

        corr_coeff = stats.pearsonr(p_t, EPSC_test)[0]

        if corr_coeff > threshold:

            stf.set_marker(pt,
                           region_to_search[trace_region_to_search[0] + pt])

            event_times.append(pt * stf.get_sampling_interval())

            pt += min_samples_btw_events

        else:

            pt += 1

    return (event_times)
コード例 #18
0
def upsample_flex():
    """
    Upsample to sampling interval of 1 ms using cubic spline interpolation
    """

    old_time = [
        i * stf.get_sampling_interval() for i in range(stf.get_size_trace())
    ]
    new_time = range(
        int(np.fix((stf.get_size_trace() - 1) * stf.get_sampling_interval())))
    new_traces = []
    for i in range(stf.get_size_channel()):
        f = interpolate.interp1d(old_time, stf.get_trace(i), 'cubic')
        new_traces.append(f(new_time))
    stf.new_window_list(new_traces)
    stf.set_sampling_interval(1)

    return
コード例 #19
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)
コード例 #20
0
def slice_peak_region(params, trace):
    """use time for params, function converts to samples for cutting/displaying"""

    stf.select_trace(trace)

    sampling_interval = stf.get_sampling_interval()

    peak_2_start_samples = (params[2] / sampling_interval)
    peak_2_end_samples = (params[3] / sampling_interval)

    peak_region = stf.get_trace()[peak_2_start_samples:peak_2_end_samples]

    return (peak_region)
コード例 #21
0
def remove_artifacts(first_artifact_start, length_time_to_remove,
                     time_between_artifacts, number_of_artifacts):

    #get sampling interval of current tract

    sampling_interval = stf.get_sampling_interval()

    #convert input paramenters (units of time) to samples

    first_artifact_start_samples = float(first_artifact_start) / float(
        sampling_interval)

    length_time_to_remove_samples = float(length_time_to_remove) / float(
        sampling_interval)

    time_between_artifacts_samples = float(time_between_artifacts) / float(
        sampling_interval)

    #create variable for artifact end

    first_artifact_end_samples = first_artifact_start_samples + length_time_to_remove_samples

    #get trace, convert trace to normal list

    original_trace = list(stf.get_trace())

    #create list for section of trace up until 1st artifact

    trace_artifacts_removed = original_trace[0:int(first_artifact_start_samples
                                                   )]

    #add remaining sections of trace with artifacts removed

    for artifact_number in range(0, number_of_artifacts):

        start_sample = int(first_artifact_end_samples +
                           (time_between_artifacts_samples * artifact_number))
        end_sample = int(first_artifact_start_samples +
                         (time_between_artifacts_samples *
                          (artifact_number + 1)))

        print(start_sample)
        print(end_sample)

        trace_artifacts_removed.extend(original_trace[start_sample:end_sample])

    #plots trace in new window
    stf.new_window(trace_artifacts_removed)

    return (trace_artifacts_removed)
コード例 #22
0
ファイル: spells.py プロジェクト: 410pfeliciano/stimfit
    def update(self):
        """ update current trace sampling rate, 
        cursors position and  measurements (peak, baseline & AP kinetics)
        according to the threshold value set at construction or when
        the object is called with a threshold argument.
        """
        # set slope
        stf.set_slope(self._thr) # on stf v0.93 or above

        # update sampling rate
        self._dt = stf.get_sampling_interval() 

        # update cursors and AP kinetics (peak and half-width)
        stf.measure() 
コード例 #23
0
    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)
コード例 #24
0
ファイル: spells.py プロジェクト: yueqiw/stimfit
    def update(self):
        """ update current trace sampling rate, 
        cursors position and  measurements (peak, baseline & AP kinetics)
        according to the threshold value set at construction or when
        the object is called with a threshold argument.
        """
        # set slope
        stf.set_slope(self._thr)  # on stf v0.93 or above

        # update sampling rate
        self._dt = stf.get_sampling_interval()

        # update cursors and AP kinetics (peak and half-width)
        stf.measure()
コード例 #25
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)
コード例 #26
0
ファイル: embedded_mpl.py プロジェクト: 410pfeliciano/stimfit
 def plot_screen(self):
     import stf
     
     tsl = []
     try:
         l = stf.get_selected_indices()
         for idx in l:
             tsl.append(stfio_plot.Timeseries(stf.get_trace(idx), 
                                              stf.get_sampling_interval(),
                                              yunits = stf.get_yunits(),
                                              color='0.2'))
             fit = stf.get_fit(idx)
             if fit is not None:
                 self.axes.plot(fit[0], fit[1], color='0.4', alpha=0.5, lw=5.0)
     except:
         pass
     
     tsl.append(stfio_plot.Timeseries(stf.get_trace(),
                                      stf.get_sampling_interval(),
                                      yunits = stf.get_yunits()))
     if stf.get_size_recording()>1:
         tsl2 = [stfio_plot.Timeseries(stf.get_trace(trace=-1, channel=stf.get_channel_index(False)),
                                       stf.get_sampling_interval(),
                                       yunits = stf.get_yunits(trace=-1, channel=stf.get_channel_index(False)),
                                       color='r', linestyle='-r')]
         stfio_plot.plot_traces(tsl, traces2=tsl2, ax=self.axes, textcolor2 = 'r',
                                xmin=stf.plot_xmin(), xmax=stf.plot_xmax(),
                                ymin=stf.plot_ymin(), ymax=stf.plot_ymax(), 
                                y2min=stf.plot_y2min(), y2max=stf.plot_y2max())
     else:
         stfio_plot.plot_traces(tsl, ax=self.axes,
                                xmin=stf.plot_xmin(), xmax=stf.plot_xmax(),
                                ymin=stf.plot_ymin(), ymax=stf.plot_ymax())
     fit = stf.get_fit()
     if fit is not None:
         self.axes.plot(fit[0], fit[1], color='0.2', alpha=0.5, lw=5.0)
コード例 #27
0
def trainpeaks():
    """    
    Measure a 20 Hz train of peaks starting at 260 ms into the trace 
    """

    pk = []
    for i in range(5):
        stf.set_base_start(
            int(255 / stf.get_sampling_interval()) +
            (50 / stf.get_sampling_interval()) * i)
        stf.set_base_end(
            int(259 / stf.get_sampling_interval()) +
            (50 / stf.get_sampling_interval()) * i)
        stf.set_peak_start(
            int(260.5 / stf.get_sampling_interval()) +
            (50 / stf.get_sampling_interval()) * i)
        stf.set_peak_end(
            int(270.5 / stf.get_sampling_interval()) +
            (50 / stf.get_sampling_interval()) * i)
        stf.measure()
        pk.append(stf.get_peak() - stf.get_base())

    # Create table of results
    dictlist = [("Peak 1", pk[0])]
    dictlist += [("Peak 2", pk[1])]
    dictlist += [("Peak 3", pk[2])]
    dictlist += [("Peak 4", pk[3])]
    dictlist += [("Peak 5", pk[4])]
    retval = dict(dictlist)
    stf.show_table(retval,
                   "peaks, Section #%i" % float(stf.get_trace_index() + 1))

    # Create table of results
    dictlist = [("Peak 1", pk[0] / pk[0] * 100)]
    dictlist += [("Peak 2", pk[1] / pk[0] * 100)]
    dictlist += [("Peak 3", pk[2] / pk[0] * 100)]
    dictlist += [("Peak 4", pk[3] / pk[0] * 100)]
    dictlist += [("Peak 5", pk[4] / pk[0] * 100)]
    retval = dict(dictlist)
    stf.show_table(
        retval, "norm peaks, Section #%i" % float(stf.get_trace_index() + 1))

    return
コード例 #28
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
コード例 #29
0
ファイル: analysis.py プロジェクト: acp29/penn
def interpstim():
    """
    Interpolate values between fit cursors in all traces in the active channel.
    Typically used to remove stimulus artifacts.
    """

    x = np.array(
        [i * stf.get_sampling_interval() for i in range(stf.get_size_trace())])
    fit_start = int(stf.get_fit_start())
    fit_end = int(stf.get_fit_end())
    interp_traces = []
    for i in range(stf.get_size_channel()):
        tmp = stf.get_trace(i)
        tmp[fit_start:fit_end] = np.interp(x[fit_start:fit_end],
                                           [x[fit_start], x[fit_end]],
                                           [tmp[fit_start], tmp[fit_end]])
        interp_traces.append(tmp)
    stf.new_window_list(interp_traces)

    return
コード例 #30
0
def remove_artifacts_from_sweeps(artifact_start_time, artifact_end_time):

    sampling_interval = stf.get_sampling_interval()
    artifact_start = int(artifact_start_time / sampling_interval)
    artifact_end = int(artifact_end_time / sampling_interval)

    continuous_trace = []
    output_artifacts_removed = []

    for sweep in range(stf.get_size_channel()):
        sweep_trace_before_artifact = stf.get_trace(sweep)[0:artifact_start]
        sweep_trace_after_artifact = stf.get_trace(sweep)[artifact_end:]
        sweep_trace = np.append(sweep_trace_before_artifact,
                                sweep_trace_after_artifact)
        output_artifacts_removed.append(sweep_trace)
        continuous_trace.extend(sweep_trace)

    stf.new_window_list(output_artifacts_removed)

    return (continuous_trace)
コード例 #31
0
def find_baseline_amplitude(sigma):
    # gaussian filter with sigma 10
    trace_ = stf.get_trace()
    trace_filtered = ndimage.filters.gaussian_filter(trace_, sigma)
    # take derivative
    si = stf.get_sampling_interval()
    #read V values from trace,
    V_values = stf.get_trace()
    #compute dv and by iterating over voltage vectors
    dv = [V_values[i + 1] - V_values[i] for i in range(len(V_values) - 1)]
    #compute dv/dt
    dv_dt = [(dv[i] / si) for i in range(len(dv))]
    # find index of derivative peak
    deriv_max = np.argmin(dv_dt)
    # use derivative peak index to get baseline from original trace
    # use a mean of 10 sample points
    baseline = np.mean(trace_[deriv_max - 10:deriv_max])
    peak_amplitude = np.min(stf.get_trace())
    peak_from_baseline = peak_amplitude - baseline

    return (baseline, peak_amplitude, peak_from_baseline)
コード例 #32
0
ファイル: spells.py プロジェクト: 410pfeliciano/stimfit
def cut_sweeps(start, delta, sequence=None):
    """
    Cuts a sequence of traces and present
    them in a new window.

    Arguments:

    start       -- starting point (in ms) to cut.
    delta       -- time interval (in ms) to cut
    sequence    -- list of indices to be cut. If None, every trace in the
                    channel will be cut.

    Returns:
    A new window with the traced cut.

    Examples:
    cut_sweeps(200,300) cut the traces between t=200 ms and t=500 ms 
        within the whole channel.
    cut_sweeps(200,300,range(30,60)) the same as above, but only between 
        traces 30 and 60.
    cut_sweeps(200,300,stf.get_selected_indices()) cut between 200 ms               and 500 ms only in the selected traces.

    """

    # select every trace in the channel if not selection is given in sequence
    if sequence is None:
        sequence = range(stf.get_size_channel())

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

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

    # creates a destination python list
    dlist = [ stf.get_trace(i)[pstart:(pstart+pdelta)] for i in sequence ]

    return stf.new_window_list(dlist)
コード例 #33
0
ファイル: spells.py プロジェクト: yueqiw/stimfit
def cut_sweeps(start, delta, sequence=None):
    """
    Cuts a sequence of traces and present
    them in a new window.

    Arguments:

    start       -- starting point (in ms) to cut.
    delta       -- time interval (in ms) to cut
    sequence    -- list of indices to be cut. If None, every trace in the
                    channel will be cut.

    Returns:
    A new window with the traced cut.

    Examples:
    cut_sweeps(200,300) cut the traces between t=200 ms and t=500 ms 
        within the whole channel.
    cut_sweeps(200,300,range(30,60)) the same as above, but only between 
        traces 30 and 60.
    cut_sweeps(200,300,stf.get_selected_indices()) cut between 200 ms               and 500 ms only in the selected traces.

    """

    # select every trace in the channel if not selection is given in sequence
    if sequence is None:
        sequence = range(stf.get_size_channel())

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

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

    # creates a destination python list
    dlist = [stf.get_trace(i)[pstart:(pstart + pdelta)] for i in sequence]

    return stf.new_window_list(dlist)
コード例 #34
0
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)
コード例 #35
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
コード例 #36
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)
コード例 #37
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
コード例 #38
0
ファイル: spells.py プロジェクト: 410pfeliciano/stimfit
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
コード例 #39
0
def savemat():
    """
    Save electrophysiology recordings to 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 save dialog to obtain file path
    root = Tk()
    opt = dict(defaultextension='.mat',
               filetypes=[('MATLAB v7.3 (HDF5) file', '*.mat'),
                          ('All files', '*.*')])
    if 'savecwd' not in globals():
        global savecwd
    else:
        opt['initialdir'] = savecwd
    filepath = tkFileDialog.asksaveasfilename(**opt)
    root.destroy()

    if filepath != '':

        # Move to file directoty
        savecwd = filepath.rsplit('/', 1)[0]
        import os
        print filepath
        os.chdir(savecwd)
        filename = filepath.rsplit('/', 1)[1]

        # Get data from active Stimfit window
        import stf
        import numpy as np
        n = stf.get_size_channel()
        array = np.array([stf.get_trace(i).tolist() for i in range(n)])
        if np.any(np.isnan(array)) | np.any(np.isinf(array)):
            raise ValueError(
                "nan and inf values cannot be parsed into ephysIO")
        if stf.get_yunits() == 'pA':
            yunit = 'A'
            array = 1.0e-12 * array
        elif stf.get_yunits() == 'mV':
            yunit = 'V'
            array = 1.0e-03 * array
        else:
            yunit = stf.get_yunits()
            #print "Warning: Expected Y dimension units to be either pA or mV"

        # Create X dimension properties
        if stf.get_xunits() == 'ms':
            xunit = 's'
            xdiff = np.array([[1.0e-03 * stf.get_sampling_interval()]])
        else:
            raise ValueError("Expected X dimension units to be ms")

        # Calculate X dimension and add to array
        x = xdiff * np.arange(0.0, np.shape(array)[1], 1, 'float64')
        array = np.concatenate((np.array(x, ndmin=2), array), 0)

        # Get data recording notes
        notes = stf.get_recording_comment().split('\n')
        names = None

        import ephysIO
        ephysIO.MATsave(filepath, array, xunit, yunit, names, notes)

    collect()

    return
コード例 #40
0
def chebexp(n, Tn=20):
    """
    Fits sums of exponentials with offset to the current trace in the
    active channel using the Chebyshev tranform algorithm. The maximum
    order of the Chebyshev polynomials can be set using Tn.

    Reference:
    Malachowski, Clegg and Redford (2007) J Microsc 228(3): 282-95
    """

    # Get data trace between fit/decay cursors
    y = stf.get_trace()[stf.get_fit_start():stf.get_fit_end()].astype(
        np.double)
    si = np.double(stf.get_sampling_interval())
    l = len(y)
    N = np.double(l - 1)

    # Calculate time dimension with unit 1
    t = np.arange(0, l, 1, np.double)

    # Check the maximum order Chebyshev polynomials to generate
    if l < Tn:
        raise ValueError('Tn exceeds the number of data points')

    # Generate the polynomials T and coefficients d
    T0 = np.ones((l), np.double)
    R0 = np.sum(T0**2)
    d0 = np.sum((T0 * y) / R0)
    T = np.zeros((l, Tn), np.double)
    T[:, 0] = 1 - 2 * t / N
    T[:, 1] = 1 - 6 * t / (N - 1) + 6 * t**2 / (N * (N - 1))
    R = np.zeros((Tn), np.double)
    d = np.zeros((Tn), np.double)
    for j in range(Tn):
        if j > 1:
            A = (j + 1) * (N - j)
            B = 2 * (j + 1) - 1
            C = j * (N + j + 1)
            T[:, j] = (B * (N - 2 * t) * T[:, j - 1] - C * T[:, j - 2]) / A
        R[j] = np.sum(T[:, j]**2)
        d[j] = np.sum(T[:, j] * y / R[j])

    # Generate additional coefficients dn that describe the relationship
    # between the Chebyshev coefficients d and the constant k, which is
    # directly related to the exponent time constant
    dn = np.zeros((n, Tn), np.double)
    for i in range(1, n + 1):
        for j in range(1 + i, Tn - i + 1):
            if i > 1:
                dn[i - 1, j - 1] = (((N + j + 2) * dn[i - 2, j] /
                                     (2 * j + 3)) - dn[i - 2, j - 1] -
                                    ((N - j + 1) * dn[i - 2, j - 2] /
                                     (2 * j - 1))) / 2
            else:
                dn[i - 1,
                   j - 1] = (((N + j + 2) * d[j] / (2 * j + 3)) - d[j - 1] -
                             ((N - j + 1) * d[j - 2] / (2 * j - 1))) / 2
    for i in range(n):
        dn[i, :] = dn[i, :] * np.double(np.all(dn, 0))

    # Form the regression model to find the time constants of each exponent
    Mn = np.zeros((n, n), np.double)
    b = np.zeros(n, np.double)
    for i in range(n):
        b[i] = np.sum(d * dn[i, :])
        for m in range(n):
            Mn[i, m] = -np.sum(dn[i, :] * dn[m, :])

    # Solve the linear problem
    try:
        x = np.linalg.solve(Mn, b)
    except:
        x = np.linalg.lstsq(Mn, b)[0]
    k = np.roots(np.hstack((1, x)))
    if any(k != np.real(k)):
        raise ValueError("Result is not a sum of %d real exponents" % n)
    tau = -1 / np.log(1 + k)

    # Generate the Chebyshev coefficients df for each exponent
    df0 = np.zeros(n, np.double)
    df = np.zeros((n, Tn), np.double)
    for i in range(n):
        for j in range(Tn):
            df[i, j] = np.sum(np.exp(-t / tau[i]) * T[:, j] / R[j])
        df0[i] = np.sum(np.exp(-t / tau[i]) * T0 / R0)

    # Form the regression model to find the amplitude of each exponent
    Mf = np.zeros((n, n), np.double)
    b = np.zeros(n, np.double)
    for i in range(n):
        b[i] = np.sum(d * df[i, :])
        for m in range(n):
            Mf[i, m] = np.sum(df[i, :] * df[m, :])

    # Solve the linear problem
    try:
        a = np.linalg.solve(Mf, b)
    except:
        a = np.linalg.lstsq(Mf, b)[0]

    # Calculate the offset for the fit
    offset = d0 - np.sum(df0 * a.T)

    # Prepare output
    retval = [("Amp_%d" % i, a[i]) for i in range(n)]
    retval += [("Tau_%d" % i, si * tau[i]) for i in range(n)]
    retval += [("Offset", np.double(offset))]
    retval = dict(retval)

    return retval