def deflection_error(weight, target, templateFile, trials=10, window=30e-3, ai=int(os.environ['AI_CHANNEL']), ao=int(os.environ['AO_CHANNEL'])): try: w = weight[0] except: w = weight lcg.substituteStrings( templateFile, 'psp.xml', { '<weight>0</weight>': '<weight>' + str(w) + '</weight>', 'AI': str(ai), 'AO': str(ao) }) sub.call(lcg.common.prog_name + ' -c psp.xml -V 4 -n ' + str(trials), shell=True) # get the file list files = glob.glob('*.h5') files.sort() files = files[-trials:] # read the first file to allocate memory entities, info = lcg.loadH5Trace(files[0]) for ntt in entities: if ntt['name'] == 'RealNeuron' or ntt['id'] == 4: post = ntt elif ntt['name'] == 'LIFNeuron': pre = ntt elif ntt['name'] == 'Waveform': t0 = ntt['metadata'][0][0] #if max(pre['data']) < -50: # no spike in the presynaptic # print('>>> No spike in the presynaptic neuron. <<<') # sys.exit(1) # allocate memory t = np.arange(0, info['dt'] * len(post['data']), info['dt']) idx = np.nonzero(t < t0)[0] dV = np.zeros((trials, len(post['data']))) dV[0, :] = post['data'] - np.mean(post['data'][idx]) for k in range(1, trials): entities, info = lcg.loadH5Trace(files[k]) for ntt in entities: if ntt['name'] == 'RealNeuron' or ntt['id'] == 4: dV[k, :] = ntt['data'] - np.mean(ntt['data'][idx]) break dV = np.mean(dV, 0) idx = np.intersect1d(np.nonzero(t > t0)[0], np.nonzero(t < t0 + window)[0]) deflection = np.max(np.abs(dV[idx])) print('weight = %.3f -> deflection = %.3f mV' % (weight, deflection)) return (deflection - target)**2
def analyseSTEPprotocol(folder, ax=None): files, kfiles = gatherH5files(folder) Ke = np.loadtxt(kfiles[0]) / 1e9 V = [] I = [] spks = [] ktrials = [os.path.basename(k).split("_")[0] for k in kfiles] print("Analysing step protocol...") spks = [] for f in files: ent, info = lcg.loadH5Trace(f) if not os.path.basename(f).split(".")[0] in ktrials: tmpV, tmpI, meta = compensateVoltage(ent, Ke, ["AnalogInput", "Waveform"]) V.append(tmpV) I.append(tmpI) spks.append(argfindspks(tmpV, -20)) time = np.linspace(0, info["tend"], len(tmpV)) prot_time = np.cumsum(meta[::, 0]) idx = np.where((time > prot_time[0] - 0.1) & (time < prot_time[1] + 0.1))[0] V = np.vstack(V).T I = np.vstack(I).T ax.plot(time[idx], V[idx,], color="gray", lw=0.6) ax.plot(time[idx], V[idx, 0], color="k", lw=1) spks = [time[sp] for sp in spks] isi = [np.diff(sp) for sp in spks] adapt_coeff = [(i[-1] - i[0]) / i[0] for i in isi] # print adapt_coeff ax.axis("tight") remove_spines(ax) ax.set_ylabel("Voltage (mV)") ax.set_xlabel("Time (s)") return np.mean(adapt_coeff)
def read_analog_input(filename): ent,info = lcg.loadH5Trace(filename) for e in ent: if e['name'] in ['AnalogInput']: V = e['data'] time = np.linspace(0,info['tend'],len(V)) return V,time,info
def analyseSTEPprotocol(folder, ax=None): files, kfiles = gatherH5files(folder) Ke = np.loadtxt(kfiles[0]) / 1e9 V = [] I = [] spks = [] ktrials = [os.path.basename(k).split('_')[0] for k in kfiles] print('Analysing step protocol...') spks = [] for f in files: ent, info = lcg.loadH5Trace(f) if not os.path.basename(f).split('.')[0] in ktrials: tmpV, tmpI, meta = compensateVoltage(ent, Ke, ['AnalogInput', 'Waveform']) V.append(tmpV) I.append(tmpI) spks.append(argfindspks(tmpV, -20)) time = np.linspace(0, info['tend'], len(tmpV)) prot_time = np.cumsum(meta[::, 0]) idx = np.where((time > prot_time[0] - 0.1) & (time < prot_time[1] + .1))[0] V = np.vstack(V).T I = np.vstack(I).T ax.plot(time[idx], V[idx, ], color='gray', lw=0.6) ax.plot(time[idx], V[idx, 0], color='k', lw=1) spks = [time[sp] for sp in spks] isi = [np.diff(sp) for sp in spks] adapt_coeff = [(i[-1] - i[0]) / i[0] for i in isi] # print adapt_coeff ax.axis('tight') remove_spines(ax) ax.set_ylabel('Voltage (mV)') ax.set_xlabel('Time (s)') return np.mean(adapt_coeff)
def frequency_error(Vbal, target, Rm, R_inh, ai=0, ao=0, duration=10, interval=1, sampling_rate=20000): ratio = lcg.computeRatesRatio(Vm=Vbal, Rin=Rm) R_exc = R_inh * ratio[0] G0_exc,G0_inh,sigma_exc,sigma_inh = lcg.computeSynapticBackgroundCoefficients(ratio[0], R_exc, Rin=Rm) lcg.writeSpontaneousConfig(0, G0_exc, sigma_exc, G0_inh, sigma_inh, ai, ao, duration, sampling_rate, outfile='spontaneous.xml') if interval > 0: sub.call(['sleep', str(interval)]) sub.call(lcg.common.prog_name + ' -c spontaneous.xml -V 4', shell=True) files = glob.glob('*.h5') files.sort() files = files[-1] entities,info = lcg.loadH5Trace(files) for ntt in entities: if ntt['name'] == 'RealNeuron': V = ntt['data'] break if max(V) < -40: # no spike in the presynaptic print('Balanced voltage: %.2f mV.' % Vbal) print('Spontaneous firing frequency: 0 Hz (0 spikes).') print('Error = %g Hz^2.' % target**2) return target**2 t = np.arange(0, len(V)) * info['dt'] spks = lcg.findSpikes(t,V,-20) freq = float(len(spks)) / duration print('Balanced voltage: %.2f mV.' % Vbal) print('Spontaneous firing frequency: %.3f Hz (%d spikes).' % (freq, len(spks))) print('Error = %g Hz^2.' % (freq-target)**2) return (freq - target)**2
def analyse_ramp(directory): if directory[-1] == '/': directory = directory[:-1] h5_files = list_h5_files(directory, True) if len(h5_files) == 0: print('No H5 files in %s.' % directory) return None rheobase = np.zeros(len(h5_files)) try: Ke = np.loadtxt(directory + 'kernel.dat') except: Ke = None for i, file in enumerate(h5_files): entities, info = lcg.loadH5Trace(file) for ntt in entities: if ntt['name'] == 'Waveform': I = ntt['data'] elif ntt['name'] == 'AnalogInput': if Ke is None: V = ntt['data'] else: V = aec.compensate(ntt['data'], I, Ke) idx = extract_spikes(V) rheobase[i] = I[idx[0]] return (np.mean(rheobase), np.std(rheobase))
def analyse_ramp(directory): if directory[-1] == '/': directory = directory[:-1] h5_files = list_h5_files(directory,True) if len(h5_files) == 0: print('No H5 files in %s.' % directory) return None rheobase = np.zeros(len(h5_files)) try: Ke = np.loadtxt(directory + 'kernel.dat') except: Ke = None for i,file in enumerate(h5_files): entities,info = lcg.loadH5Trace(file) for ntt in entities: if ntt['name'] == 'Waveform': I = ntt['data'] elif ntt['name'] == 'AnalogInput': if Ke is None: V = ntt['data'] else: V = aec.compensate(ntt['data'],I,Ke) idx = extract_spikes(V) rheobase[i] = I[idx[0]] return (np.mean(rheobase),np.std(rheobase))
def read_analog_input(filename): ent, info = lcg.loadH5Trace(filename) for e in ent: if e['name'] in ['AnalogInput']: V = e['data'] time = np.linspace(0, info['tend'], len(V)) return V, time, info
def run_pulse(self): if self.b_running.isChecked(): duration = self.duration sub.call('lcg-experiment -c {0} -V 4 --disable-replay'.format( self.cfg_file), shell=True) try: ent, info = lcg.loadH5Trace(self.filename) except: print('File {0} not found.\n', ) return Idone = False Vdone = False for e in ent: if e['units'] in 'pA' and not Idone: if not Idone: self.I.append(e['data']) Idone = True else: self.I[-1] = self.I[-1] + e['data'] break for e in ent: if e['units'] in 'mV': if not Vdone: self.V.append(e['data']) self.time = np.linspace(0, info['tend'] * 1.0e3, len(self.V[-1])) Vdone = True else: self.V[-1] = self.V[-1] + e['data'] break if len(self.I) > 20: del (self.I[0]) del (self.V[0]) self.count += 1 allI = np.vstack(self.I).T allV = np.vstack(self.V).T idxpre = np.where(self.time < (-0.1 + duration / 4))[0] idxpost = np.where((self.time > (-1 + (duration * 5) / 4)) & (self.time < (-0.1 + (duration * 5) / 4)))[0] if len(self.I) > 11: self.meanI = np.mean(allI[:, -8:], axis=1) self.meanV = np.mean(allV[:, -8:], axis=1) else: self.meanI = self.I[-1] self.meanV = self.V[-1] self.Vpre = np.mean(self.meanV[idxpre]) self.Vpost = np.mean(self.meanV[idxpost]) self.Ipre = np.mean(self.meanI[idxpre]) self.Ipost = np.mean(self.meanI[idxpost]) self.resistance_time.append(info['startTimeSec']) # print([(self.Vpost-self.Vpre),((self.Ipost-self.Ipre))]) self.resistance.append(1e3 * ((self.Vpost - self.Vpre) / (self.Ipost - self.Ipre))) if self.opts['mode'] == 'VC': self.Iaxis_limits = [np.min(allI), np.max(allI)] else: self.Iaxis_limits = [np.min(allV), np.max(allV)]
def run_pulse(self): if self.b_running.isChecked(): duration = self.duration sub.call('lcg-experiment -c {0} -V 4 --disable-replay'.format(self.cfg_file),shell=True) try: ent,info = lcg.loadH5Trace(self.filename) except: print('File {0} not found.\n',) return Idone = False Vdone = False for e in ent: if e['units'] in 'pA' and not Idone: if not Idone: self.I.append(e['data']) Idone = True else: self.I[-1] = self.I[-1] + e['data'] break for e in ent: if e['units'] in 'mV': if not Vdone: self.V.append(e['data']) self.time = np.linspace(0,info['tend']*1.0e3, len(self.V[-1])) Vdone = True else: self.V[-1] = self.V[-1] + e['data'] break if len(self.I) > 20: del(self.I[0]) del(self.V[0]) self.count += 1 allI = np.vstack(self.I).T allV = np.vstack(self.V).T idxpre = np.where(self.time<(-0.1+duration/4))[0] idxpost = np.where((self.time>(-1+(duration*5)/4)) & (self.time<(-0.1+(duration*5)/4)))[0] if len(self.I) > 11: self.meanI = np.mean(allI[:,-8:],axis=1) self.meanV = np.mean(allV[:,-8:],axis=1) else: self.meanI = self.I[-1] self.meanV = self.V[-1] self.Vpre = np.mean(self.meanV[idxpre]) self.Vpost = np.mean(self.meanV[idxpost]) self.Ipre = np.mean(self.meanI[idxpre]) self.Ipost = np.mean(self.meanI[idxpost]) self.resistance_time.append(info['startTimeSec']) # print([(self.Vpost-self.Vpre),((self.Ipost-self.Ipre))]) self.resistance.append(1e3*((self.Vpost- self.Vpre)/(self.Ipost- self.Ipre))) if self.opts['mode'] == 'VC': self.Iaxis_limits = [np.min(allI),np.max(allI)] else: self.Iaxis_limits = [np.min(allV),np.max(allV)]
def deflection_error(weight, target, templateFile, trials=10, window=30e-3, ai=int(os.environ['AI_CHANNEL']), ao=int(os.environ['AO_CHANNEL'])): try: w = weight[0] except: w = weight lcg.substituteStrings(templateFile, 'psp.xml', {'<weight>0</weight>': '<weight>' + str(w) + '</weight>', 'AI': str(ai), 'AO': str(ao)}) sub.call(lcg.common.prog_name + ' -c psp.xml -V 4 -n ' + str(trials), shell=True) # get the file list files = glob.glob('*.h5') files.sort() files = files[-trials:] # read the first file to allocate memory entities,info = lcg.loadH5Trace(files[0]) for ntt in entities: if ntt['name'] == 'RealNeuron' or ntt['id'] == 4: post = ntt elif ntt['name'] == 'LIFNeuron': pre = ntt elif ntt['name'] == 'Waveform': t0 = ntt['metadata'][0][0] #if max(pre['data']) < -50: # no spike in the presynaptic # print('>>> No spike in the presynaptic neuron. <<<') # sys.exit(1) # allocate memory t = np.arange(0, info['dt']*len(post['data']), info['dt']) idx = np.nonzero(t < t0)[0] dV = np.zeros((trials,len(post['data']))) dV[0,:] = post['data'] - np.mean(post['data'][idx]) for k in range(1,trials): entities,info = lcg.loadH5Trace(files[k]) for ntt in entities: if ntt['name'] == 'RealNeuron' or ntt['id'] == 4: dV[k,:] = ntt['data'] - np.mean(ntt['data'][idx]) break dV = np.mean(dV,0) idx = np.intersect1d(np.nonzero(t>t0)[0], np.nonzero(t<t0+window)[0]) deflection = np.max(np.abs(dV[idx])) print('weight = %.3f -> deflection = %.3f mV' % (weight,deflection)) return (deflection - target)**2
def analyseRAMPprotocol(folder, ax=None): files, kfiles = gatherH5files(folder) Ke = np.loadtxt(kfiles[0]) / 1e9 V = [] I = [] spks = [] ktrials = [os.path.basename(k).split('_')[0] for k in kfiles] print('Analysing ramp protocol...') for f in files: ent, info = lcg.loadH5Trace(f) if not os.path.basename(f).split('.')[0] in ktrials: tmpV, tmpI, meta = compensateVoltage(ent, Ke, ['AnalogInput', 'Waveform']) V.append(tmpV) I.append(tmpI) spks.append(argfindspks(tmpV, -20)) time = np.linspace(0, info['tend'], len(tmpV)) prot_time = np.cumsum(meta[::, 0]) idx = np.where(time > prot_time[-3])[0] V = np.vstack(V).T I = np.vstack(I).T ax[0].plot(time[idx], V[idx, 0], 'k') IFR_time = [] IFR = [] threshold_current = [I[ii[0], jj] for jj, ii in enumerate(spks)] for sp in spks: sp = time[sp] IFR_time.append(sp[1:] - np.diff(sp) / 2) IFR.append(1. / np.diff(sp)) ax[1].plot(np.hstack(IFR_time), np.hstack(IFR), 'r-o', markerfacecolor='gray', markeredgecolor='k', markersize=2) for a in ax: a.axis('tight') tmp = ax[0].get_ylim() ax[1].set_xlim(ax[0].get_xlim()) ax[1].set_ylim([0, max(ax[1].get_ylim()) * 1.2]) ax[0].set_ylim(tmp) remove_spines(ax[0]) ax[0].set_ylabel('Voltage (mV)') ax[0].set_xlabel('Time (s)') remove_spines(ax[1], v='right') ax[1].spines['top'].set_visible(False) ax[1].xaxis.set_visible(False) ax[1].spines['right'].set_color('red') ax[1].tick_params(axis='y', colors='red') ax[1].set_ylabel('Firing Freq (Hz)', color='red') return np.mean(threshold_current)
def analyseVIprotocol(folder, ax=None): files, kfiles = gatherH5files(folder) Ke = np.loadtxt(kfiles[0]) / 1e9 V = [] I = [] idx = [] ktrials = [os.path.basename(k).split("_")[0] for k in kfiles] print("Analysing hyperpolarizing current steps...") for f in files: ent, info = lcg.loadH5Trace(f) if not os.path.basename(f).split(".")[0] in ktrials: tmpV, tmpI, meta = compensateVoltage(ent, Ke, ["AnalogInput", "Waveform"]) V.append(tmpV) I.append(tmpI) time = np.linspace(0, info["tend"], len(tmpV)) prot_time = np.cumsum(meta[::, 0]) idx = np.where(time > prot_time[-3] - 0.2)[0] V = np.vstack(V).T I = np.vstack(I).T ax[1].plot(time[idx], V[idx, ::], "k", clip_on=False) ax[0].plot(time[idx], I[idx, ::], "k", clip_on=False) # Scale in left corner for a in ax: a.axis("tight") a.clipbox = False a.set_xlim([time[idx[0]], time[idx[-1]]]) tmpx = a.get_xlim() tmpy = a.get_ylim() a.set_yticks(np.linspace(tmpy[0], tmpy[-1], 4).astype(int)) a.set_xticks(np.round(np.linspace(tmpx[0], tmpx[-1], 4), 3)) # print time[idx[0]] tmpx = ax[1].get_xticks() tmpy = ax[1].get_yticks() ax[1].plot(tmpx[-1] + [0, 0], tmpy[:2] + 2, "k", clip_on=False) ax[1].text( tmpx[-1] + 0.05, tmpy[1], "{0}mV".format(np.diff(tmpy[-2::])[0]), va="top", ha="left", fontsize=7, rotation=90 ) ax[1].plot(tmpx[-2:], tmpy[0] + [2, 2], "k", clip_on=False) ax[1].text(tmpx[-2], tmpy[0] + 3, "{0}s".format(np.diff(tmpx[0:2])[0]), va="bottom", ha="left", fontsize=7) tmpx = ax[0].get_xticks() tmpy = ax[0].get_yticks() ax[0].plot(tmpx[-1] + [0, 0], tmpy[:2], "k", clip_on=False) ax[0].text( tmpx[-1] + 0.05, tmpy[1], "{0}pA".format(np.diff(tmpy[-2::])[0]), va="top", ha="left", fontsize=7, rotation=90 ) return None
def analyseRAMPprotocol(folder, ax=None): files, kfiles = gatherH5files(folder) Ke = np.loadtxt(kfiles[0]) / 1e9 V = [] I = [] spks = [] ktrials = [os.path.basename(k).split("_")[0] for k in kfiles] print("Analysing ramp protocol...") for f in files: ent, info = lcg.loadH5Trace(f) if not os.path.basename(f).split(".")[0] in ktrials: tmpV, tmpI, meta = compensateVoltage(ent, Ke, ["AnalogInput", "Waveform"]) V.append(tmpV) I.append(tmpI) spks.append(argfindspks(tmpV, -20)) time = np.linspace(0, info["tend"], len(tmpV)) prot_time = np.cumsum(meta[::, 0]) idx = np.where(time > prot_time[-3])[0] V = np.vstack(V).T I = np.vstack(I).T ax[0].plot(time[idx], V[idx, 0], "k") IFR_time = [] IFR = [] threshold_current = [I[ii[0], jj] for jj, ii in enumerate(spks)] for sp in spks: sp = time[sp] IFR_time.append(sp[1:] - np.diff(sp) / 2) IFR.append(1.0 / np.diff(sp)) ax[1].plot(np.hstack(IFR_time), np.hstack(IFR), "r-o", markerfacecolor="gray", markeredgecolor="k", markersize=2) for a in ax: a.axis("tight") tmp = ax[0].get_ylim() ax[1].set_xlim(ax[0].get_xlim()) ax[1].set_ylim([0, max(ax[1].get_ylim()) * 1.2]) ax[0].set_ylim(tmp) remove_spines(ax[0]) ax[0].set_ylabel("Voltage (mV)") ax[0].set_xlabel("Time (s)") remove_spines(ax[1], v="right") ax[1].spines["top"].set_visible(False) ax[1].xaxis.set_visible(False) ax[1].spines["right"].set_color("red") ax[1].tick_params(axis="y", colors="red") ax[1].set_ylabel("Firing Freq (Hz)", color="red") return np.mean(threshold_current)
def frequency_error(Vbal, target, Rm, R_inh, ai=0, ao=0, duration=10, interval=1, sampling_rate=20000): ratio = lcg.computeRatesRatio(Vm=Vbal, Rin=Rm) R_exc = R_inh * ratio[0] G0_exc, G0_inh, sigma_exc, sigma_inh = lcg.computeSynapticBackgroundCoefficients( ratio[0], R_exc, Rin=Rm) lcg.writeSpontaneousConfig(0, G0_exc, sigma_exc, G0_inh, sigma_inh, ai, ao, duration, sampling_rate, outfile='spontaneous.xml') if interval > 0: sub.call(['sleep', str(interval)]) sub.call(lcg.common.prog_name + ' -c spontaneous.xml -V 4', shell=True) files = glob.glob('*.h5') files.sort() files = files[-1] entities, info = lcg.loadH5Trace(files) for ntt in entities: if ntt['name'] == 'RealNeuron': V = ntt['data'] break if max(V) < -40: # no spike in the presynaptic print('Balanced voltage: %.2f mV.' % Vbal) print('Spontaneous firing frequency: 0 Hz (0 spikes).') print('Error = %g Hz^2.' % target**2) return target**2 t = np.arange(0, len(V)) * info['dt'] spks = lcg.findSpikes(t, V, -20) freq = float(len(spks)) / duration print('Balanced voltage: %.2f mV.' % Vbal) print('Spontaneous firing frequency: %.3f Hz (%d spikes).' % (freq, len(spks))) print('Error = %g Hz^2.' % (freq - target)**2) return (freq - target)**2
def analyseTAUprotocol(folder, ax=None): files, kfiles = gatherH5files(folder) Ke = np.loadtxt(kfiles[0]) / 1e9 V = [] I = [] spks = [] ktrials = [os.path.basename(k).split('_')[0] for k in kfiles] print('Analysing tau protocol...') for f in files: ent, info = lcg.loadH5Trace(f) if not os.path.basename(f).split('.')[0] in ktrials: tmpV, tmpI, meta = compensateVoltage(ent, Ke, ['AnalogInput', 'Waveform']) V.append(tmpV) I.append(tmpI) time = np.linspace(0, info['tend'], len(tmpV)) prot_time = np.cumsum(meta[::, 0]) idx = np.where((time > prot_time[0] - 0.0055) & (time < prot_time[1] + 0.1))[0] fitidx = np.where((time > prot_time[1] + 0.0007) & (time < prot_time[1] + 0.08))[0] V = np.vstack(V).T I = np.vstack(I).T ax.plot(time[idx], V[idx, ], color='gray', lw=0.6) ax.plot(time[idx], np.mean(V[idx, ], 1), color='k', lw=.7) func = lambda x, a, b, c, d, e: a * (1 - np.exp(-x / b)) + c * (1 - np.exp( -x / d)) + e from scipy.optimize import curve_fit popt, pcov = curve_fit( func, np.reshape(np.repeat(time - time[fitidx[0]], V.shape[1]), V.shape)[fitidx, :].flatten(), V[fitidx, :].flatten()) ax.plot(time[fitidx[0]:idx[-1]], func(time[fitidx[0]:idx[-1]] - time[fitidx[0]], *popt), 'r') # import ipdb; ipdb.set_trace() ax.axis('tight') remove_spines(ax) ax.set_ylabel('Voltage (mV)') ax.set_xlabel('Time (s)') return popt
def analyse_last_file(): ''' Extracts the spiketrain statistics from the last file. ''' files = glob.glob('*.h5') files.sort() data_file = files[-1] ent, info = lcg.loadH5Trace(data_file) V = ent[1]['data'] I = ent[0]['data'] kernel_file = glob.glob('*.dat') kernel_file.sort() if len(kernel_file): kernel_file = kernel_file[-1] Ke = np.loadtxt(kernel_file) V = aec.compensate(V, I, Ke / 1.0e9) t = np.arange(0, len(V) - 1) * info['dt'] spks = lcg.findSpikes(t, V, thresh=-10) isi = np.diff(spks) return np.mean(isi), np.std(isi) / np.mean(isi), np.mean(V), np.std(V)
def analyse_last_file(): ''' Extracts the spiketrain statistics from the last file. ''' files = glob.glob('*.h5') files.sort() data_file = files[-1] ent,info = lcg.loadH5Trace(data_file) V = ent[1]['data'] I = ent[0]['data'] kernel_file = glob.glob('*.dat') kernel_file.sort() if len(kernel_file): kernel_file = kernel_file[-1] Ke = np.loadtxt(kernel_file) V = aec.compensate(V,I,Ke/1.0e9) t = np.arange(0,len(V)-1)*info['dt'] spks = lcg.findSpikes(t, V, thresh=-10) isi = np.diff(spks) return np.mean(isi), np.std(isi)/np.mean(isi),np.mean(V),np.std(V)
def analyseTAUprotocol(folder, ax=None): files, kfiles = gatherH5files(folder) Ke = np.loadtxt(kfiles[0]) / 1e9 V = [] I = [] spks = [] ktrials = [os.path.basename(k).split("_")[0] for k in kfiles] print("Analysing tau protocol...") for f in files: ent, info = lcg.loadH5Trace(f) if not os.path.basename(f).split(".")[0] in ktrials: tmpV, tmpI, meta = compensateVoltage(ent, Ke, ["AnalogInput", "Waveform"]) V.append(tmpV) I.append(tmpI) time = np.linspace(0, info["tend"], len(tmpV)) prot_time = np.cumsum(meta[::, 0]) idx = np.where((time > prot_time[0] - 0.0055) & (time < prot_time[1] + 0.1))[0] fitidx = np.where((time > prot_time[1] + 0.0007) & (time < prot_time[1] + 0.08))[0] V = np.vstack(V).T I = np.vstack(I).T ax.plot(time[idx], V[idx,], color="gray", lw=0.6) ax.plot(time[idx], np.mean(V[idx,], 1), color="k", lw=0.7) func = lambda x, a, b, c, d, e: a * (1 - np.exp(-x / b)) + c * (1 - np.exp(-x / d)) + e from scipy.optimize import curve_fit popt, pcov = curve_fit( func, np.reshape(np.repeat(time - time[fitidx[0]], V.shape[1]), V.shape)[fitidx, :].flatten(), V[fitidx, :].flatten(), ) ax.plot(time[fitidx[0] : idx[-1]], func(time[fitidx[0] : idx[-1]] - time[fitidx[0]], *popt), "r") # import ipdb; ipdb.set_trace() ax.axis("tight") remove_spines(ax) ax.set_ylabel("Voltage (mV)") ax.set_xlabel("Time (s)") return popt
def plotAllEntitiesFromFile(fig, filename, kernelFiles = [], filesCounter=[], ax = [], downsampleFactor = 1): # TODO: Cleanup function (filesCounter and return values) ent, info = lcg.loadH5Trace(filename) # print('Loaded file %s'%filename) time = np.linspace(0,info['tend'],len(ent[0]['data'])) compensateWithKernelOffline(ent,kernelFiles) if (not len(ax) == len(ent)) and len(ax): print('Trying to plot different experiments, cleaning up...') ax = [] fig.clf() filesCounter = [] if len(ax) == 0: ax.append(fig.add_subplot(len(ent),1,1, axisbg='w')) for i in range(1,len(ent)): ax.append(fig.add_subplot(len(ent),1,i+1, sharex=ax[0], axisbg='w')) [t.set_color('black') for t in ax[-1].xaxis.get_ticklines()] [t.set_color('black') for t in ax[-1].xaxis.get_ticklabels()] ax[-1].set_xlabel('Time (s)') for a in ax: a.grid(True,color=[0.7,0.7,0.7]) a.set_axisbelow(True) a.spines['top'].set_visible(False) a.spines['right'].set_visible(False) a.yaxis.set_ticks_position('left') a.xaxis.set_ticks_position('bottom') for a in ax[:-1]: plt.setp(a.get_xticklabels(), visible=False) plot_entities(ax, time, ent, 0 , None, downsampleFactor, color=cc[len(filesCounter),:]) # Aesthetics related ax[0].set_xlim([time[0],time[-1]]) filesCounter.append(filename) return ax,filesCounter
def analyseAPprotocol(folder, tpre=5, tpost=20, ax=None): files, kfiles = gatherH5files(folder) # Uses the first kernel Ke = np.loadtxt(kfiles[0]) / 1e9 V = [] I = [] idx = [] ktrials = [os.path.basename(k).split('_')[0] for k in kfiles] print('Analysing spike shapes...') for f in files: ent, info = lcg.loadH5Trace(f) if not os.path.basename(f).split('.')[0] in ktrials: try: inset_samples except NameError: inset_samples = np.arange( np.floor(-(tpre * 1e-3) / info['dt']), np.floor(+(tpost * 1e-3) / info['dt']), dtype=int) # time_actual = np.linspace( - tpre, tpost, len(inset_samples)) time = np.linspace(-tpre, tpost, len(inset_samples)) tmpV, tmpI, meta = compensateVoltage(ent, Ke, ['AnalogInput', 'Waveform']) spks = argfindspks(tmpV, -20) if len(spks) == 1: # f = interp1d(time_actual, tmpV[spks + inset_samples], 'cubic') # V.append(f(time)) V.append(tmpV[spks + inset_samples]) I.append(tmpI[spks + inset_samples]) V = np.vstack(V).T I = np.vstack(I).T dt = info['dt'] * 1e3 dV3 = np.diff(V, 3, 0) / (dt**3) dV1 = np.diff(V, 1, 0) / dt dV3Thresh = 10000 # Not counting for the extra points resulting from the diff idx = np.array([ np.where(dV3[::, ii] > dV3Thresh)[0][0] for ii in range(dV3.shape[1]) ]) + 3 idxmean = np.where(np.mean(dV3, 1) > dV3Thresh)[0][0] + 3 mV = np.mean(V, 1) # mdV1 = np.mean(dV1[1:,], 1) # ax.plot(mV[1:],mdV1, color = 'r', lw = 1) # ax.plot(mV[idxmean + 1] + [ - 5,+ 5], mdV1[idxmean] + [0, 0], 'k--') ax.plot(time, V, color='gray', lw=0.8) [ ax.plot(time[ii], V[ii, jj], 'ro', markerfacecolor='gray', markersize=2) for jj, ii in enumerate(idx) ] ax.plot(time, mV, 'r', lw=1) ax.axis('tight') ax.set_xticks(np.unique(np.linspace(-tpre, tpost, 10).astype(int))) ax.set_yticks(np.unique(np.linspace(np.min(mV), max(mV), 5).astype(int))) ax.plot(time[np.mean(idx)] + [0, 0], ax.get_ylim(), 'k--') tmp = mV[np.mean(idx)] + [0, 0] ax.plot([-tpre, tpost], tmp, 'k--') # Scale in right corner ax.set_xticks(np.linspace(-tpre, tpost, 12).astype(int)) ax.set_yticks(np.linspace(min(mV), max(mV), 5).astype(int)) tmpx = ax.get_xticks() tmpy = ax.get_yticks() ax.plot(tmpx[-4:-2], tmpy[-2] + [0, 0], 'k') ax.plot(tmpx[-4] + [0, 0], tmpy[-2::], 'k') ax.text(tmpx[-4], tmpy[-2] - 2, '{0}ms'.format(np.diff(tmpx[0:2])[0]), va='top', ha='left', fontsize=7) ax.text(tmpx[-4], tmpy[-1], '{0}mV'.format(np.diff(tmpy[-2::])[0]), va='top', ha='right', fontsize=7, rotation=90) return mV[np.mean(idx)]
def analyseVIprotocol(folder, ax=None): files, kfiles = gatherH5files(folder) Ke = np.loadtxt(kfiles[0]) / 1e9 V = [] I = [] idx = [] ktrials = [os.path.basename(k).split('_')[0] for k in kfiles] print('Analysing hyperpolarizing current steps...') for f in files: ent, info = lcg.loadH5Trace(f) if not os.path.basename(f).split('.')[0] in ktrials: tmpV, tmpI, meta = compensateVoltage(ent, Ke, ['AnalogInput', 'Waveform']) V.append(tmpV) I.append(tmpI) time = np.linspace(0, info['tend'], len(tmpV)) prot_time = np.cumsum(meta[::, 0]) idx = np.where(time > prot_time[-3] - .2)[0] V = np.vstack(V).T I = np.vstack(I).T ax[1].plot(time[idx], V[idx, ::], 'k', clip_on=False) ax[0].plot(time[idx], I[idx, ::], 'k', clip_on=False) # Scale in left corner for a in ax: a.axis('tight') a.clipbox = False a.set_xlim([time[idx[0]], time[idx[-1]]]) tmpx = a.get_xlim() tmpy = a.get_ylim() a.set_yticks(np.linspace(tmpy[0], tmpy[-1], 4).astype(int)) a.set_xticks(np.round(np.linspace(tmpx[0], tmpx[-1], 4), 3)) # print time[idx[0]] tmpx = ax[1].get_xticks() tmpy = ax[1].get_yticks() ax[1].plot(tmpx[-1] + [0, 0], tmpy[:2] + 2, 'k', clip_on=False) ax[1].text(tmpx[-1] + 0.05, tmpy[1], '{0}mV'.format(np.diff(tmpy[-2::])[0]), va='top', ha='left', fontsize=7, rotation=90) ax[1].plot(tmpx[-2:], tmpy[0] + [2, 2], 'k', clip_on=False) ax[1].text(tmpx[-2], tmpy[0] + 3, '{0}s'.format(np.diff(tmpx[0:2])[0]), va='bottom', ha='left', fontsize=7) tmpx = ax[0].get_xticks() tmpy = ax[0].get_yticks() ax[0].plot(tmpx[-1] + [0, 0], tmpy[:2], 'k', clip_on=False) ax[0].text(tmpx[-1] + 0.05, tmpy[1], '{0}pA'.format(np.diff(tmpy[-2::])[0]), va='top', ha='left', fontsize=7, rotation=90) return None
def analyseAPprotocol(folder, tpre=5, tpost=20, ax=None): files, kfiles = gatherH5files(folder) # Uses the first kernel Ke = np.loadtxt(kfiles[0]) / 1e9 V = [] I = [] idx = [] ktrials = [os.path.basename(k).split("_")[0] for k in kfiles] print("Analysing spike shapes...") for f in files: ent, info = lcg.loadH5Trace(f) if not os.path.basename(f).split(".")[0] in ktrials: try: inset_samples except NameError: inset_samples = np.arange( np.floor(-(tpre * 1e-3) / info["dt"]), np.floor(+(tpost * 1e-3) / info["dt"]), dtype=int ) # time_actual = np.linspace( - tpre, tpost, len(inset_samples)) time = np.linspace(-tpre, tpost, len(inset_samples)) tmpV, tmpI, meta = compensateVoltage(ent, Ke, ["AnalogInput", "Waveform"]) spks = argfindspks(tmpV, -20) if len(spks) == 1: # f = interp1d(time_actual, tmpV[spks + inset_samples], 'cubic') # V.append(f(time)) V.append(tmpV[spks + inset_samples]) I.append(tmpI[spks + inset_samples]) V = np.vstack(V).T I = np.vstack(I).T dt = info["dt"] * 1e3 dV3 = np.diff(V, 3, 0) / (dt ** 3) dV1 = np.diff(V, 1, 0) / dt dV3Thresh = 10000 # Not counting for the extra points resulting from the diff idx = np.array([np.where(dV3[::, ii] > dV3Thresh)[0][0] for ii in range(dV3.shape[1])]) + 3 idxmean = np.where(np.mean(dV3, 1) > dV3Thresh)[0][0] + 3 mV = np.mean(V, 1) # mdV1 = np.mean(dV1[1:,], 1) # ax.plot(mV[1:],mdV1, color = 'r', lw = 1) # ax.plot(mV[idxmean + 1] + [ - 5,+ 5], mdV1[idxmean] + [0, 0], 'k--') ax.plot(time, V, color="gray", lw=0.8) [ax.plot(time[ii], V[ii, jj], "ro", markerfacecolor="gray", markersize=2) for jj, ii in enumerate(idx)] ax.plot(time, mV, "r", lw=1) ax.axis("tight") ax.set_xticks(np.unique(np.linspace(-tpre, tpost, 10).astype(int))) ax.set_yticks(np.unique(np.linspace(np.min(mV), max(mV), 5).astype(int))) ax.plot(time[np.mean(idx)] + [0, 0], ax.get_ylim(), "k--") tmp = mV[np.mean(idx)] + [0, 0] ax.plot([-tpre, tpost], tmp, "k--") # Scale in right corner ax.set_xticks(np.linspace(-tpre, tpost, 12).astype(int)) ax.set_yticks(np.linspace(min(mV), max(mV), 5).astype(int)) tmpx = ax.get_xticks() tmpy = ax.get_yticks() ax.plot(tmpx[-4:-2], tmpy[-2] + [0, 0], "k") ax.plot(tmpx[-4] + [0, 0], tmpy[-2::], "k") ax.text(tmpx[-4], tmpy[-2] - 2, "{0}ms".format(np.diff(tmpx[0:2])[0]), va="top", ha="left", fontsize=7) ax.text(tmpx[-4], tmpy[-1], "{0}mV".format(np.diff(tmpy[-2::])[0]), va="top", ha="right", fontsize=7, rotation=90) return mV[np.mean(idx)]