def plotIV(cell, infile, plottau=False): sizer = OrderedDict([('A', {'pos': [0.2, 0.6, 0.3, 0.5]}), ('B', {'pos': [0.2, 0.6, 0.1, 0.15]}) ]) # dict elements are [left, width, bottom, height] for the axes in the plot. gr = [(a, a+1, 0, 1) for a in range(0, len(sizer.keys()))] # just generate subplots - shape does not matter axmap = OrderedDict(zip(sizer.keys(), gr)) P = PH.Plotter((len(sizer.keys()), 1), axmap=axmap, label=True, figsize=(6., 4.)) # PH.show_figure_grid(P.figure_handle) P.resize(sizer) # perform positioning magic P.figure_handle.suptitle(cell) ivr, d, tr = readIVFile(infile) mon1 = d['runInfo']['electrodeSection'] mon2 = d['runInfo']['dendriticElectrodeSection'] # print mon1 # print mon2 taufit = ivr['taufit'] for i, k in enumerate(tr.keys()): P.axdict['A'].plot(tr[k]['monitor']['time'], tr[k]['monitor']['postsynapticV'], 'k-', linewidth=0.75) P.axdict['B'].plot(tr[k]['monitor']['time'], tr[k]['monitor']['postsynapticI'], 'b-', linewidth=0.75) if plottau: for k in taufit[0].keys(): P.axdict['A'].plot(taufit[0][k], taufit[1][k], 'r-') P.axdict['A'].set_xlim(0, 150.) P.axdict['A'].set_ylabel('V (mV)') P.axdict['A'].set_xticklabels([]) PH.calbar(P.axdict['A'], calbar=[125., -120., 25., 25.], unitNames={'x': 'ms', 'y': 'mV'}) # def calbar(axl, calbar=None, axesoff=True, orient='left', unitNames=None, fontsize=11, weight='normal', font='Arial'): P.axdict['B'].set_xlim(0., 150.) P.axdict['B'].set_xlabel('T (ms)') P.axdict['B'].set_ylabel('I (nA)') PH.calbar(P.axdict['B'], calbar=[125., 0.1, 25., 0.5], unitNames={'x': 'ms', 'y': 'nA'})
def plot(self): P = PH.Plotter((2, 1), figsize=(6, 4)) cell_ax = list(P.axdict.keys())[0] iax = list(P.axdict.keys())[1] for i in range(self.traces.shape[0]): P.axdict[cell_ax].plot(self.time, self.traces.view(np.ndarray)[i], linewidth=1.0) P.axdict[iax].plot(self.time, self.cmd_wave.view(np.ndarray)[i], linewidth=1.0) P.axdict[cell_ax].set_xlim(0., 150.) P.axdict[cell_ax].set_ylim(-200., 50.) PH.calbar(P.axdict[cell_ax], calbar=[120., -95., 25., 20.], axesoff=True, orient='left', unitNames={'x': 'ms', 'y': 'mV'}, font='Arial', fontsize=8) # mpl.savefig(outfile) mpl.show()
def showpicklediv(name): f = open(name, 'r') result = pickle.load(f) f.close() d = result['results'] ncells = len(d) vr = result['cells']['varrange'] fig, ax = mpl.subplots(ncells + 1, 2, figsize=(8.5, 11.)) # fig.set_size_inches(8.5, 11., forward=True) for ni in range(len(d[0]['i'])): ax[-1, 0].plot(d[0]['t'], d[0]['i'][ni], 'k', linewidth=0.5) ax[-1, 0].set_ylim([-2., 2.]) for nc in range(ncells): for ni in range(len(d[nc]['v'])): ax[nc, 0].plot(d[nc]['t'], d[nc]['v'][ni], 'k', linewidth=0.5) ax[nc, 0].set_ylim([-180., 40.]) if ni == 0: ax[nc, 0].annotate('%.2f' % vr[nc], (180., 20.)) PH.nice_plot(ax.ravel().tolist()) PH.noaxes(ax.ravel()[:-1].tolist()) PH.calbar(ax[0, 0], calbar=[120., -130., 25., 50.], axesoff=True, orient='left', unitNames={ 'x': 'ms', 'y': 'mV' }, fontsize=9, weight='normal', font='Arial') PH.calbar(ax[-1, 0], calbar=[120., 0.5, 25., 1.], axesoff=True, orient='left', unitNames={ 'x': 'ms', 'y': 'nA' }, fontsize=9, weight='normal', font='Arial') mpl.show()
def plot_all_events_and_fits(self): P3 = PH.regular_grid(1, 5, order='columns', figsize=(12, 8.), showgrid=False, verticalspacing=0.1, horizontalspacing=0.02, margins={ 'leftmargin': 0.07, 'rightmargin': 0.05, 'topmargin': 0.03, 'bottommargin': 0.05 }, labelposition=(-0.12, 0.95)) idx = [a for a in P3.axdict.keys()] ncol = 5 offset2 = 0. k = 0 for itr in range(len(all_evok)): # for each trace for evok in all_evok[itr]: # for each ok event in that trace P3.axdict[idx[k]].plot([ self.cell_summary['indiv_tb'][itr][0], self.cell_summary['indiv_tb'][itr][-1] ], np.zeros(2) + offset2, 'b--', linewidth=0.3) P3.axdict[idx[k]].plot( self.cell_summary['indiv_tb'][itr], self.cell_summary['allevents'][itr][evok] + offset2, 'k--', linewidth=0.5) P3.axdict[idx[k]].plot( self.cell_summary['indiv_tb'][itr], -self.cell_summary['best_fit'][itr][evok] + offset2, 'r--', linewidth=0.5) if k == 4: k = 0 offset2 += 20. else: k += 1 mpl.show()
def plot_setup(self): sizer = OrderedDict( [ ('A', { 'pos': [0.12, 0.8, 0.35, 0.60] }), # ('A1', {'pos': [0.52, 0.35, 0.35, 0.60]}), ('B', { 'pos': [0.12, 0.35, 0.08, 0.20] }), ('C', { 'pos': [0.60, 0.35, 0.08, 0.20] }), ] ) # dict elements are [left, width, bottom, height] for the axes in the plot. n_panels = len(sizer.keys()) gr = [(a, a + 1, 0, 1) for a in range(0, n_panels) ] # just generate subplots - shape does not matter axmap = OrderedDict(zip(sizer.keys(), gr)) self.P = PH.Plotter((n_panels, 1), axmap=axmap, label=True, figsize=(7., 9.)) self.P.resize(sizer) # perform positioning magic hht = 3 ax0 = self.P.axdict['A'] ax0.set_ylabel('pA', fontsize=9) ax0.set_xlabel('T (ms)', fontsize=9) #self.axdec = P.axdict['A1'] axIntvls = self.P.axdict['B'] axIntvls.set_ylabel('Fraction of Events', fontsize=9) axIntvls.set_xlabel('Interevent Interval (ms)', fontsize=9) axIntvls.set_title('mEPSC Interval Distributon', fontsize=10) axAmps = self.P.axdict['C'] axAmps.set_ylabel('Fraction of Events', fontsize=9) axAmps.set_xlabel('Event Amplitude (pA)', fontsize=9) axAmps.set_title('mEPSC Amplitude Distribution', fontsize=10) self.ax0 = ax0 self.axIntvls = axIntvls self.axAmps = axAmps
def plot_iv(self, pubmode=False): x = -0.08 y = 1.02 sizer = { 'A': { 'pos': [0.05, 0.50, 0.08, 0.78], 'labelpos': (x, y), 'noaxes': False }, 'B': { 'pos': [0.62, 0.30, 0.64, 0.22], 'labelpos': (x, y), 'noaxes': False }, 'C': { 'pos': [0.62, 0.30, 0.34, 0.22], 'labelpos': (x, y) }, 'D': { 'pos': [0.62, 0.30, 0.08, 0.22], 'labelpos': (x, y) }, } # dict pos elements are [left, width, bottom, height] for the axes in the plot. gr = [(a, a + 1, 0, 1) for a in range(0, 4) ] # just generate subplots - shape does not matter axmap = OrderedDict(zip(sizer.keys(), gr)) P = PH.Plotter((4, 1), axmap=axmap, label=True, figsize=(8., 6.)) # PH.show_figure_grid(P.figure_handle) P.resize(sizer) # perform positioning magic # P = PH.regular_grid(2 , 2, order='columns', figsize=(8., 6.), showgrid=False, # verticalspacing=0.1, horizontalspacing=0.12, # margins={'leftmargin': 0.12, 'rightmargin': 0.12, 'topmargin': 0.08, 'bottommargin': 0.1}, # labelposition=(-0.12, 0.95)) P.figure_handle.suptitle(self.datapath, fontsize=8) dv = 50. jsp = 0 for i in range(self.AR.traces.shape[0]): if i in list(self.SP.spikeShape.keys()): idv = float(jsp) * dv jsp += 1 else: idv = 0. P.axdict['A'].plot(self.AR.time_base * 1e3, idv + self.AR.traces[i, :].view(np.ndarray) * 1e3, '-', linewidth=0.35) ptps = np.array([]) paps = np.array([]) if i in list(self.SP.spikeShape.keys()): for j in list(self.SP.spikeShape[i].keys()): paps = np.append(paps, self.SP.spikeShape[i][j]['peak_V'] * 1e3) ptps = np.append(ptps, self.SP.spikeShape[i][j]['peak_T'] * 1e3) P.axdict['A'].plot(ptps, idv + paps, 'ro', markersize=0.5) # mark spikes outside the stimlulus window ptps = np.array([]) paps = np.array([]) for window in ['baseline', 'poststimulus']: ptps = np.array(self.SP.analysis_summary[window + '_spikes'][i]) uindx = [int(u / self.AR.sample_interval) + 1 for u in ptps] paps = np.array(self.AR.traces[i, uindx]) P.axdict['A'].plot(ptps * 1e3, idv + paps * 1e3, 'bo', markersize=0.5) for k in self.RM.taum_fitted.keys(): P.axdict['A'].plot(self.RM.taum_fitted[k][0] * 1e3, self.RM.taum_fitted[k][1] * 1e3, '--k', linewidth=0.30) for k in self.RM.tauh_fitted.keys(): P.axdict['A'].plot(self.RM.tauh_fitted[k][0] * 1e3, self.RM.tauh_fitted[k][1] * 1e3, '--r', linewidth=0.50) if pubmode: PH.calbar(P.axdict['A'], calbar=[0., -90., 25., 25.], axesoff=True, orient='left', unitNames={ 'x': 'ms', 'y': 'mV' }, fontsize=10, weight='normal', font='Arial') P.axdict['B'].plot(self.SP.analysis_summary['FI_Curve'][0] * 1e9, self.SP.analysis_summary['FI_Curve'][1] / (self.AR.tend - self.AR.tstart), 'ko-', markersize=4, linewidth=0.5) clist = ['r', 'b', 'g', 'c', 'm'] # only 5 possiblities linestyle = ['-', '--', '-.', '-', '--'] n = 0 for i, figrowth in enumerate(self.SP.analysis_summary['FI_Growth']): legstr = '{0:s}\n'.format(figrowth['FunctionName']) if len(figrowth['parameters']) == 0: # no valid fit P.axdict['B'].plot([np.nan, np.nan], [np.nan, np.nan], label='No valid fit') else: for j, fna in enumerate(figrowth['names'][0]): legstr += '{0:s}: {1:.3f} '.format( fna, figrowth['parameters'][0][j]) if j in [2, 5, 8]: legstr += '\n' P.axdict['B'].plot(figrowth['fit'][0][0] * 1e9, figrowth['fit'][1][0], linestyle=linestyle[i], color=clist[i], linewidth=0.5, label=legstr) n += 1 if n > 0: P.axdict['B'].legend(fontsize=6) P.axdict['C'].plot(self.RM.ivss_cmd * 1e9, self.RM.ivss_v * 1e3, 'ko-', markersize=4, linewidth=1.0) if not pubmode: if self.RM.analysis_summary['CCComp']['CCBridgeEnable'] == 1: enable = 'On' else: enable = 'Off' tstr = ( r'RMP: {0:.1f} mV {1:s}${{R_{{in}}}}$: {2:.1f} ${{M\Omega}}${3:s}${{\tau_{{m}}}}$: {4:.2f} ms' .format(self.RM.analysis_summary['RMP'], '\n', self.RM.analysis_summary['Rin'], '\n', self.RM.analysis_summary['taum'] * 1e3)) tstr += ( r'{0:s}Holding: {1:.1f} pA{2:s}Bridge [{3:3s}]: {4:.1f} ${{M\Omega}}$' .format( '\n', np.mean(self.RM.analysis_summary['Irmp']) * 1e12, '\n', enable, np.mean(self.RM.analysis_summary['CCComp'] ['CCBridgeResistance'] / 1e6))) tstr += ( r'{0:s}Bridge Adjust: {1:.1f} ${{M\Omega}}$ {2:s}Pipette: {3:.1f} mV' .format( '\n', self.RM.analysis_summary['BridgeAdjust'] / 1e6, '\n', np.mean( self.RM.analysis_summary['CCComp']['CCPipetteOffset'] * 1e3))) P.axdict['C'].text(-0.05, 0.80, tstr, transform=P.axdict['C'].transAxes, horizontalalignment='left', verticalalignment='top', fontsize=7) # P.axdict['C'].xyzero=([0., -0.060]) PH.talbotTicks(P.axdict['A'], tickPlacesAdd={ 'x': 0, 'y': 0 }, floatAdd={ 'x': 0, 'y': 0 }) P.axdict['A'].set_xlabel('T (ms)') P.axdict['A'].set_ylabel('V (mV)') P.axdict['B'].set_xlabel('I (nA)') P.axdict['B'].set_ylabel('Spikes/s') PH.talbotTicks(P.axdict['B'], tickPlacesAdd={ 'x': 1, 'y': 0 }, floatAdd={ 'x': 2, 'y': 0 }) try: maxv = np.max(self.RM.ivss_v * 1e3) except: maxv = 0. # sometimes IVs do not have negative voltages for an IVss to be available... ycross = np.around(maxv / 5., decimals=0) * 5. if ycross > maxv: ycross = maxv PH.crossAxes(P.axdict['C'], xyzero=(0., ycross)) PH.talbotTicks(P.axdict['C'], tickPlacesAdd={ 'x': 1, 'y': 0 }, floatAdd={ 'x': 2, 'y': 0 }) P.axdict['C'].set_xlabel('I (nA)') P.axdict['C'].set_ylabel('V (mV)') for i in range(len(self.SP.spikes)): if len(self.SP.spikes[i]) == 0: continue spx = np.argwhere((self.SP.spikes[i] > self.SP.Clamps.tstart) & ( self.SP.spikes[i] <= self.SP.Clamps.tend)).ravel() spkl = (np.array(self.SP.spikes[i][spx]) - self.SP.Clamps.tstart) * 1e3 # just shorten... if len(spkl) == 1: P.axdict['D'].plot(spkl[0], spkl[0], 'or', markersize=4) else: P.axdict['D'].plot(spkl[:-1], np.diff(spkl), 'o-', markersize=3, linewidth=0.5) PH.talbotTicks(P.axdict['C'], tickPlacesAdd={ 'x': 1, 'y': 0 }, floatAdd={ 'x': 1, 'y': 0 }) P.axdict['D'].set_yscale('log') P.axdict['D'].set_ylim((1.0, P.axdict['D'].get_ylim()[1])) P.axdict['D'].set_xlabel('Latency (ms)') P.axdict['D'].set_ylabel('ISI (ms)') P.axdict['D'].text(0.05, 0.05, 'Adapt Ratio: {0:.3f}'.format( self.SP.analysis_summary['AdaptRatio']), fontsize=9, transform=P.axdict['D'].transAxes, horizontalalignment='left', verticalalignment='bottom') self.IVFigure = P.figure_handle if self.plot: mpl.show()
def summarize_inputs(self): P = PH.regular_grid(2, 3, order='columns', figsize=(10., 8), showgrid=False) ax = [P.axdict[x] for x in P.axdict.keys()] # PH.nice_plot(ax) allendings = [] cellendings = {} for cell, v in self.VCN_Inputs.items(): cellendings[cell] = [] for s in v[1]: if isinstance(s, list) or isinstance(s, tuple): allendings.append(s[0]) cellendings[cell].append(s[0]) else: continue # print('not list or tuple: ', cell, s) # allendings.append(s) # cellendings[cell].append(s) ax[0].set_title('All ending areas') ax[0].hist(allendings, bins=20) ax[0].set_ylim((0, 25)) ax[0].set_ylabel('N') ax[0].set_xlim((0,350)) ax[0].set_xlabel('Area ($um^2$)') normd = [] ratio1 = [] ratio2 = [] meansize = [] maxsize = [] convergence = [] for cell in cellendings.keys(): normd.extend(cellendings[cell]/np.max(cellendings[cell])) ratio1.append(cellendings[cell][1]/cellendings[cell][0]) ratio2.append(np.mean(cellendings[cell])/cellendings[cell][0]) meansize.append(np.mean(cellendings[cell])) maxsize.append(np.max(cellendings[cell])) convergence.append(len(cellendings[cell])) print('convergence: ', convergence) ax[1].set_title('Normalized by largest') ax[1].hist(normd, bins=20, range=(0,1.0), align='mid') ax[1].set_xlabel('Area ($um^2$)') ax[1].set_ylabel('N') ax[2].set_title('Ratio largest to next largest') ax[2].hist(ratio1, bins=10, range=(0,1.0), align='mid') ax[2].set_xlabel('Area ($um^2$)') ax[3].set_title('Ratio of mean to largest') ax[3].hist(ratio2, bins=10, range=(0,1.0), align='mid') ax[3].set_xlabel('Area ($um^2$)') ax[4].set_title('Convergence vs. mean size') ax[4].set_xlim((0., 200.)) ax[4].set_xlabel('Area ($um^2$)') ax[4].set_ylim((0., 15.)) ax[4].set_ylabel('Convergence') fit = np.polyfit(meansize, convergence, 1) fit_fn = np.poly1d(fit) r, p = scipy.stats.pearsonr(meansize, convergence) ax[4].text(x=0.05, y=0.95, s=f"r: {r:.3f}, p={p:.3e}", fontsize=8) ax[4].scatter(meansize, convergence) ax[4].plot(meansize, fit_fn(meansize), '--k') ax[5].set_title('Convergence vs max size') fit = np.polyfit(maxsize, convergence, 1) fit_fn = np.poly1d(fit) r, p = scipy.stats.pearsonr(maxsize, convergence) ax[5].text(x=0.05, y=0.95, s=f"r: {r:.3f}, p={p:.3f}", fontsize=8) ax[5].scatter(maxsize, convergence) ax[5].plot(maxsize, fit_fn(maxsize), '--k') ax[5].set_xlim((0., 350.)) ax[5].set_xlabel('Area ($um^2$)') ax[5].set_ylim((0., 15.)) ax[5].set_xlabel('Convergence') mpl.show()
def run_democlamp(cell, dend, vsteps=[-60,-70,-60], tsteps=[10,50,100]): """ Does some stuff. """ f1 = pylab.figure(1) gs = GS.GridSpec(2, 2, width_ratios=[1, 1], height_ratios=[1, 1]) # note numbering for insets goes from 1 (upper right) to 4 (lower right) # counterclockwise pA = f1.add_subplot(gs[0]) pAi = INSETS.inset_axes(pA, width="66%", height="40%", loc=2) pB = f1.add_subplot(gs[1]) pBi = INSETS.inset_axes(pB, width="66%", height="40%", loc=4) pC = f1.add_subplot(gs[2]) pCi = INSETS.inset_axes(pC, width="66%", height="40%", loc=2) pD = f1.add_subplot(gs[3]) pDi = INSETS.inset_axes(pD, width="66%", height="40%", loc=1) #h.topology() Ld = 0.5 Ld2 = 1.0 VClamp = h.SEClamp(0.5, cell) VClamp.dur1 = tsteps[0] VClamp.amp1 = vsteps[0] VClamp.dur2 = tsteps[1] VClamp.amp2 = vsteps[1] VClamp.dur3 = tsteps[2] VClamp.amp3 = vsteps[2] Rs0 = 10. VClamp.rs = Rs0 compensation = [0., 70., 95.] cms = [cell.cm*(100.-c)/100. for c in compensation] vrec = h.iStim(Ld, sec=dend[0]) vrec.delay = 0 vrec.dur = 1e9 # these actually do not matter... vrec.iMax = 0.0 vrec2 = h.iStim(Ld2, sec=dend[0]) vrec2.delay = 0 vrec2.dur = 1e9 # these actually do not matter... vrec2.iMax = 0.0 stim = {} stim['NP'] = 1 stim['Sfreq'] = 20 # stimulus frequency stim['delay'] = tsteps[0] stim['dur'] = tsteps[1] stim['amp'] = vsteps[1] stim['PT'] = 0.0 stim['hold'] = vsteps[0] # (secmd, maxt, tstims) = make_pulse(stim) tend = 79.5 linetype = ['-', '-', '-'] linethick = [0.5, 0.75, 1.25] linecolor = [[0.66, 0.66, 0.66], [0.4, 0.4, 0.3], 'k'] n = 0 vcmds = [-70, -20] vplots = [(pA, pAi, pC, pCi), (pB, pBi, pD, pDi)] for m, VX in enumerate(vcmds): stim['amp'] = VX pl = vplots[m] print m, VX (secmd, maxt, tstims) = make_pulse(stim) for n, rsc in enumerate(compensation): vec={} for var in ['VCmd', 'i_inj', 'time', 'Vsoma', 'Vdend', 'Vdend2', 'VCmdR']: vec[var] = h.Vector() VClamp.rs = Rs0*(100.-rsc)/100. cell.cm = cms[n] # print VClamp.rs, cell.cm, VClamp.rs*cell.cm vec['VCmd'] = h.Vector(secmd) vec['Vsoma'].record(cell(0.5)._ref_v, sec=cell) vec['Vdend'].record(dend[0](Ld)._ref_v, sec=dend[0]) vec['time'].record(h._ref_t) vec['i_inj'].record(VClamp._ref_i, sec=cell) vec['VCmdR'].record(VClamp._ref_vc, sec=cell) VClamp.amp2 = VX # vec['VCmd'].play(VClamp.amp2, h.dt, 0, sec=cell) h.tstop = tend h.init() h.finitialize(-60) h.run() vc = np.asarray(vec['Vsoma']) tc = np.asarray(vec['time']) # now plot the data, raw and as insets for k in [0, 1]: pl[k].plot(vec['time'], vec['i_inj'], color=linecolor[n], linestyle = linetype[n], linewidth=linethick[n]) yl = pl[k].get_ylim() if k == 0: pass #pl[k].set_ylim([1.5*yl[0], -1.5*yl[1]]) else: pass for k in [2,3]: pl[k].plot(vec['time'], vec['Vsoma'], color=linecolor[n], linestyle = linetype[n], linewidth=linethick[n]) pl[k].plot(vec['time'], vec['VCmdR'], color=linecolor[n], linestyle = '--', linewidth=1, dashes=(1,1)) pl[k].plot(vec['time'], vec['Vdend'], color=linecolor[n], linestyle = linetype[n], linewidth=linethick[n], dashes=(3,3)) if VX < vsteps[0]: pl[k].set_ylim([-72, -40]) else: pl[k].set_ylim([-62,VX+30]) ptx = 10.8 pBi.set_xlim([9.8, ptx]) pAi.set_xlim([9.8, ptx]) PH.setX(pAi, pCi) PH.setX(pBi, pDi) pD.set_ylim([-65, 10]) # PH.setY(pC, pCi) # match Y limits PH.cleanAxes([pA, pAi, pB, pBi, pC, pCi, pD, pDi]) PH.formatTicks([pA, pB, pC, pD], axis='x', fmt='%d') PH.formatTicks([pC, pD], axis='y', fmt='%d') PH.calbar(pAi, [ptx-1, 0, 0.2, 2.]) PH.calbar(pCi, [ptx-1, -50., 0.2, 10]) PH.calbar(pBi, [ptx-1, 0, 0.2, 10]) PH.calbar(pDi, [ptx-1, -50., 0.2, 20]) pylab.draw() pylab.show()
def plot_revcorr(p, ax, ax2, respike=False, thr=-20., width=4.0): d={} basepath = 'VCN_Cells/VCN_{0:s}/Simulations/AN'.format(p) h = open(os.path.join(basepath, fn[p]), 'rb') d[p] = pickle.load(h, ) h.close() seaborn.set_style('ticks') syninfo = SC.VCN_Inputs['VCN_{0:s}'.format(p)] if not respike: st = d[p]['spikeTimes'] else: st = {} # print(d.keys()) # print(d[p].keys()) # print(d[p]['trials'][0].keys()) for k in d[p]['trials'].keys(): trd = d[p]['trials'][k] sv = trd['somaVoltage'] ti = trd['time'] dt = ti[1]-ti[0] st[k] = pu.findspikes(ti, sv, thr, dt=dt, mode='peak') st[k] = clean_spiketimes(st[k]) ndet1 = 0 for n in st: ndet1 = ndet1 + len(st[n]) ndet0 = 0 for n in d[p]['trials'].keys(): st = d[p]['trials'][n]['spikeTimes'] ndet0 = ndet0 + len(st) print(f'Detected {ndet1:d} AN spikes') print(f'Detected {ndet0:d} Postsynaptic spikes') ntrials = len(d[p]['trials'].keys()) print ("# trials: ", ntrials) ninputs = len(syninfo[1]) sites = np.zeros(ninputs) print('ninputs: ', ninputs) binw = 0.1 tcwidth = width # msec for total correlation width xwidth = 5. tx = np.arange(-xwidth, 0, binw) amax = 0. for isite in range(ninputs): # precompute areas area = syninfo[1][isite][0] if area > amax: amax = area sites[isite] = int(np.around(area*SC.synperum2)) summarySiteTC = {} maxtc = 0 for isite in range(ninputs): # for each ANF input (get from those on first trial) for trial in range(ntrials): # sum across trials stx = d[p]['trials'][trial]['spikeTimes'] # get postsynaptic spike train for this trial anx = d[p]['trials'][trial]['inputSpikeTimes'][isite] andirac = np.zeros(int(200./binw)+1) if trial == 0: C = SPKS.correlogram(stx, anx, width=xwidth, bin=binw, T=None) TC = SPKS.total_correlation(anx, stx, width=tcwidth, T=None) if np.isnan(TC): TC = 0. # definition: spike_triggered_average(spikes,stimulus,max_interval,dt,onset=None,display=False): # C = SPKS.spike_triggered_average(st[trial]*ms, andirac*ms, max_interval=width*ms, dt=binw*ms) else: C = C + SPKS.correlogram(stx, anx, width=xwidth, bin=binw, T=None) tct = SPKS.total_correlation(anx, stx, width=tcwidth, T=None) if ~np.isnan(tct): TC = TC + tct # C = C + SPKS.spike_triggered_average(st[trial]*ms, andirac*ms, max_interval=width*ms, dt=binw*ms) nc = int(len(C)/2) TC = TC/len(st) summarySiteTC[isite] = TC color = plt.cm.viridis(norm(sites, isite)) ax.set_facecolor((0.7, 0.7, 0.7)) # print(tx) # print('nc: ', nc) # print(C[:nc]) ax.plot(tx, C[:nc], color=color, label=('Input {0:2d} N={1:3d}'.format(isite, int(sites[isite]))), linewidth=0.75) tx2 = np.array([0.2, 0.8]) ax2.plot(tx2, TC*np.ones_like(tx2), color=color, linewidth=2) if TC > maxtc: maxtc = TC print('finished inputs') seaborn.despine(ax=ax) ax.set_ylabel('Rate of coincidences/bin (Hz)', fontsize=12) ax.set_xlabel('T (ms)', fontsize=12) ax.set_xlim(-5., 1.) ax.set_ylim(0, 1) ax2.set_ylabel('Total Correlation W=%.1f-%0.1f'% (tcwidth[0], tcwidth[1]), fontsize=12) ax2.set_ylim(0, 1.0) # maxtc*1.2) PH.talbotTicks(ax2, axes='xy', density=(1.0, 1.0), insideMargin=0.05, pointSize=10, tickPlacesAdd={'x': 0, 'y': 1}, floatAdd={'x': 0, 'y': 1}) a = re_self.search(fn[p]) b = re_c10.search(fn[p]) if a is not None: inp = 'VCN_c09' elif b is not None: inp = 'VCN_c10' else: inp = "Undefined" ax.set_title(f'VCN_{p:s} input={inp:s} [{int(np.min(sites)):d}-{int(np.max(sites)):d}]\nAmax={amax:.1f}', y=0.9, x=0.02, horizontalalignment='left', fontsize=6) return summarySiteTC, sites
def plot_SAC(): #fig, ax = plt.subplots(len(pattern_list)+1, 3) fig = plt.figure() gs_outer = gridspec.GridSpec(4, 1) # 4 rows, one column gs_inner = [] ax = {} for i, outer in enumerate(gs_outer): gs_inner.append(gridspec.GridSpecFromSubplotSpec(4, 4, subplot_spec=outer)) ax1 = plt.Subplot(fig, gs_inner[-1][:-1, 0]) fig.add_subplot(ax1) ax2 = plt.Subplot(fig, gs_inner[-1][3, 0]) fig.add_subplot(ax2) ax3 = plt.Subplot(fig, gs_inner[-1][:, 1]) fig.add_subplot(ax3) ax4 = plt.Subplot(fig, gs_inner[-1][:, 2]) fig.add_subplot(ax4) ax5 = plt.Subplot(fig, gs_inner[-1][:, 3]) fig.add_subplot(ax5) ax[i] = [ax1, ax2, ax3, ax4, ax5] for a in ax[i]: PH.nice_plot(a) #PH.noaxes(ax1, 'x') #fig.tight_layout() # plt.show() # exit() # d[cell] has keys: ['inputSpikeTimes', 'somaVoltage', 'spikeTimes', 'time', 'dendriteVoltage', 'stimInfo', 'stimWaveform'] #print 'data keys: ', d.keys() #print len(d['time']) fmod = d[patterns[0]]['stimInfo']['mod'] # modulation frequency sacht = 2.5 sacmax = 100 phaseht = 15 #print d['spikeTimes'] for j, pattern in enumerate(patterns): w = d[patterns[j]]['stimWaveform'][0][0].generate() t = d[patterns[j]]['stimWaveform'][0][0].time ax[j][1].plot(t, w) # stimulus underneath for i, st in enumerate(d[pattern]['spikeTimes'].keys()): ax[j][0].plot(d[pattern]['spikeTimes'][st]/1000., i*np.ones(len( d[pattern]['spikeTimes'][st])), 'o', markersize=2.5, color='b') inputs = len(d[pattern]['inputSpikeTimes'][st]) # for j in range(inputs): # t = (d['ref']['inputSpikeTimes'][st][j])/1000. # y = (i+0.1+j*0.05)*np.ones(len(t)) # ax[0,].plot(t, y, 'o', markersize=2.5, color='r') #for i, st in enumerate(d['ref']['somaVoltage'].keys()): # ax[2,].plot(d['ref']['time'], d['ref']['somaVoltage'][st], color='k') ax[j][0].set_xlim((0, 0.8)) ax[j][1].set_xlim((0, 0.8)) sac = SAC.SAC() xf = [] dt = 0.1 u = 2.0*np.pi/(1000.0/fmod) for j, pattern in enumerate(patterns): X = [] R = {} pars = {'twin': 500., 'binw': 1., 'ntestrep': 20, 'baseper': 1.0, 'stimdur': 800., 'delay': 100., 'dur': 1000., 'ddur': 200.} pars_x = pars = {'twin': 500., 'binw': 1., 'ntestrep': 20, 'baseper': 1.0, 'stimdur': 800., 'delay': 100., 'dur': 1000., 'ddur': 200.} tsynch = np.arange(0., 1000., dt) x_spl = [] y_spl = [] Nspikes = 0 for i, st in enumerate(d[pattern]['spikeTimes'].keys()): X.append(d[pattern]['spikeTimes'][st]) xw = np.zeros(tsynch.shape[0]) # print [int(xx/dt) for xx in X[-1]] Nspikes += np.shape(X[-1])[0] # calculate vector strength as well. x_spl.append(np.cos(np.array(X[-1])*u)) y_spl.append(np.sin(np.array(X[-1])*u)) x_spl = np.hstack(x_spl) y_spl = np.hstack(y_spl) vs = np.sqrt(np.sum(x_spl)**2 + np.sum(y_spl)**2)/Nspikes th = np.arctan2(y_spl, x_spl) p, z = PCS.rayleigh(th, w=None, d=None, axis=None) if j == 0: X0 = X # save the X yh, bins = sac.SAC_asm(X, pars) print ('mean vs: for %s at fMod = %.2f: %f angle: %f' % (pattern, fmod, vs, th.mean())) print ('rayleigh: p=%f z=%f (p > 0.05 means data is uniformly distributed)' % (p, z)) ax[j][2].bar(bins[:-1], yh) ax[j][2].set_xlim((-sacmax, sacmax)) ax[j][2].set_ylim((0, sacht)) phasebinnum = 101 phasebins = np.linspace(-0.5, 0.5, num=phasebinnum) thhist, thbins = np.histogram(th/np.pi, bins=phasebins, density=False) ax[j][3].bar(thbins[:-1]+0.5, thhist, width=1.0/phasebinnum) ax[j][3].set_ylim((0, phaseht)) if j == 0: continue ycc, ccbins = sac.XAC(X0, X, pars_x, trialbased=True) ax[j][4].bar(ccbins[:-1], ycc) ax[j][4].set_xlim((-sacmax, sacmax)) # now cross-correlate data... #PH.nice_plot(ax.flatten().tolist()) plt.show()
fn['c{0:s}'.format(g)] = 'AN_Result_VCN_c{0:s}_delays_N050_040dB_4000.0_{1:2s}.p'.format(g, SR) fn['c09'] = 'AN_Result_VCN_c09_inp=self_XM13nacncoop_II_soma=1.489_dend=1.236_all_multisite_050_tonepip_030dB_16000.0_MS.p' # 'AN_Result_VCN_c09_XM13nacncoop_II_soma=1.489_all_multisite_020_tonepip_030dB_16000.0_MS.p' patterns = fn.keys() print ('patterns: ', patterns) p = 'c09' gbcs.append('Summary') # fig, ax = plt.subplots(2, 4, figsize=(10,6)) lmar = 0.1 rmar = -0.01 tmar = 0.01 bmar = 0.08 hspace = 0.05 vspace = 0.1 nplts = len(gbcs) nrows, ncols = PH.getLayoutDimensions(nplts, pref='height') P = PH.regular_grid(nrows, ncols, figsize=(10, 6), panel_labels=gbcs) #PH.Plotter(rcshape=sizer, label=False, figsize=(10 , 6)) P.figure_handle.suptitle('Reverse Correlations, AN types={0:2s}'.format(SR)) ax2 = {} for i, g in enumerate(P.axdict.keys()): if i >= len(gbcs): continue P.axdict[g].set_xlim(-5., 0.) # P.axdict[g].set_axis_bgcolor('gainsboro') P.axdict[g].tick_params(labelsize=6) ax2[g] = twinax(P.figure_handle, P.axdict[g], pos=1.0) for l in P.axlabels: l.set_text(' ') # plt.show()
def plot_vciv(self): P = PH.regular_grid(2, 2, order='columns', figsize=(8., 6.), showgrid=False, verticalspacing=0.1, horizontalspacing=0.12, margins={ 'leftmargin': 0.12, 'rightmargin': 0.12, 'topmargin': 0.08, 'bottommargin': 0.1 }, labelposition=(-0.12, 0.95)) (date, sliceid, cell, proto, p3) = self.file_cell_protocol(self.datapath) P.figure_handle.suptitle(os.path.join(date, sliceid, cell, proto).replace('_', '\_'), fontsize=12) for i in range(self.AR.traces.shape[0]): P.axdict['A'].plot(self.AR.time_base * 1e3, self.AR.traces[i, :] * 1e12, 'k-', linewidth=0.5) PH.talbotTicks(P.axdict['A'], tickPlacesAdd={ 'x': 0, 'y': 0 }, floatAdd={ 'x': 0, 'y': 0 }) P.axdict['A'].set_xlabel('T (ms)') P.axdict['A'].set_ylabel('I (pA)') PH.crossAxes(P.axdict['C'], xyzero=(-60., 0.)) P.axdict['C'].plot(self.vcss_vcmd * 1e3, self.vcss_Im * 1e12, 'ks-', linewidth=1, markersize=4) P.axdict['C'].set_xlabel('V (mV)') P.axdict['C'].set_ylabel('I (pA)') PH.talbotTicks(P.axdict['C'], tickPlacesAdd={ 'x': 0, 'y': 0 }, floatAdd={ 'x': 0, 'y': 0 }) P.axdict['B'].set_xlabel('I (nA)') P.axdict['B'].set_ylabel('V (mV)') PH.talbotTicks(P.axdict['B'], tickPlacesAdd={ 'x': 1, 'y': 0 }, floatAdd={ 'x': 2, 'y': 0 }) P.axdict['D'].set_xlabel('I (pA)') P.axdict['D'].set_ylabel('Latency (ms)') self.IVFigure = P.figure_handle if self.plot: mpl.show()
def summarize_inputs(): import matplotlib.pyplot as mpl import pylibrary.PlotHelpers as PH P = PH.regular_grid(2, 3, order='columns', figsize=(10., 8), showgrid=False) ax = [P.axdict[x] for x in P.axdict.keys()] print(ax) # PH.nice_plot(ax) allendings = [] cellendings = {} for cell, v in iter(VCN_Inputs_Clean.items()): cellendings[cell] = [] for s in v[1]: # print cell, s[0] allendings.append(s[0]) cellendings[cell].append(s[0]) ax[0].hist(allendings, bins=20) ax[0].set_title('All ending areas') ax[0].set_ylim((0, 25)) ax[0].set_ylabel('N') ax[0].set_xlim((0,350)) ax[0].set_xlabel('Area (um^2)') normd = [] ratio1 = [] ratio2 = [] meansize = [] maxsize = [] convergence = [] for cell in cellendings.keys(): normd.extend(cellendings[cell]/np.max(cellendings[cell])) ratio1.append(cellendings[cell][1]/cellendings[cell][0]) ratio2.append(np.mean(cellendings[cell])/cellendings[cell][0]) meansize.append(np.mean(cellendings[cell])) maxsize.append(np.max(cellendings[cell])) convergence.append(len(cellendings[cell])) print('convergence: ', convergence) ax[1].set_title('Normaized by largest') ax[1].hist(normd, bins=20, range=(0,1.0), align='mid') ax[1].set_xlabel('Area (um^2)') ax[1].set_ylabel('N') ax[2].set_title('ratio largest to next largest') ax[2].hist(ratio1, bins=10, range=(0,1.0), align='mid') ax[2].set_xlabel('Area (um^2)') ax[2].set_title('ratio mean to largest') ax[3].set_title('Ratio of mean to largest') ax[3].hist(ratio2, bins=10, range=(0,1.0), align='mid') ax[3].set_xlabel('Area (um^2)') ax[4].set_xlim((0., 200.)) ax[4].set_xlabel('Area (um^2)') ax[4].set_ylim((0., 15.)) ax[4].set_ylabel('Convergence') ax[4].set_title('Convergence vs. mean size') fit = np.polyfit(meansize, convergence, 1) fit_fn = np.poly1d(fit) ax[4].scatter(meansize, convergence) ax[4].plot(meansize, fit_fn(meansize), '--k') ax[5].set_title('Convergence vs max size') fit = np.polyfit(maxsize, convergence, 1) fit_fn = np.poly1d(fit) ax[5].scatter(maxsize, convergence) ax[5].plot(maxsize, fit_fn(maxsize), '--k') ax[5].set_xlim((0., 350.)) ax[5].set_xlabel('Area (um^2)') ax[5].set_ylim((0., 15.)) ax[5].set_xlabel('Convergence') mpl.show()
def showplots(name): """ Show traces from sound stimulation - without current injection """ f = open(name, 'r') d = pickle.load(f) f.close() ncells = len(d['results']) stiminfo = d['stim'] dur = stiminfo['rundur'] * 1000. print 'dur: ', dur print 'stim info: ' print ' fmod: ', stiminfo['fmod'] print ' dmod: ', stiminfo['dmod'] print ' f0: ', stiminfo['f0'] print ' cf: ', stiminfo['cf'] varsg = np.linspace(0.25, 2.0, int((2.0 - 0.25) / 0.25) + 1) # was not stored... fig, ax = mpl.subplots(ncells + 1, 2, figsize=(8.5, 11.)) spikelists = [[]] * ncells prespikes = [[]] * ncells xmin = 50. for i in range(ncells): vdat = d['results'][i]['v'] idat = d['results'][i]['i'] tdat = d['results'][i]['t'] pdat = d['results'][i]['pre'] PH.noaxes(ax[i, 0]) # if i == 0: # PH.calbar(ax[0, 0], calbar=[120., -120., 25., 20.], axesoff=True, orient='left', # unitNames={'x': 'ms', 'y': 'mV'}, fontsize=9, weight='normal', font='Arial') for j in range(len(vdat)): if j == 2: ax[i, 0].plot(tdat - xmin, vdat[j], 'k', linewidth=0.5) if j == 0: ax[i, 0].annotate('%.2f' % varsg[i], (180., 20.)) ax[i, 0].set_xlim([0, dur - xmin]) ax[i, 0].set_ylim([-75, 50]) PH.referenceline(ax[i, 0], reference=-62.0, limits=None, color='0.33', linestyle='--', linewidth=0.5, dashes=[3, 3]) for j in range(len(vdat)): detected = PU.findspikes(tdat, vdat[j], -20.) detected = clean_spiketimes(detected) spikelists[i].extend(detected) if j == 0: n, bins = np.histogram(detected, np.linspace(0., dur, 201), density=False) else: m, bins = np.histogram(detected, np.linspace(0., dur, 201), density=False) n += m prespikes[i].extend(pdat) if j == 0: n, bins = np.histogram(pdat, np.linspace(0., dur, 201), density=False) else: m, bins = np.histogram(pdat, np.linspace(0., dur, 201), density=False) n += m ax[i, 1].bar(bins[:-1] - xmin, n, width=bins[1], facecolor='k', alpha=0.75) ax[i, 1].set_xlim([0, dur - xmin]) ax[i, 1].set_ylim([0, 30]) vs = PU.vector_strength(spikelists[i], stiminfo['fmod']) pre_vs = PU.vector_strength(prespikes[i], stiminfo['fmod']) # print 'pre: ', pre_vs # print 'post: ', vs # apos = ax[i,1].get_position() # ax[i, 1].set_title('VS = %4.3f' % pre_vs['r']) # # vector_plot(fig, vs['ph'], np.ones(len(vs['ph'])), yp = apos) # phase_hist(fig, vs['ph'], yp=apos) # phase_hist(fig, pre_vs['ph'], yp=apos) prot = Variations(runtype, runname) # stim_info = {'nreps': nrep, 'cf': cf, 'f0': f0, 'rundur': rundur, 'pipdur': pipdur, 'dbspl': dbspl, 'fmod': fmod, 'dmod': dmod} if stiminfo['dmod'] > 0: stimulus = 'SAM' else: stimulus = 'tone' prot.make_stimulus(stimulus=stimulus, cf=stiminfo['cf'], f0=stiminfo['f0'], simulator=None, rundur=stiminfo['rundur'], pipdur=stiminfo['pipdur'], dbspl=stiminfo['dbspl'], fmod=stiminfo['fmod'], dmod=stiminfo['dmod']) ax[-1, 1].plot(prot.stim.time * 1000. - xmin, prot.stim.sound, 'k-', linewidth=0.75) ax[-1, 1].set_xlim([0, (dur - xmin)]) PH.noaxes(ax[-1, 0]) ax[-1, 0].set_xlim([0, dur - xmin]) ax[-1, 0].set_ylim([-75, 50]) # PH.referenceline(ax[-1, 0], reference=-62.0, limits=None, color='0.33', linestyle='--' ,linewidth=0.5, dashes=[3, 3]) PH.calbar(ax[-1, 0], calbar=[20., 0., 25., 20.], axesoff=True, orient='left', unitNames={ 'x': 'ms', 'y': 'mV' }, fontsize=9, weight='normal', font='Arial') PH.cleanAxes(ax.ravel().tolist()) mpl.show()
def plot_individual_events(self, fit_err_limit=1000., tau2_range=2.5, title='', pdf=None): P = PH.regular_grid(3, 3, order='columns', figsize=(8., 8.), showgrid=False, verticalspacing=0.1, horizontalspacing=0.12, margins={ 'leftmargin': 0.12, 'rightmargin': 0.12, 'topmargin': 0.03, 'bottommargin': 0.1 }, labelposition=(-0.12, 0.95)) P.figure_handle.suptitle(title) all_evok = self.cell_summary[ 'indiv_evok'] # this is the list of ok events - a 2d list by all_notok = self.cell_summary['indiv_notok'] # print('all evok: ', all_evok) # print('len allevok: ', len(all_evok)) # # # print('all_notok: ', all_notok) # # print('indiv tau1: ', self.cell_summary['indiv_tau1']) # exit(1) trdat = [] trfit = [] trdecfit = [] for itr in range(len(all_evok)): # for each trace for evok in all_evok[itr]: # for each ok event in that trace P.axdict['A'].plot(self.cell_summary['indiv_tau1'][itr][evok], self.cell_summary['indiv_amp'][itr][evok], 'ko', markersize=3) P.axdict['B'].plot(self.cell_summary['indiv_tau2'][itr][evok], self.cell_summary['indiv_amp'][itr][evok], 'ko', markersize=3) P.axdict['C'].plot(self.cell_summary['indiv_tau1'][itr][evok], self.cell_summary['indiv_tau2'][itr][evok], 'ko', markersize=3) P.axdict['D'].plot( self.cell_summary['indiv_amp'][itr][evok], self.cell_summary['indiv_fiterr'][itr][evok], 'ko', markersize=3) P.axdict['H'].plot( self.cell_summary['indiv_tau1'][itr][evok], self.cell_summary['indiv_Qtotal'][itr][evok], 'ko', markersize=3) trdat.append( np.column_stack([ self.cell_summary['indiv_tb'][itr], self.cell_summary['allevents'][itr][evok] ])) #idl = len(self.cell_summary['best_decay_fit'][itr][evok]) trfit.append( np.column_stack([ self.cell_summary['indiv_tb'][itr], -self.cell_summary['best_fit'][itr][evok] ])) trdecfit.append( np.column_stack([ self.cell_summary['indiv_tb'][itr], -self.cell_summary['best_decay_fit'][itr][evok] ])) dat_coll = collections.LineCollection(trdat, colors='k', linewidths=0.5) fit_coll = collections.LineCollection(trfit, colors='r', linewidths=0.25) # decay_fit_coll = collections.LineCollection(trdecfit, colors='c', linewidths=0.3) P.axdict['G'].add_collection(dat_coll) P.axdict['G'].add_collection(fit_coll) # P.axdict['G'].add_collection(decay_fit_coll) n_trdat = [] n_trfit = [] for itr in range(len(all_notok)): for notok in all_notok[itr]: n_trdat.append( np.column_stack([ self.cell_summary['indiv_tb'][itr], self.cell_summary['allevents'][itr][notok] ])) n_trfit.append( np.column_stack([ self.cell_summary['indiv_tb'][itr], -self.cell_summary['best_fit'][itr][notok] ])) P.axdict['D'].plot( self.cell_summary['indiv_amp'][itr][notok], self.cell_summary['indiv_fiterr'][itr][notok], 'ro', markersize=3) n_dat_coll = collections.LineCollection(n_trdat, colors='b', linewidths=0.35) n_fit_coll = collections.LineCollection(n_trfit, colors='y', linewidths=0.25) P.axdict['E'].add_collection(n_dat_coll) P.axdict['E'].add_collection(n_fit_coll) P.axdict['A'].set_xlabel(r'$tau_1$ (ms)') P.axdict['A'].set_ylabel(r'Amp (pA)') P.axdict['B'].set_xlabel(r'$tau_2$ (ms)') P.axdict['B'].set_ylabel(r'Amp (pA)') P.axdict['C'].set_xlabel(r'$\tau_1$ (ms)') P.axdict['C'].set_ylabel(r'$\tau_2$ (ms)') P.axdict['D'].set_xlabel(r'Amp (pA)') P.axdict['D'].set_ylabel(r'Fit Error (cost)') P.axdict['H'].set_xlabel(r'$\tau_1$ (ms)') P.axdict['H'].set_ylabel(r'Qtotal') P.axdict['G'].set_ylim((-100., 20.)) P.axdict['G'].set_xlim((-2., 25.)) P.axdict['E'].set_ylim((-100., 20.)) P.axdict['E'].set_xlim((-2., 25.)) # put in averaged event too # self.cell_summary['averaged'].extend([{'tb': aj.avgeventtb, 'avg': aj.avgevent, 'fit': {'amplitude': aj.Amplitude, # 'tau1': aj.tau1, 'tau2': aj.tau2, 'risepower': aj.risepower}, 'best_fit': aj.avg_best_fit, # 'risetenninety': aj.risetenninety, 'decaythirtyseven': aj.decaythirtyseven}]) aev = self.cell_summary['averaged'] for i in range(len(aev)): P.axdict['F'].plot(aev[i]['tb'], aev[i]['avg'], 'k-', linewidth=0.8) P.axdict['F'].plot(aev[i]['tb'], aev[i]['best_fit'], 'r--', linewidth=0.4) if pdf is None: mpl.show() else: pdf.savefig(dpi=300) mpl.close()
def plot(self): sizer = OrderedDict( [ ('A', { 'pos': [0.12, 0.2, 0.15, 0.5] }), ('B', { 'pos': [0.45, 0.2, 0.15, 0.5] }), ('C', { 'pos': [0.72, 0.2, 0.15, 0.5] }), ] ) # dict elements are [left, width, bottom, height] for the axes in the plot. n_panels = len(sizer.keys()) gr = [(a, a + 1, 0, 1) for a in range(0, n_panels) ] # just generate subplots - shape does not matter axmap = OrderedDict(zip(sizer.keys(), gr)) P = PH.Plotter((n_panels, 1), axmap=axmap, label=True, labeloffset=[-0.15, 0.08], fontsize={ 'tick': 8, 'label': 10, 'panel': 14 }, figsize=(5., 3.)) P.resize(sizer) # perform positioning magic # P.axdict['A'].plot(np.ones(len(self.intvls[self.group_names[0]])), 1000./np.array(self.intvls[self.group_names[0]]), # 'ko', markersize=4.0, label=self.group_names[0]) # P.axdict['A'].plot(1+np.ones(len(self.intvls[self.group_names[1]])), 1000./np.array(self.intvls[self.group_names[1]]), # 'bs', markersize=4.0, label=self.group_names[1]) # P.axdict['B'].plot(np.ones(len(self.amps[self.group_names[0]])), self.amps[self.group_names[0]], # 'ko', markerfacecolor='k', markeredgecolor='k', markersize=4.0, markeredgewidth=1) # P.axdict['B'].plot(1.0 + np.ones(len(self.amps[self.group_names[1]])), self.amps[self.group_names[1]], # 'bs', markerfacecolor='b', markeredgecolor='b', markersize=4.0, markeredgewidth=1) # P.axdict['B'].plot(0.2 + np.ones(len(self.meanamps[self.group_names[0]])), self.meanamps[self.group_names[0]], # 'ko', markerfacecolor='w', markeredgecolor='k', markersize=4.0, markeredgewidth=1) # P.axdict['B'].plot(1.2 + np.ones(len(self.meanamps[self.group_names[1]])), self.meanamps[self.group_names[1]], # 'bs', markerfacecolor='w', markeredgecolor='b', markersize=4.0, markeredgewidth=1) for a in ['A', 'B', 'C']: PH.formatTicks(P.axdict[a], font='Helvetica') sns.swarmplot(x='Genotype', y='Intvls', data=self.pddata, ax=P.axdict['A']) sns.boxplot(x='Genotype', y='Intvls', data=self.pddata, ax=P.axdict['A'], color="0.8") sns.swarmplot(x='Genotype', y='Amp', data=self.pddata, ax=P.axdict['B']) sns.boxplot(x='Genotype', y='Amp', data=self.pddata, ax=P.axdict['B'], color="0.8") sns.swarmplot(x='Genotype', y='MeanAmp', data=self.pddata, ax=P.axdict['C']) sns.boxplot(x='Genotype', y='MeanAmp', data=self.pddata, ax=P.axdict['C'], color="0.8") P.axdict['A'].set_ylim(0.0, 25.) P.axdict['A'].set_ylabel('Event Frequency (Hz)') P.axdict['B'].set_ylim(0.0, 30.) P.axdict['B'].set_ylabel('Median Amplitude (pA)') P.axdict['C'].set_ylabel('Mean Amplitude (pA)') P.axdict['C'].set_ylim(0.0, 30.) # P.axdict['A'].set_xlabel('Group') # P.axdict['B'].set_xlabel('Group') # P.axdict['A'].set_xlim(0.5, 2.5) # P.axdict['B'].set_xlim(0.5, 2.5) # P.axdict['B'].set_xlim(0.5, 2.5) # P.axdict['A'].legend() P.figure_handle.suptitle(self.filename.replace('_', '\_')) mpl.savefig('msummary_%s.pdf' % self.experiment_id) mpl.show()
def plotSingles(inpath, cmd): seaborn.set_style('ticks') print( cmd['cell']) sites, celltype = CFG.makeDict(cmd['cell']) # print sites nInputs = 0 for s in sites: nInputs += len(s['postlocations'].keys()) #nInputs = len(sites) print ('cell: ', cmd['cell'], ' nInputs: ', nInputs) nrow, ncol = get_dimensions(nInputs, pref='width') nimax = 4 if nInputs > nimax: nshow = nimax else: nshow = nInputs fig, ax = plt.subplots(nshow, 1, figsize=(2.5,4)) fig.suptitle('{0:s} SR: {1:s}'.format(cmd['cell'], cmd['SR'])) vmax = -50. template = synfile_template tmin = -100. trange = [-50., 100.] if cmd['analysis'] == 'omit': template = excsynfile_template if cmd['analysis'] == 'io': template = synIOfile_template tmin = 0. trange = [0., 50.] fig2, ax2 = plt.subplots(2, 2, figsize=(4.75,6)) fig2.suptitle('{0:s} SR: {1:s}'.format(cmd['cell'], cmd['SR'])) axr = ax2.ravel() if cmd['analysis'] == 'singles': tmin = 25. template = synfile_template for i in range(nInputs): print(template) fname = template.format(cmds['cell'], modeltype, i, int(cmds['nReps']), cmds['SR']) fname = os.path.join(inpath, fname) print (fname) try: spikeTimes, inputSpikeTimes, stimInfo, d = readFile(fname, cmd) except: print('Missing: ', fname) continue #print ('stiminfo: ', stimInfo) if cmd['respike']: spiketimes = {} for k in d['somaVoltage'].keys(): dt = d['time'][1]-d['time'][0] spikeTimes[k] = pu.findspikes(d['time'], d['somaVoltage'][k], thresh=cmd['threshold']) spikeTimes[k] = clean_spiketimes(spikeTimes[k]) nReps = stimInfo['nReps'] if i < nshow: pl = ax[i] pl.set_title('Input {0:d}: N sites: {1:d}'.format(i+1, sites[i]['nSyn']), fontsize=8, x=0.05, y=0.92, horizontalalignment = 'left', verticalalignment='top') PH.noaxes(pl) sv = d['somaVoltage'] tm = d['time'] for j in range(nReps): m = np.max(sv[j]) if m > vmax: vmax = m vmax = 00. # print('tmin, minsv, maxsv', tmin, np.min(sv[j]), np.max(sv[j])) imin = int(tmin/np.mean(np.diff(d['time']))) for j in range(nReps): if j > nshow: continue # print('Rep, tmin, minsv, maxsv', j, tmin, np.min(sv[j]), np.max(sv[j]), tm.shape, sv[j].shape) pv = pl.plot(tm[imin:]-tmin, sv[j][imin:], linewidth=0.8) # pl.vlines(spikeTimes[j]-tmin, -j*2+vmax, -j*2-2+vmax, # color=pv[0].get_c(), linewidth=1.5) # spike marker same color as trace pl.set_ylabel('mV') pl.set_ylim(-80., vmax) pl.set_xlim(np.min(tm-tmin), np.max(tm-tmin)) if pl != ax[-1]: pl.set_xticklabels([]) else: plt.setp(pl.get_xticklabels(), fontsize=9) pl.set_xlabel('ms') # if cmd['analysis'] == 'io': # plt.setp(pl.get_yticklabels(), fontsize=9) # iof = np.zeros(len(sv.keys())) # iofdv = np.zeros(len(sv.keys())) # for k in sv.keys(): # iof[k] = np.max(sv[k]) # iofdv[k] = np.max(np.diff(sv[k])/np.mean(np.diff(tm))) # axr[0].plot(stimInfo['gSyns'], iof, 'o-', markersize=4) # axr[1].plot(stimInfo['gSyns'], iofdv, 's-', markersize=4) # axr.set_title('Input {0:d}: N sites: {1:d}'.format(i+1, sites[i]['nSyn']), fontsize=8, x=0.05, y=0.92, # horizontalalignment = 'left', verticalalignment='top') PH.calbar(ax[-1], calbar=[np.min(tm-tmin)+150, -40., 20., 25.], unitNames={'x': 'ms', 'y': 'mV'}) # for i in range(nInputs): # rescale all plots the same # ax[i].set_ylim(-65., vmax+cmd['nReps']*3) # ax[0].set_ylim(-65., vmax) seaborn.despine(fig) plt.savefig('VCN_c09.pdf')
def plotResults(self, res, runInfo, somasite=['postsynapticV', 'postsynapticI', 'dendriteV']): clist={'axon': 'r', 'heminode': 'g', 'stalk':'y', 'branch': 'g', 'neck': 'b', 'swelling': 'm', 'tip': 'k', 'parentaxon': '', r'synapse': 'c', 'Soma': 'k', 'dendrite': 'c', 'dend': 'c'} dx = np.array([x for k,x in res['distanceMap'].items()]) dlen = res['monitor']['postsynapticV'].shape[0] dxmax = np.max(dx) if self.plotmode == 'pg': self.plots['Soma'].setLabel('left', 'V') self.plots['Soma'].plot(res['monitor']['time'][:dlen], res['monitor']['postsynapticV'], pen=pg.mkPen(clist['Soma'], width=0.5), ) if 'dendriteV' in somasite and self.plots['Dendrite'] is not None and len(res['monitor']['dendriteV']) > 0: self.plots['Dendrite'].plot(res['monitor']['time'][:dlen], res['monitor']['dendriteV'], pen=pg.mkPen(clist['dendrite'], width=0.5), ) self.plots['Dendrite'].setLabel('left', 'V (mV)') if 'vec' in res.keys()and self.plots['p4'] is not None: for v in res['vec']: self.plots['p4'].plot(res['monitor']['time'], res['vec'][v], pen=pg.mkPen(pg.intColor(int(255.*res['distanceMap'][v]/dxmax))), width=1.5) if 'postsynapticI' in somasite and self.plots['Iinj'] is not None: vlen = len(res['monitor']['postsynapticI']) self.plots['Iinj'].plot(res['monitor']['time'][0:vlen], res['monitor']['postsynapticI'], pen = pg.mkPen('b', width=0.5)) self.plots['Iinj'].setLabel('left', 'I (inj, nA)') if 'vec' in res.keys() and self.plots['p4'] is not None: for v in res['vec']: self.plots['p4'].plot(res['monitor']['time'], res['vec'][v], pen=pg.mkPen(pg.intColor(int(255.*res['distanceMap'][v]/dxmax))), width=0.5) #for c in res['ICa']: # self.plots['Dendrite'].plot(res['monitor']['time'], res['ICa'][c]*1e12, pen=pg.mkPen('b', width=1.5)) # self.plots['Iinj'].plot(res['vec']['time'], res['Cai'][c]*1e6, pen=pg.mkPen('g', width=1.5)) #p2.set_ylim(-5e-12, 1e-12) self.plots['Soma'].setXRange(0., 120., padding=0.2) self.plots['Dendrite'].setXRange(0., 120., padding=0.2) if self.plots['Iinj'] is not None: self.plots['Iinj'].setXRange(0., 120., padding=0.2) pgPH.cleanAxes([self.plots['Soma'], self.plots['Dendrite'], self.plots['Iinj'], self.plots['p4']]) pgPH.nice_plot(self.plots['Soma']) pgPH.calbar(self.plots['Soma'], [110, -50, 20, 50]) # pgPH.nice_plot(self.plots['Dendrite']) # pgPH.calbar(self.plots['Dendrite'], [110, 0.1, 20, 1]) if self.plots['Iinj'] is not None: pgPH.nice_plot(self.plots['Iinj']) pgPH.calbar(self.plots['Iinj'], [110, -0.1, 20, 1]) elif self.plotmode == 'mpl': self.plots['Soma'].set_ylabel('V') self.plots['Soma'].plot(res['monitor']['time'][:dlen], res['monitor']['postsynapticV'], color=clist['Soma'], linewidth=0.5) if 'dendriteV' in somasite and self.plots['Dendrite'] is not None and len(res['monitor']['dendriteV']) > 0: self.plots['Dendrite'].plot(res['monitor']['time'][:dlen], res['monitor']['dendriteV'], color=clist['dendrite'], linewidth=0.5) self.plots['Dendrite'].set_ylabel('V (mV)') if 'vec' in res.keys()and self.plots['p4'] is not None: for v in res['vec']: self.plots['p4'].plot(res['monitor']['time'], res['vec'][v], color=[[int(255.*res['distanceMap'][v]/dxmax)]*3], linewidth=0.75) if 'postsynapticI' in somasite and self.plots['Iinj'] is not None: vlen = len(res['monitor']['postsynapticI']) self.plots['Iinj'].plot(res['monitor']['time'][0:vlen], res['monitor']['postsynapticI'], color='b', linewidth=0.5) self.plots['Iinj'].set_ylabel('I (inj, nA)') if 'vec' in res.keys() and self.plots['p4'] is not None: for v in res['vec']: self.plots['p4'].plot(res['monitor']['time'], res['vec'][v], color=[[int(255.*res['distanceMap'][v]/dxmax)]*3], linewidth=0.75) #for c in res['ICa']: # self.plots['Dendrite'].plot(res['monitor']['time'], res['ICa'][c]*1e12, pen=pg.mkPen('b', width=1.5)) # self.plots['Iinj'].plot(res['vec']['time'], res['Cai'][c]*1e6, pen=pg.mkPen('g', width=1.5)) #p2.set_ylim(-5e-12, 1e-12) self.plots['Soma'].set_xlim(0., 120.) self.plots['Dendrite'].set_xlim(0., 120.) if self.plots['Iinj'] is not None: self.plots['Iinj'].set_xlim(0., 120.) PH.cleanAxes([self.plots['Soma'], self.plots['Dendrite'], self.plots['Iinj']]) PH.nice_plot(self.plots['Soma']) PH.calbar(self.plots['Soma'], [110, -50, 20, 50]) PH.nice_plot(self.plots['Dendrite']) PH.calbar(self.plots['Dendrite'], [110, -50, 20, 50]) # pgPH.nice_plot(self.plots['Dendrite']) # pgPH.calbar(self.plots['Dendrite'], [110, 0.1, 20, 1]) if self.plots['Iinj'] is not None: PH.nice_plot(self.plots['Iinj']) PH.calbar(self.plots['Iinj'], [110, -0.1, 20, 1])
('VCN_c14', {'pos': [l1, wid, yp[3], ht]}), ('VCN_c16', {'pos': [l1, wid, yp[4], ht]}), ('VCN_c17', {'pos': [l2, wid, yp[5], ht]}), ('VCN_c18', {'pos': [l2, wid, yp[0], ht]}), ('VCN_c19', {'pos': [l2, wid, yp[1], ht]}), ('VCN_c20', {'pos': [l2, wid, yp[3], ht]}), ('VCN_c21', {'pos': [l1, wid, yp[4], ht]}), ('VCN_c22', {'pos': [l2, wid, yp[5], ht]}), ('None', {}), ]) # dict elements are [left, width, bottom, height] for the axes in the plot. # gr = [(a, a+1, 0, 1) for a in range(0, 8)] # just generate subplots - shape does not matter gbc_names = [s[-2:] for s in sizer.keys()] gbc_names = ['09'] P = PH.regular_grid(6, 2, figsize=(6,8), panel_labels=list(sizer.keys()), labelposition=(0.05, 0.95)) # P = PH.Plotter(rcshape=sizer, label=False, figsize=(6, 8), labeloffset=[0.6, 0.]) inputPattern = "VCN_c10" # None # 'VCN_c10' for gbc in gbc_names: if gbc == 'ne': continue print ('='*32) cell = 'VCN_c{0:s}'.format(gbc) # an_result_file = 'AN_Result_VCN_c{0:s}_delays_N{1:03d}_040dB_4000.0_{2:2s}.p'.format(gbc, nrep, SR) # andatafile = Path(baseDirectory, cell, simDirectory, 'AN', an_result_file) # print(' an result file: {0:s}'.format(str(andatafile))) # print (andatafile.is_file() ) # if not andatafile.is_file() or forcerun: # only run if no evidence we have run this already