def stimulusWaveformFromFile(abf, channel=0): """ Attempt to find the stimulus file used to record an ABF, read the stimulus file (ABF or ATF), and return the stimulus waveform (as a numpy array). """ assert isinstance(abf, pyabf.ABF) assert channel in abf.channelList stimPath = findStimulusWaveformFile(abf, channel) if not stimPath: return np.full(abf.sweepPointCount, np.nan) if abf._cacheStimulusFiles: if not stimPath in cachedStimuli.keys(): if stimPath.upper().endswith(".ABF"): cachedStimuli[stimPath] = pyabf.ABF(stimPath) elif stimPath.upper().endswith(".ATF"): cachedStimuli[stimPath] = pyabf.ATF(stimPath) return cachedStimuli[stimPath].sweepY else: if stimPath.upper().endswith(".ABF"): return pyabf.ABF(stimPath).sweepY elif stimPath.upper().endswith(".ATF"): return pyabf.ATF(stimPath).sweepY
def test_ATF_setSweep(atfPath): atf = pyabf.ATF(atfPath) if (atf.sweepCount > 1): sweep0 = np.array(atf.sweepY) atf.setSweep(1) sweep1 = np.array(atf.sweepY) assert not np.array_equiv(sweep0, sweep1)
def advanced_17_atf_plotting(self): """ ## Plotting Data from ATF Files Although most of the effort in this project has gone into the ABF class, there also exists an ATF class with much of the similar functionality. This class can read Axon Text Format (ATF) files and has a setSweep() with nearly identical sentax to the ABF class. Extra attention was invested into supporting muli-channel ATF data. Note that this example plots only channel 2 from a multi-channel ATF file. """ import pyabf atf = pyabf.ATF("data/abfs/18702001-step.atf") # not ABF! fig = plt.figure(figsize=self.figsize) ax1 = fig.add_subplot(121) ax2 = fig.add_subplot(122) for channel, ax in enumerate([ax1, ax2]): ax.set_title("channel %d" % (channel)) ax.set_xlabel(atf.sweepLabelX) ax.set_ylabel(atf.sweepLabelY) for sweepNumber in atf.sweepList: atf.setSweep(sweepNumber, channel) ax.plot(atf.sweepX, atf.sweepY) ax1.margins(0, .1) ax2.margins(0, .1) ax1.grid(alpha=.2) ax2.grid(alpha=.2) fig.subplots_adjust(wspace=.4) #ignore self.saveAndClose()
def stimulusWaveformFromFile(self): """ Attempt to find the file associated with this ABF channel stimulus waveform, read that waveform (whether ABF or ATF), and return its waveform. If the file can't be found, return False. """ # try to find the stimulus file in the obvious places stimFname = self.abf._stringsIndexed.lDACFilePath[self.channel] stimBN = os.path.basename(stimFname) abfFolder = os.path.dirname(self.abf.abfFilePath) if os.path.exists(stimFname): log.debug("stimulus file found where expected") stimFname = os.path.abspath(stimFname) elif os.path.exists(os.path.join(abfFolder, stimBN)): log.debug("stimulus file found next to ABF") stimFname = os.path.join(abfFolder, stimBN) else: log.debug("stimulus file never found: %s" % stimBN) return False # read the ABF or ATF stimulus file if stimFname.upper().endswith(".ABF"): log.debug("stimulus file is an ABF") abf = pyabf.ABF(stimFname) #TODO: data requires custom stimulus scaling! return abf.sweepY elif stimFname.upper().endswith(".ATF"): log.debug("stimulus file is an ATF") atf = pyabf.ATF(stimFname) #TODO: data requires custom stimulus scaling! return atf.sweepY
def generate_abf_array(file_path, stimuli): file_path = os.path.join(root, filename) abf = pyabf.ABF(file_path) extension = stimuli.split(".")[-1] if 'atf' in extension: stimuli_abf = pyabf.ATF(stimuli) elif 'abf' in extension: stimuli_abf = pyabf.ABF(stimuli) print(abf.abfID + ' loaded') abf_name = np.vstack( [abf.abfID, abf.abfID, abf.abfID, abf.abfID, abf.abfID]) abf_label = np.vstack( ['resist', 'react', 'freq', 'resist running avg', 'react running avg']) abf_feat = analyze_abf_chirp(abf, stimuli_abf, average) running_mean_resist = moving_avg2(abf_feat[0], 10) running_mean_react = moving_avg2(abf_feat[1], 10) #tpeaks = find_peak(abf_feat[2], running_mean) #temp = pd.DataFrame().from_dict(tpeaks[0]) #temp['id'] = np.full(temp.index.values.shape[0], abf.abfID) #temp['width'] = np.full(temp.index.values.shape[0], tpeaks[1]) #peaks = peaks.append(temp) abf_feat = np.vstack((abf_feat, running_mean_resist)) abf_feat = np.vstack((abf_feat, running_mean_react)) abf_ar = np.hstack((abf_name, abf_label, abf_feat)) abf_ar = np.hstack((abf_ar, np.vstack([ np.full(len_f - abf_ar.shape[1], np.nan), np.full(len_f - abf_ar.shape[1], np.nan), np.full(len_f - abf_ar.shape[1], np.nan), np.full(len_f - abf_ar.shape[1], np.nan), np.full(len_f - abf_ar.shape[1], np.nan) ]))) return abf_ar
def stimulusWaveformFromFile(abf, channel=0): """ Attempt to find the stimulus file used to record an ABF, read the stimulus file (ABF or ATF), and return the stimulus waveform (as a numpy array). """ assert isinstance(abf, pyabf.ABF) assert channel in abf.channelList # prepare potential file paths where the stimulus file may exist stimFname = abf._stringsIndexed.lDACFilePath[channel] stimBN = os.path.basename(stimFname) abfFolder = os.path.dirname(abf.abfFilePath) pathSameFolder = os.path.join(abfFolder, stimBN) pathAlt = os.path.join(str(abf.stimulusFileFolder), stimBN) # try to find the stimulus file if os.path.exists(stimFname): stimFname = os.path.abspath(stimFname) elif os.path.exists(pathSameFolder): stimFname = pathSameFolder elif pathAlt and os.path.exists(pathAlt): stimFname = pathAlt else: return np.full(abf.sweepPointCount, np.nan) # the stimulus waveform file was found, consider caching if abf._cacheStimulusFiles: stimFname = os.path.realpath(stimFname) if not stimFname in cachedStimuli.keys(): if stimFname.upper().endswith(".ABF"): cachedStimuli[stimFname] = pyabf.ABF(stimFname) elif stimFname.upper().endswith(".ATF"): cachedStimuli[stimFname] = pyabf.ATF(stimFname) return cachedStimuli[stimFname].sweepY else: if stimFname.upper().endswith(".ABF"): return pyabf.ABF(stimFname) elif stimFname.upper().endswith(".ATF"): return pyabf.ATF(stimFname)
def _loadAtf(path): """ Load our saved atf file. Primarily for testing the code. """ import pyabf # load abf = pyabf.ATF(path) print('_loadAtf()', abf) # plot data = abf.sweepY #plotData(data) return data
def abf_chirp(abf): t = abf.sweepX v = t abf_chrip = pyabf.ATF( 'H:\\Sam\\Protocol\\Monkey\\Chirp Proto\\0_20hz_in50s_vs.atf') i = abf_chrip.sweepY[:] for x in range(0, abf.sweepCount): abf.setSweep(x) v = np.vstack((v, abf.sweepY)) i = np.vstack((i, abf_chrip.sweepY[:])) v = v[1:] i = i[1:] t = abf.sweepX def chirp_amp_phase(v, i, t, start=0.78089, end=49.21, down_rate=20000.0, min_freq=0.1, max_freq=19.5): """ Calculate amplitude and phase of chirp responses Parameters ---------- sweep_set: SweepSet Set of chirp sweeps start: float (optional, default 0.6) Start of chirp stimulus in seconds end: float (optional, default 20.6) End of chirp stimulus in seconds down_rate: int (optional, default 2000) Sampling rate for downsampling before FFT min_freq: float (optional, default 0.2) Minimum frequency for output to contain max_freq: float (optional, default 40) Maximum frequency for output to contain Returns ------- amplitude: array Aka resistance phase: array Aka reactance freq: array Frequencies for amplitude and phase results """ v_list = v i_list = i avg_v = np.vstack(v_list).mean(axis=0) avg_i = np.vstack(i_list).mean(axis=0) #plt.plot(t, avg_v) # #plt.plot(t, avg_i) current_rate = np.rint(1 / (t[1] - t[0])) if current_rate > down_rate: width = int(current_rate / down_rate) ds_v = ds_v = fv._subsample_average(avg_v, width) ds_i = fv._subsample_average(avg_i, width) ds_t = t[::width] else: ds_v = avg_v ds_i = avg_i ds_t = t start_index = tsu.find_time_index(ds_t, start) end_index = tsu.find_time_index(ds_t, end) N = len(ds_v[start_index:end_index]) T = ds_t[1] - ds_t[0] xf = np.linspace(0.0, 1.0 / (2.0 * T), N // 2) v_fft = fftpack.fft(ds_v[start_index:end_index]) i_fft = fftpack.fft(ds_i[start_index:end_index]) Z = v_fft / i_fft R = np.real(Z) X = np.imag(Z) resistance = np.abs(Z)[0:N // 2] reactance = np.arctan(X / R)[0:N // 2] low_ind = tsu.find_time_index(xf, min_freq) high_ind = tsu.find_time_index(xf, max_freq) v2 = R[0:N // 2] return resistance[low_ind:high_ind], reactance[low_ind:high_ind], xf[ low_ind:high_ind], v2[low_ind:high_ind] resist, react, _, v2 = chirp_amp_phase(v, i, t) return resist, react, _, v2
import sys import glob import time import numpy as np PATH_HERE = os.path.abspath(os.path.dirname(__file__)) PATH_DATA = os.path.abspath(PATH_HERE+"../../../data/abfs/") PATH_SRC = os.path.abspath(PATH_HERE+"../../../src/") sys.path.insert(0, PATH_SRC) import pyabf if __name__=="__main__": # An ATF file can be loaded just like an ABF file. # Most methods of the ABF class are the same for the ATF class. stimulus = pyabf.ATF(PATH_DATA+"/sine sweep magnitude 20.atf") stimulus.setSweep(0) stimulusWaveform = stimulus.sweepY # abf.sweepC can be assigned to at any time. # Extra work (trimming or null-padding the stimulus) is done here to # ensure the stimulus waveform length matches the sweep length. for abfFileName in glob.glob(PATH_DATA+"/*.abf"): abf = pyabf.ABF(abfFileName) print("processing", abf.abfID, "...") if len(abf.sweepC) == len(stimulusWaveform): abf.sweepC = stimulusWaveform elif len(abf.sweepC) < len(stimulusWaveform): abf.sweepC = stimulusWaveform[:len(abf.sweepC)] elif len(abf.sweepC) > len(stimulusWaveform): abf.sweepC.fill(np.nan)
peaks = signal.find_peaks(y, height=ds_mean, width=width_peak) if len(peaks[0]) < len(min_peaks[0]): min_peaks = peaks if len(peaks[0]) <= 2 and len(peaks[0]) >= 1: min_peaks = peaks break width_peak -= 1 min_peaks[1]['x-heights'] = x[min_peaks[0]] return [min_peaks[1], width_peak] #abf_chrip = pyabf.ATF('h:\\Sam\\Monkey\\Chirp Proto\\20mv Chirp.atf') #abf_set = abf_dataset.ABFDataSet(abf_file=abf) abf_chrip = pyabf.ATF( 'M:\\Sam\\Protocol\\Monkey\\Chirp Proto\\0_20hz_in50s_vs.atf') def abf_chirp(abf): t = abf.sweepX v = t i = abf_chrip.sweepY[:] for x in range(0, abf.sweepCount): abf.setSweep(x) v = np.vstack((v, abf.sweepY)) i = np.vstack((i, abf_chrip.sweepY[:])) v = v[1:] i = i[1:] t = abf.sweepX
import os import sys import matplotlib.pyplot as plt import glob try: PATH_HERE = os.path.abspath(os.path.dirname(__file__)) PATH_DATA = os.path.abspath(PATH_HERE+"../../../data/abfs/") PATH_SRC = os.path.abspath(PATH_HERE+"../../../src/") DATA_FOLDER = os.path.join(PATH_SRC, "../data/abfs/") sys.path.insert(0, PATH_SRC) import pyabf except: raise EnvironmentError() if __name__ == "__main__": for atfPath in glob.glob(DATA_FOLDER + "/*.atf"): atf = pyabf.ATF(atfPath) print(atf)
""" Test error messages when loading ABFs and ATFs with the wrong methods. """ import os import sys PATH_HERE = os.path.abspath(os.path.dirname(__file__)) PATH_DATA = os.path.abspath(PATH_HERE + "../../../data/abfs/") PATH_SRC = os.path.abspath(PATH_HERE + "../../../src/") sys.path.insert(0, PATH_SRC) import pyabf if __name__ == "__main__": abfFile = PATH_DATA + "/14o08011_ic_pair.abf" atfFile = PATH_DATA + "/model_vc_step.atf" # normal print(pyabf.ABF(abfFile)) print(pyabf.ATF(atfFile)) # errors #print(pyabf.ABF(atfFile)) #print(pyabf.ATF(abfFile))
def test_pathMustBeFile_ATFs(): with pytest.raises(Exception) as excinfo: atf = pyabf.ATF("data/abfs", loadData=False) assert "FILE not a FOLDER" in str(excinfo.value)
def test_pathlib_ATFs(atfPath): atf1 = pyabf.ATF(atfPath, loadData=False) atf2 = pyabf.ATF(pathlib.Path(atfPath), loadData=False) assert atf1.sweepCount == atf2.sweepCount
def test_ATF_hasSweeps(atfPath): atf = pyabf.ATF(atfPath) assert atf.sweepCount > 0 assert len(atf.sweepY) > 0