Exemple #1
0
    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 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
Exemple #3
0
    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()