Example #1
0
def fig_exc_inh_contrib(fig, axes, params, savefolders, T=[800, 1000], transient=200,
                        panel_labels = 'FGHIJ', show_xlabels=True):
    '''
    plot time series LFPs and CSDs with signal variances as function of depth
    for the cases with all synapses intact, or knocking out excitatory
    input or inhibitory input to the postsynaptic target region
    
    args:
    ::
        fig : 
        axes :  
        savefolders : list of simulation output folders
        T : list of ints, first and last time sample
        transient : int, duration of transient period
        
    returns:
    ::
        
        matplotlib.figure.Figure object
    
    '''
    # params = multicompartment_params()
    # ana_params = analysis_params.params()

    
    #file name types
    file_names = ['CSDsum.h5', 'LFPsum.h5']
    
    #panel titles
    panel_titles = [
        'LFP&CSD\nexc. syn.',
        'LFP&CSD\ninh. syn.',
        'LFP&CSD\ncompound',
        'CSD variance',
        'LFP variance',]
    
    #labels
    labels = [
        'exc. syn.',
        'inh. syn.',
        'SUM']
    
    #some colors for traces
    if analysis_params.bw:
        colors = ['k', 'gray', 'k']
        # lws = [0.75, 0.75, 1.5]
        lws = [1.25, 1.25, 1.25]
    else:
        colors = [analysis_params.colorE, analysis_params.colorI, 'k']
        # colors = 'rbk'
        # lws = [0.75, 0.75, 1.5]
        lws = [1.25, 1.25, 1.25]

    
    #scalebar labels
    units = ['$\mu$A mm$^{-3}$', 'mV']
    
    #depth of each contact site
    depth = params.electrodeParams['z']


    # #set up figure
    # #figure aspect
    # ana_params.set_PLOS_2column_fig_style(ratio=0.5)
    # fig, axes = plt.subplots(1,5)
    # fig.subplots_adjust(left=0.06, right=0.96, wspace=0.4, hspace=0.2)
    
    #clean up
    for ax in axes.flatten():
        phlp.remove_axis_junk(ax)


    for i, file_name in enumerate(file_names):
        #get the global data scaling bar range for use in latter plots
        #TODO: find nicer solution without creating figure
        dum_fig, dum_ax = plt.subplots(1)
        vlim_LFP = 0
        vlim_CSD = 0
        for savefolder in savefolders:
            vlimround0 = plot_signal_sum(dum_ax, params,
                                         os.path.join(os.path.split(params.savefolder)[0], savefolder, file_name),
                                         rasterized=False)
            if vlimround0 > vlim_LFP:
                vlim_LFP = vlimround0
            im = plot_signal_sum_colorplot(dum_ax, params, os.path.join(os.path.split(params.savefolder)[0], savefolder, file_name),
                                           cmap=plt.get_cmap('gray', 21) if analysis_params.bw else plt.get_cmap('bwr_r', 21),
                                           rasterized=False)
            if abs(im.get_array()).max() > vlim_CSD:
                vlim_CSD = abs(im.get_array()).max()
                                                  
        plt.close(dum_fig)


        for j, savefolder in enumerate(savefolders):
            ax = axes[j]
            if i == 1:
                plot_signal_sum(ax, params, os.path.join(os.path.split(params.savefolder)[0], savefolder, file_name),
                            unit=units[i], T=T,
                            color='k',
                            # color='k' if analysis_params.bw else colors[j],
                            vlimround=vlim_LFP, rasterized=False)
            elif i == 0:
                im = plot_signal_sum_colorplot(ax, params, os.path.join(os.path.split(params.savefolder)[0], savefolder, file_name),
                              unit=r'($\mu$Amm$^{-3}$)', T=T, ylabels=True,
                              colorbar=False,
                              fancy=False, cmap=plt.get_cmap('gray', 21) if analysis_params.bw else plt.get_cmap('bwr_r', 21),
                              absmax=vlim_CSD,
                              rasterized=False)
            
            
            ax.axis((T[0], T[1], -1550, 50))
            ax.set_title(panel_titles[j], va='baseline')
            
            if i == 0:
                phlp.annotate_subplot(ax, ncols=1, nrows=1, letter=panel_labels[j])
            if j != 0:
                ax.set_yticklabels([])
            
            if i == 0:#and j == 2:
                cb = phlp.colorbar(fig, ax, im,
                                   width=0.05, height=0.5,
                                   hoffset=-0.05, voffset=0.5)
                cb.set_label('($\mu$Amm$^{-3}$)', labelpad=0.)
            ax.xaxis.set_major_locator(plt.MaxNLocator(3))
            if show_xlabels:
                ax.set_xlabel(r'$t$ (ms)', labelpad=0.)
            else:
                ax.set_xlabel('')

            
    #power in CSD
    ax = axes[3]
    datas = []    
    for j, savefolder in enumerate(savefolders):
        f = h5py.File(os.path.join(os.path.split(params.savefolder)[0], savefolder, 'CSDsum.h5'))
        var = f['data'][()][:, transient:].var(axis=1)
        ax.semilogx(var, depth,
                    color=colors[j], label=labels[j], lw=lws[j], clip_on=False)
        datas.append(f['data'][()][:, transient:])
        f.close()
    #control variances
    vardiff = datas[0].var(axis=1) + datas[1].var(axis=1) + np.array([2*np.cov(x,y)[0,1] for (x,y) in zip(datas[0], datas[1])]) - datas[2].var(axis=1)
    #ax.semilogx(abs(vardiff), depth, color='gray', lw=1, label='control')
    ax.axis(ax.axis('tight'))
    ax.set_ylim(-1550, 50)
    ax.set_yticks(-np.arange(16)*100)
    if show_xlabels:
        ax.set_xlabel(r'$\sigma^2$ ($(\mu$Amm$^{-3})^2$)', labelpad=0.)
    ax.set_title(panel_titles[3], va='baseline')
    phlp.annotate_subplot(ax, ncols=1, nrows=1, letter=panel_labels[3])
    ax.set_yticklabels([])


    #power in LFP
    ax = axes[4]

    datas = []
    for j, savefolder in enumerate(savefolders):
        f = h5py.File(os.path.join(os.path.split(params.savefolder)[0], savefolder, 'LFPsum.h5'))
        var = f['data'][()][:, transient:].var(axis=1)
        ax.semilogx(var, depth,
                    color=colors[j], label=labels[j], lw=lws[j], clip_on=False)
        datas.append(f['data'][()][:, transient:])
        f.close()
    #control variances
    vardiff = datas[0].var(axis=1) + datas[1].var(axis=1) + np.array([2*np.cov(x,y)[0,1] for (x,y) in zip(datas[0], datas[1])]) - datas[2].var(axis=1)
    ax.axis(ax.axis('tight'))
    ax.set_ylim(-1550, 50)
    ax.set_yticks(-np.arange(16)*100)
    if show_xlabels:
        ax.set_xlabel(r'$\sigma^2$ (mV$^2$)', labelpad=0.)
    ax.set_title(panel_titles[4], va='baseline')
    phlp.annotate_subplot(ax, ncols=1, nrows=1, letter=panel_labels[4])

    ax.legend(bbox_to_anchor=(1.3, 1.0), frameon=False)
    ax.set_yticklabels([])
Example #2
0
def plot_multi_scale_output_b(fig, X='L5E'):
    '''docstring me'''

    show_ax_labels = True
    show_insets = False
    show_images = False

    T=[800, 1000]
    T_inset=[900, 920]

    
    left = 0.075
    bottom = 0.05
    top = 0.475
    right = 0.95
    axwidth = 0.16
    numcols = 4
    insetwidth = axwidth/2
    insetheight = 0.5
    
    lefts = np.linspace(left, right-axwidth, numcols)
    lefts += axwidth/2



    #lower row of panels
    #fig = plt.figure()
    #fig.subplots_adjust(left=0.12, right=0.9, bottom=0.36, top=0.9, wspace=0.2, hspace=0.3)

    ############################################################################    
    # E part, soma locations
    ############################################################################

    ax4 = fig.add_axes([lefts[0], bottom, axwidth, top-bottom], frameon=False)
    plt.locator_params(nbins=4)
    ax4.xaxis.set_ticks([])
    ax4.yaxis.set_ticks([])
    if show_ax_labels:
        phlp.annotate_subplot(ax4, ncols=4, nrows=1, letter='E')
    plot_population(ax4, params, isometricangle=np.pi/24, rasterized=False)
    
    
    ############################################################################    
    # F part, CSD
    ############################################################################

    ax5 = fig.add_axes([lefts[1], bottom, axwidth, top-bottom])
    plt.locator_params(nbins=4)
    phlp.remove_axis_junk(ax5)
    if show_ax_labels:
        phlp.annotate_subplot(ax5, ncols=4, nrows=1, letter='F')
    plot_signal_sum(ax5, params, fname=os.path.join(params.savefolder, 'CSDsum.h5'),
                        unit='$\mu$A mm$^{-3}$',
                        T=T,
                        ylim=[ax4.axis()[2], ax4.axis()[3]],
                        rasterized=False)
    ax5.set_title('CSD', va='center')
    
    # Inset
    if show_insets:
        ax6 = fig.add_axes([lefts[1]+axwidth-insetwidth, top-insetheight, insetwidth, insetheight])
        plt.locator_params(nbins=4)
        phlp.remove_axis_junk(ax6)
        plot_signal_sum_colorplot(ax6, params, os.path.join(params.savefolder, 'CSDsum.h5'),
                                  unit=r'$\mu$Amm$^{-3}$', T=T_inset,
                                  ylim=[ax4.axis()[2], ax4.axis()[3]],
                                  fancy=False,colorbar=False,cmap='bwr_r')
        ax6.set_xticks(T_inset)
        ax6.set_yticklabels([])

    #show traces superimposed on color image
    if show_images:
        plot_signal_sum_colorplot(ax5, params, os.path.join(params.savefolder, 'CSDsum.h5'),
                                  unit=r'$\mu$Amm$^{-3}$', T=T,
                                  ylim=[ax4.axis()[2], ax4.axis()[3]],
                                  fancy=False,colorbar=False,cmap='jet_r')
        

    
    ############################################################################
    # G part, LFP 
    ############################################################################

    ax7 = fig.add_axes([lefts[2], bottom, axwidth, top-bottom])
    plt.locator_params(nbins=4)
    if show_ax_labels:
        phlp.annotate_subplot(ax7, ncols=4, nrows=1, letter='G')
    phlp.remove_axis_junk(ax7)
    plot_signal_sum(ax7, params, fname=os.path.join(params.savefolder, 'LFPsum.h5'),
                    unit='mV', T=T, ylim=[ax4.axis()[2], ax4.axis()[3]],
                    rasterized=False)
    ax7.set_title('LFP',va='center')
    
    # Inset
    if show_insets:
        ax8 = fig.add_axes([lefts[2]+axwidth-insetwidth, top-insetheight, insetwidth, insetheight])
        plt.locator_params(nbins=4)
        phlp.remove_axis_junk(ax8)
        plot_signal_sum_colorplot(ax8, params, os.path.join(params.savefolder, 'LFPsum.h5'),
                                  unit='mV', T=T_inset,
                                  ylim=[ax4.axis()[2], ax4.axis()[3]],
                                  fancy=False,colorbar=False,cmap='bwr_r')   
        ax8.set_xticks(T_inset)
        ax8.set_yticklabels([])

    #show traces superimposed on color image
    if show_images:
        plot_signal_sum_colorplot(ax7, params, os.path.join(params.savefolder, 'LFPsum.h5'),
                                  unit='mV', T=T,
                                  ylim=[ax4.axis()[2], ax4.axis()[3]],
                                  fancy=False,colorbar=False,cmap='bwr_r')
Example #3
0
def plot_multi_scale_output_b(fig, X='L5E'):
    '''docstring me'''

    show_ax_labels = True
    show_insets = False
    show_images = False

    T = [800, 1000]
    T_inset = [900, 920]

    left = 0.075
    bottom = 0.05
    top = 0.475
    right = 0.95
    axwidth = 0.16
    numcols = 4
    insetwidth = axwidth / 2
    insetheight = 0.5

    lefts = np.linspace(left, right - axwidth, numcols)
    lefts += axwidth / 2

    #lower row of panels
    #fig = plt.figure()
    #fig.subplots_adjust(left=0.12, right=0.9, bottom=0.36, top=0.9, wspace=0.2, hspace=0.3)

    ############################################################################
    # E part, soma locations
    ############################################################################

    ax4 = fig.add_axes([lefts[0], bottom, axwidth, top - bottom],
                       frameon=False)
    plt.locator_params(nbins=4)
    ax4.xaxis.set_ticks([])
    ax4.yaxis.set_ticks([])
    if show_ax_labels:
        phlp.annotate_subplot(ax4, ncols=4, nrows=1, letter='E')
    plot_population(ax4, params, isometricangle=np.pi / 24, rasterized=False)

    ############################################################################
    # F part, CSD
    ############################################################################

    ax5 = fig.add_axes([lefts[1], bottom, axwidth, top - bottom])
    plt.locator_params(nbins=4)
    phlp.remove_axis_junk(ax5)
    if show_ax_labels:
        phlp.annotate_subplot(ax5, ncols=4, nrows=1, letter='F')
    plot_signal_sum(ax5,
                    params,
                    fname=os.path.join(params.savefolder, 'CSDsum.h5'),
                    unit='$\mu$A mm$^{-3}$',
                    T=T,
                    ylim=[ax4.axis()[2], ax4.axis()[3]],
                    rasterized=False)
    ax5.set_title('CSD', va='center')

    # Inset
    if show_insets:
        ax6 = fig.add_axes([
            lefts[1] + axwidth - insetwidth, top - insetheight, insetwidth,
            insetheight
        ])
        plt.locator_params(nbins=4)
        phlp.remove_axis_junk(ax6)
        plot_signal_sum_colorplot(ax6,
                                  params,
                                  os.path.join(params.savefolder, 'CSDsum.h5'),
                                  unit=r'$\mu$Amm$^{-3}$',
                                  T=T_inset,
                                  ylim=[ax4.axis()[2],
                                        ax4.axis()[3]],
                                  fancy=False,
                                  colorbar=False,
                                  cmap='bwr_r')
        ax6.set_xticks(T_inset)
        ax6.set_yticklabels([])

    #show traces superimposed on color image
    if show_images:
        plot_signal_sum_colorplot(ax5,
                                  params,
                                  os.path.join(params.savefolder, 'CSDsum.h5'),
                                  unit=r'$\mu$Amm$^{-3}$',
                                  T=T,
                                  ylim=[ax4.axis()[2],
                                        ax4.axis()[3]],
                                  fancy=False,
                                  colorbar=False,
                                  cmap='jet_r')

    ############################################################################
    # G part, LFP
    ############################################################################

    ax7 = fig.add_axes([lefts[2], bottom, axwidth, top - bottom])
    plt.locator_params(nbins=4)
    if show_ax_labels:
        phlp.annotate_subplot(ax7, ncols=4, nrows=1, letter='G')
    phlp.remove_axis_junk(ax7)
    plot_signal_sum(ax7,
                    params,
                    fname=os.path.join(params.savefolder, 'LFPsum.h5'),
                    unit='mV',
                    T=T,
                    ylim=[ax4.axis()[2], ax4.axis()[3]],
                    rasterized=False)
    ax7.set_title('LFP', va='center')

    # Inset
    if show_insets:
        ax8 = fig.add_axes([
            lefts[2] + axwidth - insetwidth, top - insetheight, insetwidth,
            insetheight
        ])
        plt.locator_params(nbins=4)
        phlp.remove_axis_junk(ax8)
        plot_signal_sum_colorplot(ax8,
                                  params,
                                  os.path.join(params.savefolder, 'LFPsum.h5'),
                                  unit='mV',
                                  T=T_inset,
                                  ylim=[ax4.axis()[2],
                                        ax4.axis()[3]],
                                  fancy=False,
                                  colorbar=False,
                                  cmap='bwr_r')
        ax8.set_xticks(T_inset)
        ax8.set_yticklabels([])

    #show traces superimposed on color image
    if show_images:
        plot_signal_sum_colorplot(ax7,
                                  params,
                                  os.path.join(params.savefolder, 'LFPsum.h5'),
                                  unit='mV',
                                  T=T,
                                  ylim=[ax4.axis()[2],
                                        ax4.axis()[3]],
                                  fancy=False,
                                  colorbar=False,
                                  cmap='bwr_r')
Example #4
0
    ############################################################################
    # C part, CSD
    ############################################################################
    ax5 = fig.add_subplot(gs[:, 2])
    plt.locator_params(nbins=4)
    phlp.remove_axis_junk(ax5)
    if show_ax_labels:
        phlp.annotate_subplot(ax5,
                              ncols=1,
                              nrows=1,
                              letter='C',
                              linear_offset=0.065)
    plot_signal_sum(ax5,
                    params,
                    fname=os.path.join(params.savefolder, 'CSDsum.h5'),
                    unit='$\mu$A mm$^{-3}$',
                    T=T,
                    ylim=[-1550, 50],
                    rasterized=False)
    ax5.set_title('CSD')
    a = ax5.axis()
    ax5.vlines(x['TC'][0], a[2], a[3], 'k', lw=0.25)

    #show traces superimposed on color image
    if show_images:
        im = plot_signal_sum_colorplot(
            ax5,
            params,
            os.path.join(params.savefolder, 'CSDsum.h5'),
            unit=r'$\mu$Amm$^{-3}$',
            T=T,
Example #5
0
def fig_network_input_structure(fig, params, bottom=0.1, top=0.9, transient=200, T=[800, 1000], Df= 0., mlab= True, NFFT=256, srate=1000,
             window=plt.mlab.window_hanning, noverlap=256*3/4, letters='abcde', flim=(4, 400),
             show_titles=True, show_xlabels=True, show_CSD=False):
    '''
    This figure is the top part for plotting a comparison between the PD-model
    and the modified-PD model
    
    '''
    #load spike as database
    networkSim = CachedNetwork(**params.networkSimParams)
    if analysis_params.bw:
        networkSim.colors = phlp.get_colors(len(networkSim.X))


    # ana_params.set_PLOS_2column_fig_style(ratio=ratio)
    # fig = plt.figure()
    # fig.subplots_adjust(left=0.06, right=0.94, bottom=0.09, top=0.92, wspace=0.5, hspace=0.2)
    
    #use gridspec to get nicely aligned subplots througout panel
    gs1 = gridspec.GridSpec(5, 5, bottom=bottom, top=top)
    
    
    ############################################################################ 
    # A part, full dot display
    ############################################################################
    
    ax0 = fig.add_subplot(gs1[:, 0])
    phlp.remove_axis_junk(ax0)
    phlp.annotate_subplot(ax0, ncols=5, nrows=1, letter=letters[0],
                     linear_offset=0.065)
   
    x, y = networkSim.get_xy(T, fraction=1)
    networkSim.plot_raster(ax0, T, x, y,
                           markersize=0.2, marker='_',
                           alpha=1.,
                           legend=False, pop_names=True,
                           rasterized=False)
    ax0.set_ylabel('population', labelpad=0.)
    ax0.set_xticks([800,900,1000])
   
    if show_titles:
        ax0.set_title('spiking activity',va='center')
    if show_xlabels:
        ax0.set_xlabel(r'$t$ (ms)', labelpad=0.)
    else:
        ax0.set_xlabel('')
      
    ############################################################################
    # B part, firing rate spectra
    ############################################################################

  
    # Get the firing rate from Potjan Diesmann et al network activity
    #collect the spikes x is the times, y is the id of the cell.
    T_all=[transient, networkSim.simtime]
    bins = np.arange(transient, networkSim.simtime+1)
        
    x, y = networkSim.get_xy(T_all, fraction=1)

    # create invisible axes to position labels correctly
    ax_ = fig.add_subplot(gs1[:, 1])
    phlp.annotate_subplot(ax_, ncols=5, nrows=1, letter=letters[1],
                                 linear_offset=0.065)
    if show_titles:
        ax_.set_title('firing rate PSD', va='center')
    
    ax_.axis('off')

    colors = phlp.get_colors(len(params.Y))+['k']
    
    COUNTER = 0
    label_set = False
    
    t**s = ['L23E/I', 'L4E/I', 'L5E/I', 'L6E/I', 'TC']

    if x['TC'].size > 0:
        TC = True
    else:
        TC = False

    BAxes = []
    for i, X in enumerate(networkSim.X):

        if i % 2 == 0:
            ax1 = fig.add_subplot(gs1[COUNTER, 1])
            phlp.remove_axis_junk(ax1)

            if x[X].size > 0:
                ax1.text(0.05, 0.85, t**s[COUNTER],
                    horizontalalignment='left',
                    verticalalignment='bottom',
                    transform=ax1.transAxes)
            BAxes.append(ax1)


        #firing rate histogram
        hist = np.histogram(x[X], bins=bins)[0].astype(float)
        hist -= hist.mean()
        
        if mlab:
            Pxx, freqs=plt.mlab.psd(hist, NFFT=NFFT,
                                    Fs=srate, noverlap=noverlap, window=window)
        else:
            [freqs, Pxx] = hlp.powerspec([hist], tbin= 1.,
                                        Df=Df, pointProcess=False)
            mask = np.where(freqs >= 0.)
            freqs = freqs[mask]
            Pxx = Pxx.flatten()
            Pxx = Pxx[mask]
            Pxx = Pxx/(T_all[1]-T_all[0])**2
        
        if x[X].size > 0:
            ax1.loglog(freqs[1:], Pxx[1:],
                       label=X, color=colors[i],
                       clip_on=True)
            ax1.axis(ax1.axis('tight'))
            ax1.set_ylim([5E-4,5E2])
            ax1.set_yticks([1E-3,1E-1,1E1])
            if label_set == False:
                ax1.set_ylabel(r'(s$^{-2}$/Hz)', labelpad=0.)
                label_set = True
            if i > 1:
                ax1.set_yticklabels([])
            if i >= 6 and not TC and show_xlabels or X == 'TC' and TC and show_xlabels:
                ax1.set_xlabel('$f$ (Hz)', labelpad=0.)
            if TC and i < 8 or not TC and i < 6:
                ax1.set_xticklabels([])    

        else:
            ax1.axis('off')
                       
        ax1.set_xlim(flim)
           
        
        if i % 2 == 0:
            COUNTER += 1
        
        ax1.yaxis.set_minor_locator(plt.NullLocator())
        



    ############################################################################
    # c part, LFP traces and CSD color plots
    ############################################################################
   
    ax2 = fig.add_subplot(gs1[:, 2])
    
    phlp.annotate_subplot(ax2, ncols=5, nrows=1, letter=letters[2],
                     linear_offset=0.065)


    phlp.remove_axis_junk(ax2)
    plot_signal_sum(ax2, params,
                    fname=os.path.join(params.savefolder, 'LFPsum.h5'),
                    unit='mV', T=T, ylim=[-1600, 40],
                    rasterized=False)
    
    # CSD background colorplot
    if show_CSD:
        im = plot_signal_sum_colorplot(ax2, params, os.path.join(params.savefolder, 'CSDsum.h5'),
                                  unit=r'($\mu$Amm$^{-3}$)', T=[800, 1000],
                                  colorbar=False,
                                  ylim=[-1600, 40], fancy=False, cmap=plt.cm.get_cmap('bwr_r', 21),
                                  rasterized=False)
        cb = phlp.colorbar(fig, ax2, im,
                           width=0.05, height=0.4,
                           hoffset=-0.05, voffset=0.3)
        cb.set_label('($\mu$Amm$^{-3}$)', labelpad=0.1)

    ax2.set_xticks([800,900,1000])
    ax2.axis(ax2.axis('tight'))
     
    if show_titles:
        if show_CSD:
            ax2.set_title('LFP & CSD', va='center')
        else:
            ax2.set_title('LFP', va='center')
    if show_xlabels:
        ax2.set_xlabel(r'$t$ (ms)', labelpad=0.)
    else:
        ax2.set_xlabel('')
  
 
    ############################################################################
    # d part, LFP power trace for each layer
    ############################################################################

    freqs, PSD = calc_signal_power(params, fname=os.path.join(params.savefolder,
                                                           'LFPsum.h5'),
                                        transient=transient, Df=Df, mlab=mlab,
                                        NFFT=NFFT, noverlap=noverlap,
                                        window=window)

    channels = [0, 3, 7, 11, 13]
  
    # create invisible axes to position labels correctly
    ax_ = fig.add_subplot(gs1[:, 3])
    phlp.annotate_subplot(ax_, ncols=5, nrows=1, letter=letters[3],
                                 linear_offset=0.065)

    if show_titles:
        ax_.set_title('LFP PSD',va='center')
    
    ax_.axis('off')

    for i, ch in enumerate(channels):

        ax = fig.add_subplot(gs1[i, 3])
        phlp.remove_axis_junk(ax)

        if i == 0:
            ax.set_ylabel('(mV$^2$/Hz)', labelpad=0)

        ax.loglog(freqs[1:],PSD[ch][1:], color='k')
        ax.xaxis.set_ticks_position('bottom')
        ax.yaxis.set_ticks_position('left')
        if i < 4:
            ax.set_xticklabels([])
        ax.text(0.75, 0.85,'ch. %i' %(channels[i]+1),
                horizontalalignment='left',
                verticalalignment='bottom',
                fontsize=6,
                transform=ax.transAxes)
        ax.tick_params(axis='y', which='minor', bottom='off')
        ax.axis(ax.axis('tight'))
        ax.yaxis.set_minor_locator(plt.NullLocator())

        ax.set_xlim(flim)
        ax.set_ylim(1E-7,2E-4)
        if i != 0 :
            ax.set_yticklabels([])


    if show_xlabels:
        ax.set_xlabel('$f$ (Hz)', labelpad=0.)
    
    ############################################################################
    # e part signal power
    ############################################################################
    
    ax4 = fig.add_subplot(gs1[:, 4])

    phlp.annotate_subplot(ax4, ncols=5, nrows=1, letter=letters[4],
                     linear_offset=0.065)
  
    fname=os.path.join(params.savefolder, 'LFPsum.h5')
    im = plot_signal_power_colorplot(ax4, params, fname=fname, transient=transient, Df=Df,
                                mlab=mlab, NFFT=NFFT, window=window,
                                cmap=plt.cm.get_cmap('gray_r', 12),
                                vmin=1E-7, vmax=1E-4)
    phlp.remove_axis_junk(ax4)

    ax4.set_xlim(flim)

    cb = phlp.colorbar(fig, ax4, im,
                       width=0.05, height=0.5,
                       hoffset=-0.05, voffset=0.5)
    cb.set_label('(mV$^2$/Hz)', labelpad=0.1)


    if show_titles:
        ax4.set_title('LFP PSD', va='center')
    if show_xlabels:
        ax4.set_xlabel(r'$f$ (Hz)', labelpad=0.)
    else:
        ax4.set_xlabel('')
       
    return fig 
Example #6
0
def fig_network_input_structure(fig,
                                params,
                                bottom=0.1,
                                top=0.9,
                                transient=200,
                                T=[800, 1000],
                                Df=0.,
                                mlab=True,
                                NFFT=256,
                                srate=1000,
                                window=plt.mlab.window_hanning,
                                noverlap=256 * 3 / 4,
                                letters='abcde',
                                flim=(4, 400),
                                show_titles=True,
                                show_xlabels=True,
                                show_CSD=False):
    '''
    This figure is the top part for plotting a comparison between the PD-model
    and the modified-PD model
    
    '''
    #load spike as database
    networkSim = CachedNetwork(**params.networkSimParams)
    if analysis_params.bw:
        networkSim.colors = phlp.get_colors(len(networkSim.X))

    # ana_params.set_PLOS_2column_fig_style(ratio=ratio)
    # fig = plt.figure()
    # fig.subplots_adjust(left=0.06, right=0.94, bottom=0.09, top=0.92, wspace=0.5, hspace=0.2)

    #use gridspec to get nicely aligned subplots througout panel
    gs1 = gridspec.GridSpec(5, 5, bottom=bottom, top=top)

    ############################################################################
    # A part, full dot display
    ############################################################################

    ax0 = fig.add_subplot(gs1[:, 0])
    phlp.remove_axis_junk(ax0)
    phlp.annotate_subplot(ax0,
                          ncols=5,
                          nrows=1,
                          letter=letters[0],
                          linear_offset=0.065)

    x, y = networkSim.get_xy(T, fraction=1)
    networkSim.plot_raster(ax0,
                           T,
                           x,
                           y,
                           markersize=0.2,
                           marker='_',
                           alpha=1.,
                           legend=False,
                           pop_names=True,
                           rasterized=False)
    ax0.set_ylabel('population', labelpad=0.)
    ax0.set_xticks([800, 900, 1000])

    if show_titles:
        ax0.set_title('spiking activity', va='center')
    if show_xlabels:
        ax0.set_xlabel(r'$t$ (ms)', labelpad=0.)
    else:
        ax0.set_xlabel('')

    ############################################################################
    # B part, firing rate spectra
    ############################################################################

    # Get the firing rate from Potjan Diesmann et al network activity
    #collect the spikes x is the times, y is the id of the cell.
    T_all = [transient, networkSim.simtime]
    bins = np.arange(transient, networkSim.simtime + 1)

    x, y = networkSim.get_xy(T_all, fraction=1)

    # create invisible axes to position labels correctly
    ax_ = fig.add_subplot(gs1[:, 1])
    phlp.annotate_subplot(ax_,
                          ncols=5,
                          nrows=1,
                          letter=letters[1],
                          linear_offset=0.065)
    if show_titles:
        ax_.set_title('firing rate PSD', va='center')

    ax_.axis('off')

    colors = phlp.get_colors(len(params.Y)) + ['k']

    COUNTER = 0
    label_set = False

    t**s = ['L23E/I', 'L4E/I', 'L5E/I', 'L6E/I', 'TC']

    if x['TC'].size > 0:
        TC = True
    else:
        TC = False

    BAxes = []
    for i, X in enumerate(networkSim.X):

        if i % 2 == 0:
            ax1 = fig.add_subplot(gs1[COUNTER, 1])
            phlp.remove_axis_junk(ax1)

            if x[X].size > 0:
                ax1.text(0.05,
                         0.85,
                         t**s[COUNTER],
                         horizontalalignment='left',
                         verticalalignment='bottom',
                         transform=ax1.transAxes)
            BAxes.append(ax1)

        #firing rate histogram
        hist = np.histogram(x[X], bins=bins)[0].astype(float)
        hist -= hist.mean()

        if mlab:
            Pxx, freqs = plt.mlab.psd(hist,
                                      NFFT=NFFT,
                                      Fs=srate,
                                      noverlap=noverlap,
                                      window=window)
        else:
            [freqs, Pxx] = hlp.powerspec([hist],
                                         tbin=1.,
                                         Df=Df,
                                         pointProcess=False)
            mask = np.where(freqs >= 0.)
            freqs = freqs[mask]
            Pxx = Pxx.flatten()
            Pxx = Pxx[mask]
            Pxx = Pxx / (T_all[1] - T_all[0])**2

        if x[X].size > 0:
            ax1.loglog(freqs[1:],
                       Pxx[1:],
                       label=X,
                       color=colors[i],
                       clip_on=True)
            ax1.axis(ax1.axis('tight'))
            ax1.set_ylim([5E-4, 5E2])
            ax1.set_yticks([1E-3, 1E-1, 1E1])
            if label_set == False:
                ax1.set_ylabel(r'(s$^{-2}$/Hz)', labelpad=0.)
                label_set = True
            if i > 1:
                ax1.set_yticklabels([])
            if i >= 6 and not TC and show_xlabels or X == 'TC' and TC and show_xlabels:
                ax1.set_xlabel('$f$ (Hz)', labelpad=0.)
            if TC and i < 8 or not TC and i < 6:
                ax1.set_xticklabels([])

        else:
            ax1.axis('off')

        ax1.set_xlim(flim)

        if i % 2 == 0:
            COUNTER += 1

        ax1.yaxis.set_minor_locator(plt.NullLocator())

    ############################################################################
    # c part, LFP traces and CSD color plots
    ############################################################################

    ax2 = fig.add_subplot(gs1[:, 2])

    phlp.annotate_subplot(ax2,
                          ncols=5,
                          nrows=1,
                          letter=letters[2],
                          linear_offset=0.065)

    phlp.remove_axis_junk(ax2)
    plot_signal_sum(ax2,
                    params,
                    fname=os.path.join(params.savefolder, 'LFPsum.h5'),
                    unit='mV',
                    T=T,
                    ylim=[-1600, 40],
                    rasterized=False)

    # CSD background colorplot
    if show_CSD:
        im = plot_signal_sum_colorplot(ax2,
                                       params,
                                       os.path.join(params.savefolder,
                                                    'CSDsum.h5'),
                                       unit=r'($\mu$Amm$^{-3}$)',
                                       T=[800, 1000],
                                       colorbar=False,
                                       ylim=[-1600, 40],
                                       fancy=False,
                                       cmap=plt.cm.get_cmap('bwr_r', 21),
                                       rasterized=False)
        cb = phlp.colorbar(fig,
                           ax2,
                           im,
                           width=0.05,
                           height=0.4,
                           hoffset=-0.05,
                           voffset=0.3)
        cb.set_label('($\mu$Amm$^{-3}$)', labelpad=0.1)

    ax2.set_xticks([800, 900, 1000])
    ax2.axis(ax2.axis('tight'))

    if show_titles:
        if show_CSD:
            ax2.set_title('LFP & CSD', va='center')
        else:
            ax2.set_title('LFP', va='center')
    if show_xlabels:
        ax2.set_xlabel(r'$t$ (ms)', labelpad=0.)
    else:
        ax2.set_xlabel('')

    ############################################################################
    # d part, LFP power trace for each layer
    ############################################################################

    freqs, PSD = calc_signal_power(params,
                                   fname=os.path.join(params.savefolder,
                                                      'LFPsum.h5'),
                                   transient=transient,
                                   Df=Df,
                                   mlab=mlab,
                                   NFFT=NFFT,
                                   noverlap=noverlap,
                                   window=window)

    channels = [0, 3, 7, 11, 13]

    # create invisible axes to position labels correctly
    ax_ = fig.add_subplot(gs1[:, 3])
    phlp.annotate_subplot(ax_,
                          ncols=5,
                          nrows=1,
                          letter=letters[3],
                          linear_offset=0.065)

    if show_titles:
        ax_.set_title('LFP PSD', va='center')

    ax_.axis('off')

    for i, ch in enumerate(channels):

        ax = fig.add_subplot(gs1[i, 3])
        phlp.remove_axis_junk(ax)

        if i == 0:
            ax.set_ylabel('(mV$^2$/Hz)', labelpad=0)

        ax.loglog(freqs[1:], PSD[ch][1:], color='k')
        ax.xaxis.set_ticks_position('bottom')
        ax.yaxis.set_ticks_position('left')
        if i < 4:
            ax.set_xticklabels([])
        ax.text(0.75,
                0.85,
                'ch. %i' % (channels[i] + 1),
                horizontalalignment='left',
                verticalalignment='bottom',
                fontsize=6,
                transform=ax.transAxes)
        ax.tick_params(axis='y', which='minor', bottom='off')
        ax.axis(ax.axis('tight'))
        ax.yaxis.set_minor_locator(plt.NullLocator())

        ax.set_xlim(flim)
        ax.set_ylim(1E-7, 2E-4)
        if i != 0:
            ax.set_yticklabels([])

    if show_xlabels:
        ax.set_xlabel('$f$ (Hz)', labelpad=0.)

    ############################################################################
    # e part signal power
    ############################################################################

    ax4 = fig.add_subplot(gs1[:, 4])

    phlp.annotate_subplot(ax4,
                          ncols=5,
                          nrows=1,
                          letter=letters[4],
                          linear_offset=0.065)

    fname = os.path.join(params.savefolder, 'LFPsum.h5')
    im = plot_signal_power_colorplot(ax4,
                                     params,
                                     fname=fname,
                                     transient=transient,
                                     Df=Df,
                                     mlab=mlab,
                                     NFFT=NFFT,
                                     window=window,
                                     cmap=plt.cm.get_cmap('gray_r', 12),
                                     vmin=1E-7,
                                     vmax=1E-4)
    phlp.remove_axis_junk(ax4)

    ax4.set_xlim(flim)

    cb = phlp.colorbar(fig,
                       ax4,
                       im,
                       width=0.05,
                       height=0.5,
                       hoffset=-0.05,
                       voffset=0.5)
    cb.set_label('(mV$^2$/Hz)', labelpad=0.1)

    if show_titles:
        ax4.set_title('LFP PSD', va='center')
    if show_xlabels:
        ax4.set_xlabel(r'$f$ (Hz)', labelpad=0.)
    else:
        ax4.set_xlabel('')

    return fig
Example #7
0
def fig_kernel_lfp(savefolders, params, transient=200, T=[800., 1000.], X='L5E',
                   lags=[20, 20], channels=[0,3,7,11,13]):

    '''
    This function calculates the  STA of LFP, extracts kernels and recontructs the LFP from kernels.
    
    Arguments
    ::
      transient : the time in milliseconds, after which the analysis should begin
                so as to avoid any starting transients
      X : id of presynaptic trigger population
       
    '''

    # Electrode geometry
    zvec = np.r_[params.electrodeParams['z']]

    alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'



    ana_params.set_PLOS_2column_fig_style(ratio=1)
    # Start the figure
    fig = plt.figure()
    fig.subplots_adjust(left=0.06, right=0.95, bottom=0.05, top=0.95, hspace=0.23, wspace=0.55) 

    # create grid_spec
    gs = gridspec.GridSpec(2*len(channels)+1, 7)


    ###########################################################################
    # spikegen "network" activity
    ############################################################################
    
    
    # path to simulation files
    params.savefolder = os.path.join(os.path.split(params.savefolder)[0],
                                     'simulation_output_spikegen')
    params.figures_path = os.path.join(params.savefolder, 'figures')
    params.spike_output_path = os.path.join(params.savefolder,
                                                       'processed_nest_output')
    params.networkSimParams['spike_output_path'] = params.spike_output_path
    
    
    # Get the spikegen LFP:
    f = h5py.File(os.path.join(params.savefolder, 'LFPsum.h5'))
    srate = f['srate'].value
    tvec = np.arange(f['data'].shape[1]) * 1000. / srate
    
    # slice
    inds = (tvec < params.tstop) & (tvec >= transient)
    
    data_sg_raw = f['data'].value.astype(float)
    data_sg = data_sg_raw[:, inds]
    f.close()
    
    # kernel width
    kwidth = 20
    
    # create some dummy spike times
    activationtimes = np.array([x*100 for x in range(3,11)] + [200])
    networkSimSpikegen = CachedNetwork(**params.networkSimParams)

    x, y = networkSimSpikegen.get_xy([transient, params.tstop])

    
    ###########################################################################
    # Part A: spatiotemporal kernels, all presynaptic populations
    ############################################################################
    
    titles = ['TC',
              'L23E/I',
              'LFP kernels \n L4E/I',
              'L5E/I',
              'L6E/I',
              ]
    
    COUNTER = 0 
    for i, X__ in enumerate(([['TC']]) + zip(params.X[1::2], params.X[2::2])):        
        ax = fig.add_subplot(gs[:len(channels), i])
        if i == 0:
            phlp.annotate_subplot(ax, ncols=7, nrows=4, letter=alphabet[0], linear_offset=0.02)
    
        for j, X_ in enumerate(X__):
            # create spikegen histogram for population Y
            cinds = np.arange(activationtimes[np.arange(-1, 8)][COUNTER]-kwidth,
                              activationtimes[np.arange(-1, 8)][COUNTER]+kwidth+2)
            x0_sg = np.histogram(x[X_], bins=cinds)[0].astype(float)
            
            if X_ == ('TC'):
                color='k' if analysis_params.bw else analysis_params.colorE
                # lw = plt.rcParams['lines.linewidth']
                # zorder=1
            else:
                color=('k' if analysis_params.bw else analysis_params.colorE,
                       'gray' if analysis_params.bw else analysis_params.colorI)[j]
            lw = 0.75 if color in ['gray', 'r', 'b'] else plt.rcParams['lines.linewidth']
            zorder = 0 if 'I' in X_ else 1
            
            
            # plot kernel as correlation of spikegen LFP signal with delta spike train
            xcorr, vlimround = plotting_correlation(params,
                                                    x0_sg/x0_sg.sum()**2, 
                                                    data_sg_raw[:, cinds[:-1]]*1E3,
                                                    ax, normalize=False,
                                                    lag=kwidth,
                                                    color=color,
                                                    scalebar=False,
                                                    lw=lw, zorder=zorder)
            if i > 0:
                ax.set_yticklabels([])
            
            ## Create scale bar
            ax.plot([kwidth, kwidth],
                [-1500 + j*3*100, -1400 + j*3*100], lw=2, color=color,
                clip_on=False)
            ax.text(kwidth*1.08, -1450 + j*3*100, '%.1f $\mu$V' % vlimround,
                        rotation='vertical', va='center')
    
            ax.set_xlim((-5, kwidth))
            ax.set_xticks([-20, 0, 20])
            ax.set_xticklabels([-20, 0, 20])
            
            COUNTER += 1
            
        ax.set_title(titles[i])
    

    ################################################
    # Iterate over savefolders
    ################################################

    for i, (savefolder, lag) in enumerate(zip(savefolders, lags)):
        
        # path to simulation files
        params.savefolder = os.path.join(os.path.split(params.savefolder)[0],
                                         savefolder)
        params.figures_path = os.path.join(params.savefolder, 'figures')
        params.spike_output_path = os.path.join(params.savefolder,
                                                'processed_nest_output')
        params.networkSimParams['spike_output_path'] = params.spike_output_path

        #load spike as database inside function to avoid buggy behaviour
        networkSim = CachedNetwork(**params.networkSimParams)

    
    
        # Get the Compound LFP: LFPsum : data[nchannels, timepoints ]
        f = h5py.File(os.path.join(params.savefolder, 'LFPsum.h5'))
        data_raw = f['data'].value
        srate = f['srate'].value
        tvec = np.arange(data_raw.shape[1]) * 1000. / srate
        # slice
        inds = (tvec < params.tstop) & (tvec >= transient)
        data = data_raw[:, inds]
        # subtract mean
        dataT = data.T - data.mean(axis=1)
        data = dataT.T
        f.close()
    
        # Get the spikegen LFP:
        f = h5py.File(os.path.join(os.path.split(params.savefolder)[0], 'simulation_output_spikegen', 'LFPsum.h5'))
        data_sg_raw = f['data'].value
        
        f.close()
    
    
    
    
        ########################################################################
        # Part B: STA LFP
        ########################################################################
        
        titles = ['stLFP(%s)\n(spont.)' % X, 'stLFP(%s)\n(AC. mod.)' % X]
        ax = fig.add_subplot(gs[:len(channels), 5 + i])
        if i == 0:
            phlp.annotate_subplot(ax, ncols=15, nrows=4, letter=alphabet[i+1],
                                  linear_offset=0.02)
          
        #collect the spikes x is the times, y is the id of the cell.
        x, y = networkSim.get_xy([0,params.tstop])
        
        # Get the spikes for the population of interest given as 'Y'
        bins = np.arange(0, params.tstop+2) + 0.5
        x0_raw = np.histogram(x[X], bins=bins)[0]
        x0 = x0_raw[inds].astype(float)
    
        # correlation between firing rate and LFP deviation
        # from mean normalized by the number of spikes  
        xcorr, vlimround = plotting_correlation(params,
                                                x0/x0.sum(), 
                                                data*1E3,
                                                ax, normalize=False, 
                                                #unit='%.3f mV',
                                                lag=lag,
                                                scalebar=False,
                                                color='k',
                                                title=titles[i],
                                                )

        # Create scale bar
        ax.plot([lag, lag],
            [-1500, -1400], lw=2, color='k',
            clip_on=False)
        ax.text(lag*1.08, -1450, '%.1f $\mu$V' % vlimround,
                    rotation='vertical', va='center')


        [Xind] = np.where(np.array(networkSim.X) == X)[0]        
                
        # create spikegen histogram for population Y
        x0_sg = np.zeros(x0.shape, dtype=float)
        x0_sg[activationtimes[Xind]] += params.N_X[Xind]
        

        ax.set_yticklabels([])
        ax.set_xticks([-lag, 0, lag])
        ax.set_xticklabels([-lag, 0, lag])

        
        ###########################################################################
        # Part C, F: LFP and reconstructed LFP
        ############################################################################

        # create grid_spec
        gsb = gridspec.GridSpec(2*len(channels)+1, 8)

      
        ax = fig.add_subplot(gsb[1+len(channels):, (i*4):(i*4+2)])
        phlp.annotate_subplot(ax, ncols=8/2., nrows=4, letter=alphabet[i*3+2],
                              linear_offset=0.02)
          
        # extract kernels, force negative lags to be zero
        kernels = np.zeros((len(params.N_X), 16, kwidth*2))
        for j in range(len(params.X)):
            kernels[j, :, kwidth:] = data_sg_raw[:, (j+2)*100:kwidth+(j+2)*100]/params.N_X[j]
    
        LFP_reconst_raw = np.zeros(data_raw.shape)
    
        for j, pop in enumerate(params.X):
            x0_raw = np.histogram(x[pop], bins=bins)[0].astype(float)
            for ch in range(kernels.shape[1]):
                LFP_reconst_raw[ch] += np.convolve(x0_raw, kernels[j, ch],
                                                   'same')
        
        # slice
        LFP_reconst = LFP_reconst_raw[:, inds]
        # subtract mean
        LFP_reconstT = LFP_reconst.T - LFP_reconst.mean(axis=1)
        LFP_reconst = LFP_reconstT.T
        vlimround = plot_signal_sum(ax, params,
                                    fname=os.path.join(params.savefolder,
                                                           'LFPsum.h5'),
                                    unit='mV', scalebar=True,
                                    T=T, ylim=[-1550, 50],
                                    color='k', label='$real$',
                                    rasterized=False,
                                    zorder=1)
    
        plot_signal_sum(ax, params, fname=LFP_reconst_raw,
                        unit='mV', scaling_factor= 1., scalebar=False,
                        vlimround=vlimround,
                        T=T, ylim=[-1550, 50],
                        color='gray' if analysis_params.bw else analysis_params.colorP,
                        label='$reconstr$',
                        rasterized=False,
                        lw=1, zorder=0)
        ax.set_title('LFP & population \n rate predictor')
        if i > 0:
            ax.set_yticklabels([])


        
        ###########################################################################
        # Part D,G: Correlation coefficient
        ############################################################################
        
        ax = fig.add_subplot(gsb[1+len(channels):, i*4+2:i*4+3])
        phlp.remove_axis_junk(ax)
        phlp.annotate_subplot(ax, ncols=8./1, nrows=4, letter=alphabet[i*3+3],
                              linear_offset=0.02)
            
        cc = np.zeros(len(zvec))
        for ch in np.arange(len(zvec)):
            cc[ch] = np.corrcoef(data[ch], LFP_reconst[ch])[1, 0]
        
        ax.barh(zvec, cc, height=80, align='center', color='0.5', linewidth=0.5)

        # superimpose the chance level, obtained by mixing one input vector n times
        # while keeping the other fixed. We show boxes drawn left to right where
        # these denote mean +/- two standard deviations.
        N = 1000
        method = 'randphase' #or 'permute'
        chance = np.zeros((cc.size, N))
        for ch in np.arange(len(zvec)):
            x1 = LFP_reconst[ch]
            x1 -= x1.mean()
            if method == 'randphase':
                x0 = data[ch]
                x0 -= x0.mean()
                X00 = np.fft.fft(x0)
            for n in range(N):
                if method == 'permute':
                    x0 = np.random.permutation(datas[ch])
                elif method == 'randphase':
                    X0 = np.copy(X00)
                    #random phase information such that spectra is preserved
                    theta = np.random.uniform(0, 2*np.pi, size=X0.size // 2-1)
                    #half-sided real and imaginary component 
                    real = abs(X0[1:X0.size // 2])*np.cos(theta)
                    imag = abs(X0[1:X0.size // 2])*np.sin(theta)
                    
                    #account for the antisymmetric phase values
                    X0.imag[1:imag.size+1] = imag
                    X0.imag[imag.size+2:] = -imag[::-1]
                    X0.real[1:real.size+1] = real
                    X0.real[real.size+2:] = real[::-1]
                    x0 = np.fft.ifft(X0).real

                chance[ch, n] = np.corrcoef(x0, x1)[1, 0]

        # p-values, compute the fraction of chance correlations > cc at each channel
        p = []
        for h, x in enumerate(cc):
            p += [(chance[h, ] >= x).sum() / float(N)]
        
        print('p-values:', p)


        #compute the 99% percentile of the chance data
        right = np.percentile(chance, 99, axis=-1)

        ax.plot(right, zvec, ':', color='k', lw=1.)    
        ax.set_ylim([-1550, 50])
        ax.set_yticklabels([])
        ax.set_yticks(zvec)
        ax.set_xlim([0, 1.])
        ax.set_xticks([0.0, 0.5, 1])
        ax.yaxis.tick_left()
        ax.set_xlabel('$cc$ (-)', labelpad=0.1)
        ax.set_title('corr. \n coef.')
    
        print 'correlation coefficients:'
        print cc


        ###########################################################################
        # Part E,H: Power spectra
        ############################################################################
        

        #compute PSDs ratio between ground truth and estimate
        freqs, PSD_data = calc_signal_power(params, fname=data,
                                            transient=transient, Df=None,
                                            mlab=True,
                                            NFFT=256, noverlap=128,
                                            window=plt.mlab.window_hanning)
        freqs, PSD_LFP_reconst = calc_signal_power(params, fname=LFP_reconst,
                                            transient=transient, Df=None,
                                            mlab=True,
                                            NFFT=256, noverlap=128,
                                            window=plt.mlab.window_hanning)

        zv = np.r_[params.electrodeParams['z']]
        zv = np.r_[zv, zv[-1] + np.diff(zv)[-1]]
        inds = freqs >= 1  # frequencies greater than 1 Hz  

        for j, ch in enumerate(channels):
        
            ax = fig.add_subplot(gsb[1+len(channels)+j, (i*4+3):(i*4+4)])
            if j == 0:
                phlp.annotate_subplot(ax, ncols=8./1, nrows=4.5*len(channels),
                                      letter=alphabet[i*3+4], linear_offset=0.02)
                ax.set_title('PSD')
                

            phlp.remove_axis_junk(ax)
            ax.loglog(freqs[inds], PSD_data[ch, inds], 'k', label='LFP',
                      clip_on=True, zorder=1)
            ax.loglog(freqs[inds], PSD_LFP_reconst[ch, inds],
                      'gray' if analysis_params.bw else analysis_params.colorP,
                      label='predictor', clip_on=True, lw=1, zorder=0)
            ax.set_xlim([4E0,4E2])
            ax.set_ylim([1E-8, 1E-4])
            ax.tick_params(axis='y', which='major', pad=0)
            ax.set_yticks([1E-8,1E-6,1E-4])
            ax.yaxis.set_minor_locator(plt.NullLocator())
            ax.text(0.8, 0.9, 'ch. %i' % (ch+1),
                    horizontalalignment='left',
                    verticalalignment='center',
                    fontsize=6, 
                    transform=ax.transAxes)
            
            if j == 0:
                ax.set_ylabel('(mV$^2$/Hz)', labelpad=0.)
            if j > 0:
                ax.set_yticklabels([])
            if j == len(channels)-1:
                ax.set_xlabel(r'$f$ (Hz)', labelpad=0.)
            else:
                ax.set_xticklabels([])



    return fig, PSD_LFP_reconst, PSD_data
Example #8
0
def fig_lfp_decomposition(fig, axes, params, transient=200, X=['L23E', 'L6E'], show_xlabels=True):
    # ana_params.set_PLOS_2column_fig_style(ratio=0.5)
    # fig, axes = plt.subplots(1,5)
    # fig.subplots_adjust(left=0.06, right=0.96, wspace=0.4, hspace=0.2)
    
    if analysis_params.bw:
        # linestyles = ['-', '-', '--', '--', '-.', '-.', ':', ':']
        linestyles = ['-', '-', '-', '-', '-', '-', '-', '-']
        markerstyles = ['s', 's', 'v', 'v', 'o', 'o', '^', '^']
    else:
        if plt.matplotlib.__version__ == '1.5.x':
            linestyles = ['-', ':']*(len(params.Y) / 2)
            print('CSD variance semi log plots may fail with matplotlib.__version__ {}'.format(plt.matplotlib.__version__))
        else:
            linestyles = ['-', (0, (1,1))]*(len(params.Y) / 2) #cercor version
        # markerstyles = ['s', 's', 'v', 'v', 'o', 'o', '^', '^']
        markerstyles = [None]*len(params.Y)
        linewidths = [1.25 for i in range(len(linestyles))]
    
    plt.delaxes(axes[0])
    
    #population plot
    axes[0] = fig.add_subplot(261)
    axes[0].xaxis.set_ticks([])
    axes[0].yaxis.set_ticks([])
    axes[0].set_frame_on(False)
    plot_population(axes[0], params, aspect='tight', isometricangle=np.pi/32,
                           plot_somas = False, plot_morphos = True,
                           num_unitsE = 1, num_unitsI=1,
                           clip_dendrites=False, main_pops=True,
                           rasterized=False)
    phlp.annotate_subplot(axes[0], ncols=5, nrows=1, letter='A')
    axes[0].set_aspect('auto')
    axes[0].set_ylim(-1550, 50)
    axis = axes[0].axis()
    
    
    
    phlp.remove_axis_junk(axes[1])
    plot_signal_sum(axes[1], params,
                    fname=os.path.join(params.populations_path, X[0] + '_population_LFP.h5'),
                    unit='mV', T=[800,1000], ylim=[axis[2], axis[3]],
                    rasterized=False)
    
    # CSD background colorplot
    im = plot_signal_sum_colorplot(axes[1], params, os.path.join(params.populations_path,  X[0] + '_population_CSD.h5'),
                              unit=r'$\mu$Amm$^{-3}$', T=[800,1000],
                              colorbar=False,
                              ylim=[axis[2], axis[3]], fancy=False,
                              cmap=plt.get_cmap('gray', 21) if analysis_params.bw else plt.get_cmap('bwr_r', 21),
                              rasterized=False)

    cb = phlp.colorbar(fig, axes[1], im,
                       width=0.05, height=0.5,
                       hoffset=-0.05, voffset=0.5)
    cb.set_label('($\mu$Amm$^{-3}$)', labelpad=0.)

    axes[1].set_ylim(-1550, 50)
    axes[1].set_title('LFP and CSD ({})'.format(X[0]), va='baseline')
    phlp.annotate_subplot(axes[1], ncols=3, nrows=1, letter='B')
     
    #quickfix on first axes
    axes[0].set_ylim(-1550, 50)
    if show_xlabels:
        axes[1].set_xlabel(r'$t$ (ms)',labelpad=0.)
    else:
        axes[1].set_xlabel('')
    


    phlp.remove_axis_junk(axes[2])
    plot_signal_sum(axes[2], params,
                    fname=os.path.join(params.populations_path, X[1] + '_population_LFP.h5'), ylabels=False,
                    unit='mV', T=[800,1000], ylim=[axis[2], axis[3]],
                    rasterized=False)
    
    # CSD background colorplot
    im = plot_signal_sum_colorplot(axes[2], params, os.path.join(params.populations_path, X[1] + '_population_CSD.h5'),
                              unit=r'$\mu$Amm$^{-3}$', T=[800,1000], ylabels=False,
                              colorbar=False,
                              ylim=[axis[2], axis[3]], fancy=False, 
                              cmap=plt.get_cmap('gray', 21) if analysis_params.bw else plt.get_cmap('bwr_r', 21),
                              rasterized=False)

    cb = phlp.colorbar(fig, axes[2], im,
                       width=0.05, height=0.5,
                       hoffset=-0.05, voffset=0.5)
    cb.set_label('($\mu$Amm$^{-3}$)', labelpad=0.)

    axes[2].set_ylim(-1550, 50)
    axes[2].set_title('LFP and CSD ({})'.format(X[1]), va='baseline')
    phlp.annotate_subplot(axes[2], ncols=1, nrows=1, letter='C')
    if show_xlabels:
        axes[2].set_xlabel(r'$t$ (ms)',labelpad=0.)
    else:
        axes[2].set_xlabel('')
    

    plotPowers(axes[3], params, params.Y, 'CSD', linestyles=linestyles, transient=transient, markerstyles=markerstyles, linewidths=linewidths)
    axes[3].axis(axes[3].axis('tight'))
    axes[3].set_ylim(-1550, 50)
    axes[3].set_yticks(-np.arange(16)*100)
    if show_xlabels:
        axes[3].set_xlabel(r'$\sigma^2$ ($(\mu$Amm$^{-3})^2$)', va='center')
    axes[3].set_title('CSD variance', va='baseline')
    axes[3].set_xlim(left=1E-7)
    phlp.remove_axis_junk(axes[3])
    phlp.annotate_subplot(axes[3], ncols=1, nrows=1, letter='D')
    
    
    plotPowers(axes[4], params, params.Y, 'LFP', linestyles=linestyles, transient=transient, markerstyles=markerstyles, linewidths=linewidths)
    axes[4].axis(axes[4].axis('tight'))
    axes[4].set_ylim(-1550, 50)
    axes[4].set_yticks(-np.arange(16)*100)
    if show_xlabels:
        axes[4].set_xlabel(r'$\sigma^2$ (mV$^2$)', va='center')
    axes[4].set_title('LFP variance', va='baseline')
    axes[4].legend(bbox_to_anchor=(1.37, 1.0), frameon=False)
    axes[4].set_xlim(left=1E-7)
    phlp.remove_axis_junk(axes[4])
    phlp.annotate_subplot(axes[4], ncols=1, nrows=1, letter='E')
    
    
    
    
    return fig
Example #9
0
def fig_intro(params,
              ana_params,
              T=[800, 1000],
              fraction=0.05,
              rasterized=False):
    '''set up plot for introduction'''
    ana_params.set_PLOS_2column_fig_style(ratio=0.5)

    #load spike as database
    networkSim = CachedNetwork(**params.networkSimParams)
    if analysis_params.bw:
        networkSim.colors = phlp.get_colors(len(networkSim.X))

    #set up figure and subplots
    fig = plt.figure()
    gs = gridspec.GridSpec(3, 4)

    fig.subplots_adjust(left=0.05, right=0.95, wspace=0.5, hspace=0.)

    #network diagram
    ax0_1 = fig.add_subplot(gs[:, 0], frameon=False)
    ax0_1.set_title('point-neuron network', va='bottom')

    network_sketch(ax0_1, yscaling=1.3)
    ax0_1.xaxis.set_ticks([])
    ax0_1.yaxis.set_ticks([])
    phlp.annotate_subplot(ax0_1,
                          ncols=4,
                          nrows=1,
                          letter='A',
                          linear_offset=0.065)

    #network raster
    ax1 = fig.add_subplot(gs[:, 1], frameon=True)
    phlp.remove_axis_junk(ax1)
    phlp.annotate_subplot(ax1,
                          ncols=4,
                          nrows=1,
                          letter='B',
                          linear_offset=0.065)

    x, y = networkSim.get_xy(T, fraction=fraction)
    # networkSim.plot_raster(ax1, T, x, y, markersize=0.1, alpha=1.,legend=False, pop_names=True)
    networkSim.plot_raster(ax1,
                           T,
                           x,
                           y,
                           markersize=0.2,
                           marker='_',
                           alpha=1.,
                           legend=False,
                           pop_names=True,
                           rasterized=rasterized)
    ax1.set_ylabel('')
    ax1.xaxis.set_major_locator(plt.MaxNLocator(4))
    ax1.set_title('spiking activity', va='bottom')
    a = ax1.axis()
    ax1.vlines(x['TC'][0], a[2], a[3], 'k', lw=0.25)

    #population
    ax2 = fig.add_subplot(gs[:, 2], frameon=False)
    ax2.xaxis.set_ticks([])
    ax2.yaxis.set_ticks([])
    plot_population(ax2,
                    params,
                    isometricangle=np.pi / 24,
                    plot_somas=False,
                    plot_morphos=True,
                    num_unitsE=1,
                    num_unitsI=1,
                    clip_dendrites=True,
                    main_pops=True,
                    title='',
                    rasterized=rasterized)
    ax2.set_title('multicompartment\nneurons',
                  va='bottom',
                  fontweight='normal')
    phlp.annotate_subplot(ax2,
                          ncols=4,
                          nrows=1,
                          letter='C',
                          linear_offset=0.065)

    #LFP traces in all channels
    ax3 = fig.add_subplot(gs[:, 3], frameon=True)
    phlp.remove_axis_junk(ax3)
    plot_signal_sum(ax3,
                    params,
                    fname=os.path.join(params.savefolder, 'LFPsum.h5'),
                    unit='mV',
                    vlimround=0.8,
                    T=T,
                    ylim=[ax2.axis()[2], ax2.axis()[3]],
                    rasterized=False)
    ax3.set_title('LFP', va='bottom')
    ax3.xaxis.set_major_locator(plt.MaxNLocator(4))
    phlp.annotate_subplot(ax3,
                          ncols=4,
                          nrows=1,
                          letter='D',
                          linear_offset=0.065)
    a = ax3.axis()
    ax3.vlines(x['TC'][0], a[2], a[3], 'k', lw=0.25)

    #draw some arrows:
    ax = plt.gca()
    ax.annotate(
        "",
        xy=(0.27, 0.5),
        xytext=(.24, 0.5),
        xycoords="figure fraction",
        arrowprops=dict(facecolor='black', arrowstyle='simple'),
    )
    ax.annotate(
        "",
        xy=(0.52, 0.5),
        xytext=(.49, 0.5),
        xycoords="figure fraction",
        arrowprops=dict(facecolor='black', arrowstyle='simple'),
    )
    ax.annotate(
        "",
        xy=(0.78, 0.5),
        xytext=(.75, 0.5),
        xycoords="figure fraction",
        arrowprops=dict(facecolor='black', arrowstyle='simple'),
    )

    return fig
Example #10
0
def fig_lfp_scaling(fig, params, bottom=0.55, top=0.95, channels=[0,3,7,11,13], T=[800.,1000.], Df=None,
                    mlab=True, NFFT=256, noverlap=128,
                    window=plt.mlab.window_hanning, letters='ABCD',
                    lag=20, show_titles=True, show_xlabels=True):

   
    fname_fullscale=os.path.join(params.savefolder, 'LFPsum.h5')
    fname_downscaled=os.path.join(params.savefolder, 'populations','subsamples', 'LFPsum_10_0.h5')

    # ana_params.set_PLOS_2column_fig_style(ratio=0.5)
    
    gs = gridspec.GridSpec(len(channels), 8, bottom=bottom, top=top)
    
    # fig = plt.figure()
    # fig.subplots_adjust(left=0.075, right=0.95, bottom=0.075, wspace=0.8, hspace=0.1)
  
    scaling_factor = np.sqrt(10)

    ##################################
    ###  LFP traces                ###
    ##################################

    ax = fig.add_subplot(gs[:, :3])

    phlp.annotate_subplot(ax, ncols=8/3., nrows=1, letter=letters[0], linear_offset=0.065)
    plot_signal_sum(ax, params, fname=os.path.join(params.savefolder, 'LFPsum.h5'),
                    unit='mV', scaling_factor= 1., scalebar=True,
                    vlimround=None,
                    T=T, ylim=[-1600, 50] ,color='k',label='$\Phi$',
                    rasterized=False,
                    zorder=1,)
    plot_signal_sum(ax, params, fname=os.path.join(params.savefolder, 'populations',
                                            'subsamples', 'LFPsum_10_0.h5'),
                    unit='mV', scaling_factor= scaling_factor,scalebar=False,
                    vlimround=None,
                    T=T, ylim=[-1600, 50],
                    color='gray' if analysis_params.bw else analysis_params.colorP,
                    label='$\hat{\Phi}^{\prime}$',
                    rasterized=False,
                    lw=1, zorder=0)

    
    if show_titles:
        ax.set_title('LFP & low-density predictor')
    if show_xlabels:
        ax.set_xlabel('$t$ (ms)', labelpad=0.)
    else:
        ax.set_xlabel('')


    #################################
    ### Correlations              ###
    #################################
    
    ax = fig.add_subplot(gs[:, 3])
    phlp.annotate_subplot(ax, ncols=8, nrows=1, letter=letters[1], linear_offset=0.065)
    phlp.remove_axis_junk(ax)
    
    datas = []
    files = [os.path.join(params.savefolder, 'LFPsum.h5'),
             os.path.join(params.savefolder, 'populations',
                                            'subsamples', 'LFPsum_10_0.h5')]
    for fil in files:
        f = h5py.File(fil)
        datas.append(f['data'].value[:, 200:])
        f.close()
    

    zvec = np.r_[params.electrodeParams['z']]
    cc = np.zeros(len(zvec))
    for ch in np.arange(len(zvec)):
        x0 = datas[0][ch]
        x0 -= x0.mean()
        x1 = datas[1][ch]
        x1 -= x1.mean()
        cc[ch] = np.corrcoef(x0, x1)[1, 0]
        
    ax.barh(zvec, cc, height=80, align='center', color='0.5', linewidth=0.5)
    
    # superimpose the chance level, obtained by mixing one input vector N times
    # while keeping the other fixed. We show boxes drawn left to right where
    # these denote mean +/- two standard deviations.
    N = 1000
    method = 'randphase' #or 'permute'
    chance = np.zeros((cc.size, N))
    for ch in np.arange(len(zvec)):
        x1 = datas[1][ch]
        x1 -= x1.mean()
        if method == 'randphase':
            x0 = datas[0][ch]
            x0 -= x0.mean()
            X00 = np.fft.fft(x0)
        for n in range(N):
            if method == 'permute':
                x0 = np.random.permutation(datas[0][ch])
            elif method == 'randphase':
                X0 = np.copy(X00)
                #random phase information such that spectra is preserved
                theta = np.random.uniform(0, 2*np.pi, size=X0.size // 2)
                #half-sided real and imaginary component 
                real = abs(X0[1:X0.size // 2 + 1])*np.cos(theta)
                imag = abs(X0[1:X0.size // 2 + 1])*np.sin(theta)
                
                #account for the antisymmetric phase values
                X0.imag[1:imag.size+1] = imag
                X0.imag[imag.size+1:] = -imag[::-1]
                X0.real[1:real.size+1] = real
                X0.real[real.size+1:] = real[::-1]
                x0 = np.fft.ifft(X0).real

            chance[ch, n] = np.corrcoef(x0, x1)[1, 0]
    
    # p-values, compute the fraction of chance correlations > cc at each channel
    p = []
    for i, x in enumerate(cc):
        p += [(chance[i, ] >= x).sum() / float(N)]
    
    print('p-values:', p)
    
    
    #compute the 99% percentile of the chance data
    right = np.percentile(chance, 99, axis=-1)
    
    ax.plot(right, zvec, ':', color='k', lw=1.)    
    ax.set_ylim([-1550, 50])
    ax.set_yticklabels([])
    ax.set_yticks(zvec)
    ax.set_xlim([0., 1.])
    ax.set_xticks([0.0, 0.5, 1])
    ax.yaxis.tick_left()

    if show_titles:
        ax.set_title('corr.\ncoef.')
    if show_xlabels:
        ax.set_xlabel('$cc$ (-)', labelpad=0.)
    



    ##################################
    ###  Single channel PSDs       ###
    ##################################

    freqs, PSD_fullscale = calc_signal_power(params, fname=fname_fullscale,
                                             transient=200, Df=Df, mlab=mlab,
                                             NFFT=NFFT, noverlap=noverlap,
                                             window=window)
    freqs, PSD_downscaled = calc_signal_power(params, fname=fname_downscaled,
                                              transient=200, Df=Df, mlab=mlab,
                                              NFFT=NFFT, noverlap=noverlap,
                                              window=window)
    inds = freqs >= 1  # frequencies greater than 4 Hz  

    for i, ch in enumerate(channels):
    
        ax = fig.add_subplot(gs[i, 4:6])
        if i == 0:
            phlp.annotate_subplot(ax, ncols=8/2., nrows=len(channels), letter=letters[2], linear_offset=0.065)
        phlp.remove_axis_junk(ax)
        ax.loglog(freqs[inds],PSD_fullscale[ch][inds],
                  color='k', label='$\gamma=1.0$',
                  zorder=1,)
        ax.loglog(freqs[inds],PSD_downscaled[ch][inds]*scaling_factor**2,
                  lw=1,
                  color='gray' if analysis_params.bw else analysis_params.colorP,
                  label='$\gamma=0.1, \zeta=\sqrt{10}$',
                  zorder=0,)
        ax.loglog(freqs[inds],PSD_downscaled[ch][inds]*scaling_factor**4,
                  lw=1,
                  color='0.75', label='$\gamma=0.1, \zeta=10$',
                  zorder=0)
        ax.xaxis.set_ticks_position('bottom')
        ax.yaxis.set_ticks_position('left')
        ax.text(0.8,0.9,'ch. %i' %(ch+1),horizontalalignment='left',
                     verticalalignment='center',
                     fontsize=6, 
                     transform=ax.transAxes)
        ax.yaxis.set_minor_locator(plt.NullLocator())
        if i < len(channels)-1:
            #ax.set_xticks([])
            ax.set_xticklabels([])
        ax.tick_params(axis='y',which='minor',bottom='off')
        ax.set_xlim([4E0,4E2])
        ax.set_ylim([3E-8,1E-4])
        if i == 0:
            ax.tick_params(axis='y', which='major', pad=0)
            ax.set_ylabel('(mV$^2$/Hz)', labelpad=0.)
            if show_titles:
                ax.set_title('power spectra')
        #ax.set_yticks([1E-9,1E-7,1E-5])
        if i > 0:
            ax.set_yticklabels([])
            
    if show_xlabels:
        ax.set_xlabel(r'$f$ (Hz)', labelpad=0.)     


    ##################################
    ###  PSD ratios                ###
    ##################################


    ax = fig.add_subplot(gs[:, 6:8])
    phlp.annotate_subplot(ax, ncols=8./2, nrows=1, letter=letters[3], linear_offset=0.065)

    
    PSD_ratio = PSD_fullscale/(PSD_downscaled*scaling_factor**2)
    zvec = np.r_[params.electrodeParams['z']]
    zvec = np.r_[zvec, zvec[-1] + np.diff(zvec)[-1]]
    inds = freqs >= 1  # frequencies greater than 4 Hz  

    im = ax.pcolormesh(freqs[inds], zvec+40, PSD_ratio[:, inds],
                        rasterized=False,
                        cmap=plt.get_cmap('gray_r', 18) if analysis_params.bw else plt.cm.get_cmap('Reds', 18),
                        vmin=1E0,vmax=1.E1)
    ax.set_xlim([4E0,4E2])
    ax.set_xscale('log')
    ax.set_yticks(zvec)
    yticklabels = ['ch. %i' %i for i in np.arange(len(zvec))+1]
    ax.set_yticklabels(yticklabels)
    plt.axis('tight')
    cb = phlp.colorbar(fig, ax, im,
                       width=0.05, height=0.5,
                       hoffset=-0.05, voffset=0.0)
    cb.set_label('(-)', labelpad=0.)
    phlp.remove_axis_junk(ax)

    if show_titles:
        ax.set_title('power ratio')
    if show_xlabels:
        ax.set_xlabel(r'$f$ (Hz)', labelpad=0.)


  
    return fig
Example #11
0
def fig_lfp_scaling(fig,
                    params,
                    bottom=0.55,
                    top=0.95,
                    channels=[0, 3, 7, 11, 13],
                    T=[800., 1000.],
                    Df=None,
                    mlab=True,
                    NFFT=256,
                    noverlap=128,
                    window=plt.mlab.window_hanning,
                    letters='ABCD',
                    lag=20,
                    show_titles=True,
                    show_xlabels=True):

    fname_fullscale = os.path.join(params.savefolder, 'LFPsum.h5')
    fname_downscaled = os.path.join(params.savefolder, 'populations',
                                    'subsamples', 'LFPsum_10_0.h5')

    # ana_params.set_PLOS_2column_fig_style(ratio=0.5)

    gs = gridspec.GridSpec(len(channels), 8, bottom=bottom, top=top)

    # fig = plt.figure()
    # fig.subplots_adjust(left=0.075, right=0.95, bottom=0.075, wspace=0.8, hspace=0.1)

    scaling_factor = np.sqrt(10)

    ##################################
    ###  LFP traces                ###
    ##################################

    ax = fig.add_subplot(gs[:, :3])

    phlp.annotate_subplot(ax,
                          ncols=8 / 3.,
                          nrows=1,
                          letter=letters[0],
                          linear_offset=0.065)
    plot_signal_sum(
        ax,
        params,
        fname=os.path.join(params.savefolder, 'LFPsum.h5'),
        unit='mV',
        scaling_factor=1.,
        scalebar=True,
        vlimround=None,
        T=T,
        ylim=[-1600, 50],
        color='k',
        label='$\Phi$',
        rasterized=False,
        zorder=1,
    )
    plot_signal_sum(
        ax,
        params,
        fname=os.path.join(params.savefolder, 'populations', 'subsamples',
                           'LFPsum_10_0.h5'),
        unit='mV',
        scaling_factor=scaling_factor,
        scalebar=False,
        vlimround=None,
        T=T,
        ylim=[-1600, 50],
        color='gray' if analysis_params.bw else analysis_params.colorP,
        label='$\hat{\Phi}^{\prime}$',
        rasterized=False,
        lw=1,
        zorder=0)

    if show_titles:
        ax.set_title('LFP & low-density predictor')
    if show_xlabels:
        ax.set_xlabel('$t$ (ms)', labelpad=0.)
    else:
        ax.set_xlabel('')

    #################################
    ### Correlations              ###
    #################################

    ax = fig.add_subplot(gs[:, 3])
    phlp.annotate_subplot(ax,
                          ncols=8,
                          nrows=1,
                          letter=letters[1],
                          linear_offset=0.065)
    phlp.remove_axis_junk(ax)

    datas = []
    files = [
        os.path.join(params.savefolder, 'LFPsum.h5'),
        os.path.join(params.savefolder, 'populations', 'subsamples',
                     'LFPsum_10_0.h5')
    ]
    for fil in files:
        f = h5py.File(fil)
        datas.append(f['data'][()][:, 200:])
        f.close()

    zvec = np.r_[params.electrodeParams['z']]
    cc = np.zeros(len(zvec))
    for ch in np.arange(len(zvec)):
        x0 = datas[0][ch]
        x0 -= x0.mean()
        x1 = datas[1][ch]
        x1 -= x1.mean()
        cc[ch] = np.corrcoef(x0, x1)[1, 0]

    ax.barh(zvec, cc, height=80, align='center', color='0.5', linewidth=0.5)

    # superimpose the chance level, obtained by mixing one input vector N times
    # while keeping the other fixed. We show boxes drawn left to right where
    # these denote mean +/- two standard deviations.
    N = 1000
    method = 'randphase'  #or 'permute'
    chance = np.zeros((cc.size, N))
    for ch in np.arange(len(zvec)):
        x1 = datas[1][ch]
        x1 -= x1.mean()
        if method == 'randphase':
            x0 = datas[0][ch]
            x0 -= x0.mean()
            X00 = np.fft.fft(x0)
        for n in range(N):
            if method == 'permute':
                x0 = np.random.permutation(datas[0][ch])
            elif method == 'randphase':
                X0 = np.copy(X00)
                #random phase information such that spectra is preserved
                theta = np.random.uniform(0, 2 * np.pi, size=X0.size // 2)
                #half-sided real and imaginary component
                real = abs(X0[1:X0.size // 2 + 1]) * np.cos(theta)
                imag = abs(X0[1:X0.size // 2 + 1]) * np.sin(theta)

                #account for the antisymmetric phase values
                X0.imag[1:imag.size + 1] = imag
                X0.imag[imag.size + 1:] = -imag[::-1]
                X0.real[1:real.size + 1] = real
                X0.real[real.size + 1:] = real[::-1]
                x0 = np.fft.ifft(X0).real

            chance[ch, n] = np.corrcoef(x0, x1)[1, 0]

    # p-values, compute the fraction of chance correlations > cc at each channel
    p = []
    for i, x in enumerate(cc):
        p += [(chance[i, ] >= x).sum() / float(N)]

    print('p-values:', p)

    #compute the 99% percentile of the chance data
    right = np.percentile(chance, 99, axis=-1)

    ax.plot(right, zvec, ':', color='k', lw=1.)
    ax.set_ylim([-1550, 50])
    ax.set_yticklabels([])
    ax.set_yticks(zvec)
    ax.set_xlim([0., 1.])
    ax.set_xticks([0.0, 0.5, 1])
    ax.yaxis.tick_left()

    if show_titles:
        ax.set_title('corr.\ncoef.')
    if show_xlabels:
        ax.set_xlabel('$cc$ (-)', labelpad=0.)

    ##################################
    ###  Single channel PSDs       ###
    ##################################

    freqs, PSD_fullscale = calc_signal_power(params,
                                             fname=fname_fullscale,
                                             transient=200,
                                             Df=Df,
                                             mlab=mlab,
                                             NFFT=NFFT,
                                             noverlap=noverlap,
                                             window=window)
    freqs, PSD_downscaled = calc_signal_power(params,
                                              fname=fname_downscaled,
                                              transient=200,
                                              Df=Df,
                                              mlab=mlab,
                                              NFFT=NFFT,
                                              noverlap=noverlap,
                                              window=window)
    inds = freqs >= 1  # frequencies greater than 4 Hz

    for i, ch in enumerate(channels):

        ax = fig.add_subplot(gs[i, 4:6])
        if i == 0:
            phlp.annotate_subplot(ax,
                                  ncols=8 / 2.,
                                  nrows=len(channels),
                                  letter=letters[2],
                                  linear_offset=0.065)
        phlp.remove_axis_junk(ax)
        ax.loglog(
            freqs[inds],
            PSD_fullscale[ch][inds],
            color='k',
            label='$\gamma=1.0$',
            zorder=1,
        )
        ax.loglog(
            freqs[inds],
            PSD_downscaled[ch][inds] * scaling_factor**2,
            lw=1,
            color='gray' if analysis_params.bw else analysis_params.colorP,
            label='$\gamma=0.1, \zeta=\sqrt{10}$',
            zorder=0,
        )
        ax.loglog(freqs[inds],
                  PSD_downscaled[ch][inds] * scaling_factor**4,
                  lw=1,
                  color='0.75',
                  label='$\gamma=0.1, \zeta=10$',
                  zorder=0)
        ax.xaxis.set_ticks_position('bottom')
        ax.yaxis.set_ticks_position('left')
        ax.text(0.8,
                0.9,
                'ch. %i' % (ch + 1),
                horizontalalignment='left',
                verticalalignment='center',
                fontsize=6,
                transform=ax.transAxes)
        ax.yaxis.set_minor_locator(plt.NullLocator())
        if i < len(channels) - 1:
            #ax.set_xticks([])
            ax.set_xticklabels([])
        ax.tick_params(axis='y', which='minor', bottom='off')
        ax.set_xlim([4E0, 4E2])
        ax.set_ylim([3E-8, 1E-4])
        if i == 0:
            ax.tick_params(axis='y', which='major', pad=0)
            ax.set_ylabel('(mV$^2$/Hz)', labelpad=0.)
            if show_titles:
                ax.set_title('power spectra')
        #ax.set_yticks([1E-9,1E-7,1E-5])
        if i > 0:
            ax.set_yticklabels([])

    if show_xlabels:
        ax.set_xlabel(r'$f$ (Hz)', labelpad=0.)

    ##################################
    ###  PSD ratios                ###
    ##################################

    ax = fig.add_subplot(gs[:, 6:8])
    phlp.annotate_subplot(ax,
                          ncols=8. / 2,
                          nrows=1,
                          letter=letters[3],
                          linear_offset=0.065)

    PSD_ratio = PSD_fullscale / (PSD_downscaled * scaling_factor**2)
    zvec = np.r_[params.electrodeParams['z']]
    zvec = np.r_[zvec, zvec[-1] + np.diff(zvec)[-1]]
    inds = freqs >= 1  # frequencies greater than 4 Hz

    im = ax.pcolormesh(freqs[inds],
                       zvec + 40,
                       PSD_ratio[:, inds],
                       rasterized=False,
                       cmap=plt.get_cmap('gray_r', 18)
                       if analysis_params.bw else plt.cm.get_cmap('Reds', 18),
                       vmin=1E0,
                       vmax=1.E1)
    ax.set_xlim([4E0, 4E2])
    ax.set_xscale('log')
    ax.set_yticks(zvec)
    yticklabels = ['ch. %i' % i for i in np.arange(len(zvec)) + 1]
    ax.set_yticklabels(yticklabels)
    plt.axis('tight')
    cb = phlp.colorbar(fig,
                       ax,
                       im,
                       width=0.05,
                       height=0.5,
                       hoffset=-0.05,
                       voffset=0.0)
    cb.set_label('(-)', labelpad=0.)
    phlp.remove_axis_junk(ax)

    if show_titles:
        ax.set_title('power ratio')
    if show_xlabels:
        ax.set_xlabel(r'$f$ (Hz)', labelpad=0.)

    return fig
Example #12
0
def fig_intro(params, fraction=0.05, rasterized=False):
    '''set up plot for introduction'''
    plt.close("all")

    #load spike as database
    networkSim = CachedNetwork(**params.networkSimParams)
    # num_pops = 8

    fig = plt.figure(figsize=[4.5, 3.5])

    fig.subplots_adjust(left=0.03, right=0.98, wspace=0.5, hspace=0.)
    ax_spikes = fig.add_axes([0.09, 0.4, 0.2, 0.55])
    ax_morph = fig.add_axes([0.37, 0.3, 0.3, 0.75],
                            frameon=False,
                            aspect=1,
                            xticks=[],
                            yticks=[])
    ax_lfp = fig.add_axes([0.73, 0.4, 0.23, 0.55], frameon=True)
    ax_4s = fig.add_axes([0.42, 0.05, 0.25, 0.2],
                         frameon=False,
                         aspect=1,
                         title='head model',
                         xticks=[],
                         yticks=[])
    ax_top_EEG = fig.add_axes([0.65, 0.02, 0.33, 0.32],
                              frameon=False,
                              xticks=[],
                              yticks=[],
                              ylim=[-0.5, .25])
    dt = 1
    t_idx = 875
    T = [t_idx, t_idx + 75]

    fig.text(0.55, 0.97, "multicompartment neurons", fontsize=6, ha="center")
    ax_spikes.set_title("spiking activity", fontsize=6)
    ax_lfp.set_title("LFP", fontsize=6)

    #network raster
    ax_spikes.xaxis.set_major_locator(plt.MaxNLocator(4))
    phlp.remove_axis_junk(ax_spikes)
    phlp.annotate_subplot(ax_spikes,
                          ncols=4,
                          nrows=1,
                          letter='A',
                          linear_offset=0.045)
    x, y = networkSim.get_xy(T, fraction=fraction)

    networkSim.plot_raster(ax_spikes,
                           T,
                           x,
                           y,
                           markersize=0.2,
                           marker='_',
                           alpha=1.,
                           legend=False,
                           pop_names=True,
                           rasterized=rasterized)

    #population
    plot_population(ax_morph,
                    params,
                    isometricangle=np.pi / 24,
                    plot_somas=False,
                    plot_morphos=True,
                    num_unitsE=1,
                    num_unitsI=1,
                    clip_dendrites=True,
                    main_pops=True,
                    title='',
                    rasterized=rasterized)
    # ax_morph.set_title('multicompartment neurons', va='top')
    phlp.annotate_subplot(ax_morph,
                          ncols=5,
                          nrows=1,
                          letter='B',
                          linear_offset=0.005)

    phlp.remove_axis_junk(ax_lfp)
    #ax_lfp.set_title('LFP', va='bottom')
    ax_lfp.xaxis.set_major_locator(plt.MaxNLocator(4))
    phlp.annotate_subplot(ax_lfp,
                          ncols=4,
                          nrows=2,
                          letter='C',
                          linear_offset=0.025)
    #print(ax_morph.axis())
    plot_signal_sum(ax_lfp,
                    params,
                    fname=join(params.savefolder, 'LFPsum.h5'),
                    unit='mV',
                    vlimround=0.8,
                    T=T,
                    ylim=[-1600, 100],
                    rasterized=False)

    plot_cdms(fig, params, dt, T)

    plot_foursphere_to_ax(ax_4s)
    phlp.annotate_subplot(ax_4s,
                          ncols=3,
                          nrows=7,
                          letter='E',
                          linear_offset=0.05)

    # Plot EEG at top of head
    # ax_top_EEG.xaxis.set_major_locator(plt.MaxNLocator(4))
    phlp.annotate_subplot(ax_top_EEG,
                          ncols=1,
                          nrows=1,
                          letter='F',
                          linear_offset=-0.08)

    # ax_top_EEG.set_ylabel("$\mu$V", labelpad=-3)
    summed_top_EEG = np.load(join(params.savefolder, "summed_EEG.npy"))

    simple_EEG_single_pop = np.load(
        join(params.savefolder, "simple_EEG_single_pop.npy"))
    simple_EEG_pops_with_pos = np.load(
        join(params.savefolder, "simple_EEG_pops_with_pos.npy"))

    tvec = np.arange(len(summed_top_EEG)) * dt

    # sub_pops = ["L5I", "L4I", "L6I", "L23I", "L5E", "L4E", "L6E", "L23E"]
    pops = np.unique(next(zip(*params.mapping_Yy)))
    colors = phlp.get_colors(np.unique(pops).size)
    for p_idx, pop in enumerate(pops):
        pop_eeg = np.load(join(params.savefolder, "EEG_{}.npy".format(pop)))
        pop_eeg -= np.average(pop_eeg)
        # pop_sum.append(pop_eeg)
        ax_top_EEG.plot(pop_eeg, c=colors[p_idx], lw=1)

    ax_top_EEG.plot([878, 878], [-0.1, -0.3], c='k', lw=1)
    ax_top_EEG.plot([878, 888], [-0.3, -0.3], c='k', lw=1)
    ax_top_EEG.text(879, -0.2, "0.2 $\mu$V", va="center")
    ax_top_EEG.text(885, -0.32, "10 ms", va="top", ha="center")

    y0 = summed_top_EEG - np.average(summed_top_EEG)
    y1 = simple_EEG_single_pop - np.average(simple_EEG_single_pop)
    y2 = simple_EEG_pops_with_pos - np.average(simple_EEG_pops_with_pos)

    l3, = ax_top_EEG.plot(tvec, y0 - y2, lw=1.5, c='orange', ls='-')
    l1, = ax_top_EEG.plot(tvec, y0, lw=1.5, c='k')
    l2, = ax_top_EEG.plot(tvec, y2, lw=1.5, c='r', ls='--')

    t0_plot_idx = np.argmin(np.abs(tvec - 875))
    t1_plot_idx = np.argmin(np.abs(tvec - 950))
    max_sig_idx = np.argmax(np.abs(y0[t0_plot_idx:])) + t0_plot_idx

    EEG_error_at_max_1 = np.abs(y0[max_sig_idx] - y1[max_sig_idx]) / np.abs(
        y0[max_sig_idx])
    EEG_error_at_max_2 = np.abs(y0[max_sig_idx] - y2[max_sig_idx]) / np.abs(
        y0[max_sig_idx])

    max_EEG_error_1 = np.max(
        np.abs(y0[t0_plot_idx:t1_plot_idx] - y1[t0_plot_idx:t1_plot_idx]) /
        np.max(np.abs(y0[t0_plot_idx:t1_plot_idx])))
    max_EEG_error_2 = np.max(
        np.abs(y0[t0_plot_idx:t1_plot_idx] - y2[t0_plot_idx:t1_plot_idx]) /
        np.max(np.abs(y0[t0_plot_idx:t1_plot_idx])))

    print(
        "Error with single pop at sig max (t={:1.3f} ms): {:1.4f}. Max relative error: {:1.4f}"
        .format(tvec[max_sig_idx], EEG_error_at_max_1, max_EEG_error_1))
    print(
        "Error with multipop at sig max (t={:1.3f} ms): {:1.4f}. Max relative error: {:1.4f}"
        .format(tvec[max_sig_idx], EEG_error_at_max_2, max_EEG_error_2))
    ax_top_EEG.legend([l1, l2, l3], ["full sum", "pop. dipole", "difference"],
                      frameon=False,
                      loc=(0.5, 0.1))
    # phlp.remove_axis_junk(ax_top_EEG)
    ax_top_EEG.axvline(900, c='gray', ls='--')
    ax_lfp.axvline(900, c='gray', ls='--')

    ax_top_EEG.set_xlim(T)

    fig.savefig(join("..", "figures", 'Figure6.png'), dpi=300)
    fig.savefig(join("..", "figures", 'Figure6.pdf'), dpi=300)
Example #13
0
    ax3.xaxis.set_ticks_position('bottom')
    ax3.yaxis.set_ticks_position('left')
    ax3.set_xlabel(r'$t$ (ms)', labelpad=0.1)


    ############################################################################    
    # C part, CSD
    ############################################################################
    ax5 = fig.add_subplot(gs[:, 2])
    plt.locator_params(nbins=4)
    phlp.remove_axis_junk(ax5)
    if show_ax_labels:
        phlp.annotate_subplot(ax5, ncols=1, nrows=1, letter='C', linear_offset=0.065)
    plot_signal_sum(ax5, params,
                    fname=os.path.join(params.savefolder, 'CSDsum.h5'),
                    unit='$\mu$A mm$^{-3}$',
                    T=T,
                    ylim=[-1550, 50],
                    rasterized=False)
    ax5.set_title('CSD')
    a = ax5.axis()
    ax5.vlines(x['TC'][0], a[2], a[3], 'k', lw=0.25)
    

    #show traces superimposed on color image
    if show_images:
        im = plot_signal_sum_colorplot(ax5, params, os.path.join(params.savefolder, 'CSDsum.h5'),
                                  unit=r'$\mu$Amm$^{-3}$', T=T,
                                  ylim=[-1550, 50],
                                  fancy=False, colorbar=False,
                                  cmap=plt.get_cmap('gray', 21) if analysis_params.bw else plt.get_cmap('bwr_r', 21),
                                  rasterized=False)
Example #14
0
def fig_exc_inh_contrib(fig, axes, params, savefolders, T=[800, 1000], transient=200,
                        panel_labels = 'FGHIJ', show_xlabels=True):
    '''
    plot time series LFPs and CSDs with signal variances as function of depth
    for the cases with all synapses intact, or knocking out excitatory
    input or inhibitory input to the postsynaptic target region
    
    args:
    ::
        fig : 
        axes :  
        savefolders : list of simulation output folders
        T : list of ints, first and last time sample
        transient : int, duration of transient period
        
    returns:
    ::
        
        matplotlib.figure.Figure object
    
    '''
    # params = multicompartment_params()
    # ana_params = analysis_params.params()

    
    #file name types
    file_names = ['CSDsum.h5', 'LFPsum.h5']
    
    #panel titles
    panel_titles = [
        'LFP&CSD\nexc. syn.',
        'LFP&CSD\ninh. syn.',
        'LFP&CSD\ncompound',
        'CSD variance',
        'LFP variance',]
    
    #labels
    labels = [
        'exc. syn.',
        'inh. syn.',
        'SUM']
    
    #some colors for traces
    if analysis_params.bw:
        colors = ['k', 'gray', 'k']
        # lws = [0.75, 0.75, 1.5]
        lws = [1.25, 1.25, 1.25]
    else:
        colors = [analysis_params.colorE, analysis_params.colorI, 'k']
        # colors = 'rbk'
        # lws = [0.75, 0.75, 1.5]
        lws = [1.25, 1.25, 1.25]

    
    #scalebar labels
    units = ['$\mu$A mm$^{-3}$', 'mV']
    
    #depth of each contact site
    depth = params.electrodeParams['z']


    # #set up figure
    # #figure aspect
    # ana_params.set_PLOS_2column_fig_style(ratio=0.5)
    # fig, axes = plt.subplots(1,5)
    # fig.subplots_adjust(left=0.06, right=0.96, wspace=0.4, hspace=0.2)
    
    #clean up
    for ax in axes.flatten():
        phlp.remove_axis_junk(ax)


    for i, file_name in enumerate(file_names):
        #get the global data scaling bar range for use in latter plots
        #TODO: find nicer solution without creating figure
        dum_fig, dum_ax = plt.subplots(1)
        vlim_LFP = 0
        vlim_CSD = 0
        for savefolder in savefolders:
            vlimround0 = plot_signal_sum(dum_ax, params,
                                         os.path.join(os.path.split(params.savefolder)[0], savefolder, file_name),
                                         rasterized=False)
            if vlimround0 > vlim_LFP:
                vlim_LFP = vlimround0
            im = plot_signal_sum_colorplot(dum_ax, params, os.path.join(os.path.split(params.savefolder)[0], savefolder, file_name),
                                           cmap=plt.get_cmap('gray', 21) if analysis_params.bw else plt.get_cmap('bwr_r', 21),
                                           rasterized=False)
            if abs(im.get_array()).max() > vlim_CSD:
                vlim_CSD = abs(im.get_array()).max()
                                                  
        plt.close(dum_fig)


        for j, savefolder in enumerate(savefolders):
            ax = axes[j]
            if i == 1:
                plot_signal_sum(ax, params, os.path.join(os.path.split(params.savefolder)[0], savefolder, file_name),
                            unit=units[i], T=T,
                            color='k',
                            # color='k' if analysis_params.bw else colors[j],
                            vlimround=vlim_LFP, rasterized=False)
            elif i == 0:
                im = plot_signal_sum_colorplot(ax, params, os.path.join(os.path.split(params.savefolder)[0], savefolder, file_name),
                              unit=r'($\mu$Amm$^{-3}$)', T=T, ylabels=True,
                              colorbar=False,
                              fancy=False, cmap=plt.get_cmap('gray', 21) if analysis_params.bw else plt.get_cmap('bwr_r', 21),
                              absmax=vlim_CSD,
                              rasterized=False)
            
            
            ax.axis((T[0], T[1], -1550, 50))
            ax.set_title(panel_titles[j], va='baseline')
            
            if i == 0:
                phlp.annotate_subplot(ax, ncols=1, nrows=1, letter=panel_labels[j])
            if j != 0:
                ax.set_yticklabels([])
            
            if i == 0:#and j == 2:
                cb = phlp.colorbar(fig, ax, im,
                                   width=0.05, height=0.5,
                                   hoffset=-0.05, voffset=0.5)
                cb.set_label('($\mu$Amm$^{-3}$)', labelpad=0.)
            ax.xaxis.set_major_locator(plt.MaxNLocator(3))
            if show_xlabels:
                ax.set_xlabel(r'$t$ (ms)', labelpad=0.)
            else:
                ax.set_xlabel('')

            
    #power in CSD
    ax = axes[3]
    datas = []    
    for j, savefolder in enumerate(savefolders):
        f = h5py.File(os.path.join(os.path.split(params.savefolder)[0], savefolder, 'CSDsum.h5'))
        var = f['data'].value[:, transient:].var(axis=1)
        ax.semilogx(var, depth,
                    color=colors[j], label=labels[j], lw=lws[j], clip_on=False)
        datas.append(f['data'].value[:, transient:])
        f.close()
    #control variances
    vardiff = datas[0].var(axis=1) + datas[1].var(axis=1) + np.array([2*np.cov(x,y)[0,1] for (x,y) in zip(datas[0], datas[1])]) - datas[2].var(axis=1)
    #ax.semilogx(abs(vardiff), depth, color='gray', lw=1, label='control')
    ax.axis(ax.axis('tight'))
    ax.set_ylim(-1550, 50)
    ax.set_yticks(-np.arange(16)*100)
    if show_xlabels:
        ax.set_xlabel(r'$\sigma^2$ ($(\mu$Amm$^{-3})^2$)', labelpad=0.)
    ax.set_title(panel_titles[3], va='baseline')
    phlp.annotate_subplot(ax, ncols=1, nrows=1, letter=panel_labels[3])
    ax.set_yticklabels([])


    #power in LFP
    ax = axes[4]

    datas = []
    for j, savefolder in enumerate(savefolders):
        f = h5py.File(os.path.join(os.path.split(params.savefolder)[0], savefolder, 'LFPsum.h5'))
        var = f['data'].value[:, transient:].var(axis=1)
        ax.semilogx(var, depth,
                    color=colors[j], label=labels[j], lw=lws[j], clip_on=False)
        datas.append(f['data'].value[:, transient:])
        f.close()
    #control variances
    vardiff = datas[0].var(axis=1) + datas[1].var(axis=1) + np.array([2*np.cov(x,y)[0,1] for (x,y) in zip(datas[0], datas[1])]) - datas[2].var(axis=1)
    ax.axis(ax.axis('tight'))
    ax.set_ylim(-1550, 50)
    ax.set_yticks(-np.arange(16)*100)
    if show_xlabels:
        ax.set_xlabel(r'$\sigma^2$ (mV$^2$)', labelpad=0.)
    ax.set_title(panel_titles[4], va='baseline')
    phlp.annotate_subplot(ax, ncols=1, nrows=1, letter=panel_labels[4])

    ax.legend(bbox_to_anchor=(1.3, 1.0), frameon=False)
    ax.set_yticklabels([])
Example #15
0
def fig_kernel_lfp_EITN_II(savefolders, params, transient=200, T=[800., 1000.], X='L5E',
                   lags=[20, 20], channels=[0,3,7,11,13]):

    '''
    This function calculates the  STA of LFP, extracts kernels and recontructs the LFP from kernels.
    
    Arguments
    ::
      transient : the time in milliseconds, after which the analysis should begin
                so as to avoid any starting transients
      X : id of presynaptic trigger population
       
    '''

    # Electrode geometry
    zvec = np.r_[params.electrodeParams['z']]

    alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'



    ana_params.set_PLOS_2column_fig_style(ratio=0.5)
    # Start the figure
    fig = plt.figure()
    fig.subplots_adjust(left=0.06, right=0.95, bottom=0.08, top=0.9, hspace=0.23, wspace=0.55) 

    # create grid_spec
    gs = gridspec.GridSpec(len(channels), 7)


    ###########################################################################
    # spikegen "network" activity
    ############################################################################
    
    
    # path to simulation files
    savefolder = 'simulation_output_spikegen'
    params.savefolder = os.path.join(os.path.split(params.savefolder)[0],
                                         savefolder)
    params.figures_path = os.path.join(params.savefolder, 'figures')
    params.spike_output_path = os.path.join(params.savefolder,
                                                       'processed_nest_output')
    params.networkSimParams['spike_output_path'] = params.spike_output_path
    
    
    # Get the spikegen LFP:
    f = h5py.File(os.path.join('simulation_output_spikegen', 'LFPsum.h5'))
    srate = f['srate'].value
    tvec = np.arange(f['data'].shape[1]) * 1000. / srate
    
    # slice
    inds = (tvec < params.tstop) & (tvec >= transient)
    
    data_sg_raw = f['data'].value.astype(float)
    data_sg = data_sg_raw[:, inds]
    f.close()
    
    # kernel width
    kwidth = 20
    
    # create some dummy spike times
    activationtimes = np.array([x*100 for x in range(3,11)] + [200])
    networkSimSpikegen = CachedNetwork(**params.networkSimParams)

    x, y = networkSimSpikegen.get_xy([transient, params.tstop])

    
    ############################################################################
    ## Part A: spatiotemporal kernels, all presynaptic populations
    #############################################################################
    #
    #titles = ['TC',
    #          'L23E/I',
    #          'LFP kernels \n L4E/I',
    #          'L5E/I',
    #          'L6E/I',
    #          ]
    #
    #COUNTER = 0 
    #for i, X__ in enumerate(([['TC']]) + zip(params.X[1::2], params.X[2::2])):        
    #    ax = fig.add_subplot(gs[:len(channels), i])
    #    if i == 0:
    #        phlp.annotate_subplot(ax, ncols=7, nrows=4, letter=alphabet[0], linear_offset=0.02)
    #
    #    for j, X_ in enumerate(X__):
    #        # create spikegen histogram for population Y
    #        cinds = np.arange(activationtimes[np.arange(-1, 8)][COUNTER]-kwidth,
    #                          activationtimes[np.arange(-1, 8)][COUNTER]+kwidth+2)
    #        x0_sg = np.histogram(x[X_], bins=cinds)[0].astype(float)
    #        
    #        if X_ == ('TC'):
    #            color='r'
    #        else:
    #            color=('r', 'b')[j]
    #        
    #        
    #        # plot kernel as correlation of spikegen LFP signal with delta spike train
    #        xcorr, vlimround = plotting_correlation(params,
    #                                                x0_sg/x0_sg.sum()**2, 
    #                                                data_sg_raw[:, cinds[:-1]]*1E3,
    #                                                ax, normalize=False,
    #                                                lag=kwidth,
    #                                                color=color,
    #                                                scalebar=False)
    #        if i > 0:
    #            ax.set_yticklabels([])
    #        
    #        ## Create scale bar
    #        ax.plot([kwidth, kwidth],
    #            [-1500 + j*3*100, -1400 + j*3*100], lw=2, color=color,
    #            clip_on=False)
    #        ax.text(kwidth*1.08, -1450 + j*3*100, '%.1f $\mu$V' % vlimround,
    #                    rotation='vertical', va='center')
    #
    #        ax.set_xlim((-5, kwidth))
    #        ax.set_xticks([-20, 0, 20])
    #        ax.set_xticklabels([-20, 0, 20])
    #        
    #        COUNTER += 1
    #        
    #    ax.set_title(titles[i])
    

    ################################################
    # Iterate over savefolders
    ################################################

    for i, (savefolder, lag) in enumerate(zip(savefolders, lags)):
        
        # path to simulation files
        params.savefolder = os.path.join(os.path.split(params.savefolder)[0],
                                         savefolder)
        params.figures_path = os.path.join(params.savefolder, 'figures')
        params.spike_output_path = os.path.join(params.savefolder,
                                                'processed_nest_output')
        params.networkSimParams['spike_output_path'] = params.spike_output_path
        
        #load spike as database inside function to avoid buggy behaviour
        networkSim = CachedNetwork(**params.networkSimParams)
        
        
        
        # Get the Compound LFP: LFPsum : data[nchannels, timepoints ]
        f = h5py.File(os.path.join(params.savefolder, 'LFPsum.h5'))
        data_raw = f['data'].value
        srate = f['srate'].value
        tvec = np.arange(data_raw.shape[1]) * 1000. / srate
        # slice
        inds = (tvec < params.tstop) & (tvec >= transient)
        data = data_raw[:, inds]
        # subtract mean
        dataT = data.T - data.mean(axis=1)
        data = dataT.T
        f.close()
        
        # Get the spikegen LFP:
        f = h5py.File(os.path.join('simulation_output_spikegen', 'LFPsum.h5'))
        data_sg_raw = f['data'].value
        
        f.close()
        #
        #
        #
        #
        #########################################################################
        ## Part B: STA LFP
        #########################################################################
        #
        #titles = ['staLFP(%s)\n(spont.)' % X, 'staLFP(%s)\n(AC. mod.)' % X]
        #ax = fig.add_subplot(gs[:len(channels), 5 + i])
        #if i == 0:
        #    phlp.annotate_subplot(ax, ncols=15, nrows=4, letter=alphabet[i+1],
        #                          linear_offset=0.02)
        #  
        #collect the spikes x is the times, y is the id of the cell.
        x, y = networkSim.get_xy([0,params.tstop])
        #
        ## Get the spikes for the population of interest given as 'Y'
        bins = np.arange(0, params.tstop+2) + 0.5
        x0_raw = np.histogram(x[X], bins=bins)[0]
        x0 = x0_raw[inds].astype(float)
        #
        ## correlation between firing rate and LFP deviation
        ## from mean normalized by the number of spikes  
        #xcorr, vlimround = plotting_correlation(params,
        #                                        x0/x0.sum(), 
        #                                        data*1E3,
        #                                        ax, normalize=False, 
        #                                        #unit='%.3f mV',
        #                                        lag=lag,
        #                                        scalebar=False,
        #                                        color='k',
        #                                        title=titles[i],
        #                                        )
        #
        ## Create scale bar
        #ax.plot([lag, lag],
        #    [-1500, -1400], lw=2, color='k',
        #    clip_on=False)
        #ax.text(lag*1.08, -1450, '%.1f $\mu$V' % vlimround,
        #            rotation='vertical', va='center')
        #
        #
        #[Xind] = np.where(np.array(networkSim.X) == X)[0]        
        #        
        ## create spikegen histogram for population Y
        #x0_sg = np.zeros(x0.shape, dtype=float)
        #x0_sg[activationtimes[Xind]] += params.N_X[Xind]
        #
        #
        #ax.set_yticklabels([])
        #ax.set_xticks([-lag, 0, lag])
        #ax.set_xticklabels([-lag, 0, lag])

        
        ###########################################################################
        # Part C, F: LFP and reconstructed LFP
        ############################################################################

        # create grid_spec
        gsb = gridspec.GridSpec(len(channels), 8)

      
        ax = fig.add_subplot(gsb[:, (i*4):(i*4+2)])
        phlp.annotate_subplot(ax, ncols=8/2., nrows=4, letter=alphabet[i*3+2],
                              linear_offset=0.02)
          
        # extract kernels, force negative lags to be zero
        kernels = np.zeros((len(params.N_X), 16, kwidth*2))
        for j in range(len(params.X)):
            kernels[j, :, kwidth:] = data_sg_raw[:, (j+2)*100:kwidth+(j+2)*100]/params.N_X[j]
    
        LFP_reconst_raw = np.zeros(data_raw.shape)
    
        for j, pop in enumerate(params.X):
            x0_raw = np.histogram(x[pop], bins=bins)[0].astype(float)
            for ch in range(kernels.shape[1]):
                LFP_reconst_raw[ch] += np.convolve(x0_raw, kernels[j, ch],
                                                   'same')
        
        # slice
        LFP_reconst = LFP_reconst_raw[:, inds]
        # subtract mean
        LFP_reconstT = LFP_reconst.T - LFP_reconst.mean(axis=1)
        LFP_reconst = LFP_reconstT.T
        vlimround = plot_signal_sum(ax, params,
                                    fname=os.path.join(params.savefolder,
                                                           'LFPsum.h5'),
                    unit='mV', scalebar=True,
                        T=T, ylim=[-1550, 50],
                        color='k', label='$real$',
                        rasterized=False)
    
        plot_signal_sum(ax, params, fname=LFP_reconst_raw,
                    unit='mV', scaling_factor= 1., scalebar=False,
                        vlimround=vlimround,
                        T=T, ylim=[-1550, 50],
                        color='r', label='$reconstr$',
                        rasterized=False)
        ax.set_title('LFP & population \n rate predictor')
        if i > 0:
            ax.set_yticklabels([])


        
        ###########################################################################
        # Part D,G: Correlation coefficient
        ############################################################################
        
        ax = fig.add_subplot(gsb[:, i*4+2:i*4+3])
        phlp.remove_axis_junk(ax)
        phlp.annotate_subplot(ax, ncols=8./1, nrows=4, letter=alphabet[i*3+3],
                              linear_offset=0.02)
            
        cc = np.zeros(len(zvec))
        for ch in np.arange(len(zvec)):
            cc[ch] = np.corrcoef(data[ch], LFP_reconst[ch])[1, 0]
        
        ax.barh(zvec, cc, height=90, align='center', color='1', linewidth=0.5)
        ax.set_ylim([-1550, 50])
        ax.set_yticklabels([])
        ax.set_yticks(zvec)
        ax.set_xlim([0.0, 1.])
        ax.set_xticks([0.0, 0.5, 1])
        ax.yaxis.tick_left()
        ax.set_xlabel('$cc$ (-)', labelpad=0.1)
        ax.set_title('corr. \n coef.')
    
        print 'correlation coefficients:'
        print cc


        ###########################################################################
        # Part E,H: Power spectra
        ############################################################################
        

        #compute PSDs ratio between ground truth and estimate
        freqs, PSD_data = calc_signal_power(params, fname=data,
                                            transient=transient, Df=None, mlab=True,
                                            NFFT=256, noverlap=128,
                                            window=plt.mlab.window_hanning)
        freqs, PSD_LFP_reconst = calc_signal_power(params, fname=LFP_reconst,
                                            transient=transient, Df=None, mlab=True,
                                            NFFT=256, noverlap=128,
                                            window=plt.mlab.window_hanning)

        zv = np.r_[params.electrodeParams['z']]
        zv = np.r_[zv, zv[-1] + np.diff(zv)[-1]]
        inds = freqs >= 1  # frequencies greater than 1 Hz  

        for j, ch in enumerate(channels):
        
            ax = fig.add_subplot(gsb[j, (i*4+3):(i*4+4)])
            if j == 0:
                phlp.annotate_subplot(ax, ncols=8./1, nrows=4.5*len(channels),
                                      letter=alphabet[i*3+4], linear_offset=0.02)
                ax.set_title('PSD')
                

            phlp.remove_axis_junk(ax)
            ax.loglog(freqs[inds], PSD_data[ch, inds], 'k', label='LFP', clip_on=True)
            ax.loglog(freqs[inds], PSD_LFP_reconst[ch, inds], 'r', label='predictor', clip_on=True)
            ax.set_xlim([4E0,4E2])
            ax.set_ylim([1E-8, 1E-4])
            ax.tick_params(axis='y', which='major', pad=0)
            ax.set_yticks([1E-8,1E-6,1E-4])
            ax.yaxis.set_minor_locator(plt.NullLocator())
            ax.text(0.8, 0.9, 'ch. %i' % (ch+1),
                    horizontalalignment='left',
                    verticalalignment='center',
                    fontsize=6, 
                    transform=ax.transAxes)
            
            if j == 0:
                ax.set_ylabel('(mV$^2$/Hz)', labelpad=0.)
            if j > 0:
                ax.set_yticklabels([])
            if j == len(channels)-1:
                ax.set_xlabel(r'$f$ (Hz)', labelpad=0.)
            else:
                ax.set_xticklabels([])



    return fig, PSD_LFP_reconst, PSD_data
Example #16
0
def fig_lfp_decomposition(fig,
                          axes,
                          params,
                          transient=200,
                          X=['L23E', 'L6E'],
                          show_xlabels=True):
    # ana_params.set_PLOS_2column_fig_style(ratio=0.5)
    # fig, axes = plt.subplots(1,5)
    # fig.subplots_adjust(left=0.06, right=0.96, wspace=0.4, hspace=0.2)

    if analysis_params.bw:
        # linestyles = ['-', '-', '--', '--', '-.', '-.', ':', ':']
        linestyles = ['-', '-', '-', '-', '-', '-', '-', '-']
        markerstyles = ['s', 's', 'v', 'v', 'o', 'o', '^', '^']
    else:
        if plt.matplotlib.__version__ == '1.5.x':
            linestyles = ['-', ':'] * (len(params.Y) / 2)
            print(
                'CSD variance semi log plots may fail with matplotlib.__version__ {}'
                .format(plt.matplotlib.__version__))
        else:
            linestyles = ['-',
                          (0, (1, 1))] * (len(params.Y) / 2)  #cercor version
        # markerstyles = ['s', 's', 'v', 'v', 'o', 'o', '^', '^']
        markerstyles = [None] * len(params.Y)
        linewidths = [1.25 for i in range(len(linestyles))]

    plt.delaxes(axes[0])

    #population plot
    axes[0] = fig.add_subplot(261)
    axes[0].xaxis.set_ticks([])
    axes[0].yaxis.set_ticks([])
    axes[0].set_frame_on(False)
    plot_population(axes[0],
                    params,
                    aspect='tight',
                    isometricangle=np.pi / 32,
                    plot_somas=False,
                    plot_morphos=True,
                    num_unitsE=1,
                    num_unitsI=1,
                    clip_dendrites=False,
                    main_pops=True,
                    rasterized=False)
    phlp.annotate_subplot(axes[0], ncols=5, nrows=1, letter='A')
    axes[0].set_aspect('auto')
    axes[0].set_ylim(-1550, 50)
    axis = axes[0].axis()

    phlp.remove_axis_junk(axes[1])
    plot_signal_sum(axes[1],
                    params,
                    fname=os.path.join(params.populations_path,
                                       X[0] + '_population_LFP.h5'),
                    unit='mV',
                    T=[800, 1000],
                    ylim=[axis[2], axis[3]],
                    rasterized=False)

    # CSD background colorplot
    im = plot_signal_sum_colorplot(
        axes[1],
        params,
        os.path.join(params.populations_path, X[0] + '_population_CSD.h5'),
        unit=r'$\mu$Amm$^{-3}$',
        T=[800, 1000],
        colorbar=False,
        ylim=[axis[2], axis[3]],
        fancy=False,
        cmap=plt.get_cmap('gray', 21) if analysis_params.bw else plt.get_cmap(
            'bwr_r', 21),
        rasterized=False)

    cb = phlp.colorbar(fig,
                       axes[1],
                       im,
                       width=0.05,
                       height=0.5,
                       hoffset=-0.05,
                       voffset=0.5)
    cb.set_label('($\mu$Amm$^{-3}$)', labelpad=0.)

    axes[1].set_ylim(-1550, 50)
    axes[1].set_title('LFP and CSD ({})'.format(X[0]), va='baseline')
    phlp.annotate_subplot(axes[1], ncols=3, nrows=1, letter='B')

    #quickfix on first axes
    axes[0].set_ylim(-1550, 50)
    if show_xlabels:
        axes[1].set_xlabel(r'$t$ (ms)', labelpad=0.)
    else:
        axes[1].set_xlabel('')

    phlp.remove_axis_junk(axes[2])
    plot_signal_sum(axes[2],
                    params,
                    fname=os.path.join(params.populations_path,
                                       X[1] + '_population_LFP.h5'),
                    ylabels=False,
                    unit='mV',
                    T=[800, 1000],
                    ylim=[axis[2], axis[3]],
                    rasterized=False)

    # CSD background colorplot
    im = plot_signal_sum_colorplot(
        axes[2],
        params,
        os.path.join(params.populations_path, X[1] + '_population_CSD.h5'),
        unit=r'$\mu$Amm$^{-3}$',
        T=[800, 1000],
        ylabels=False,
        colorbar=False,
        ylim=[axis[2], axis[3]],
        fancy=False,
        cmap=plt.get_cmap('gray', 21) if analysis_params.bw else plt.get_cmap(
            'bwr_r', 21),
        rasterized=False)

    cb = phlp.colorbar(fig,
                       axes[2],
                       im,
                       width=0.05,
                       height=0.5,
                       hoffset=-0.05,
                       voffset=0.5)
    cb.set_label('($\mu$Amm$^{-3}$)', labelpad=0.)

    axes[2].set_ylim(-1550, 50)
    axes[2].set_title('LFP and CSD ({})'.format(X[1]), va='baseline')
    phlp.annotate_subplot(axes[2], ncols=1, nrows=1, letter='C')
    if show_xlabels:
        axes[2].set_xlabel(r'$t$ (ms)', labelpad=0.)
    else:
        axes[2].set_xlabel('')

    plotPowers(axes[3],
               params,
               params.Y,
               'CSD',
               linestyles=linestyles,
               transient=transient,
               markerstyles=markerstyles,
               linewidths=linewidths)
    axes[3].axis(axes[3].axis('tight'))
    axes[3].set_ylim(-1550, 50)
    axes[3].set_yticks(-np.arange(16) * 100)
    if show_xlabels:
        axes[3].set_xlabel(r'$\sigma^2$ ($(\mu$Amm$^{-3})^2$)', va='center')
    axes[3].set_title('CSD variance', va='baseline')
    axes[3].set_xlim(left=1E-7)
    phlp.remove_axis_junk(axes[3])
    phlp.annotate_subplot(axes[3], ncols=1, nrows=1, letter='D')

    plotPowers(axes[4],
               params,
               params.Y,
               'LFP',
               linestyles=linestyles,
               transient=transient,
               markerstyles=markerstyles,
               linewidths=linewidths)
    axes[4].axis(axes[4].axis('tight'))
    axes[4].set_ylim(-1550, 50)
    axes[4].set_yticks(-np.arange(16) * 100)
    if show_xlabels:
        axes[4].set_xlabel(r'$\sigma^2$ (mV$^2$)', va='center')
    axes[4].set_title('LFP variance', va='baseline')
    axes[4].legend(bbox_to_anchor=(1.37, 1.0), frameon=False)
    axes[4].set_xlim(left=1E-7)
    phlp.remove_axis_junk(axes[4])
    phlp.annotate_subplot(axes[4], ncols=1, nrows=1, letter='E')

    return fig
Example #17
0
def fig_intro(params, ana_params, T=[800, 1000], fraction=0.05, rasterized=False):
    '''set up plot for introduction'''
    ana_params.set_PLOS_2column_fig_style(ratio=0.5)
    
    #load spike as database
    networkSim = CachedNetwork(**params.networkSimParams)
    if analysis_params.bw:
        networkSim.colors = phlp.get_colors(len(networkSim.X))

    #set up figure and subplots
    fig = plt.figure()
    gs = gridspec.GridSpec(3, 4)
    
    
    fig.subplots_adjust(left=0.05, right=0.95, wspace=0.5, hspace=0.)


    #network diagram
    ax0_1 = fig.add_subplot(gs[:, 0], frameon=False)
    ax0_1.set_title('point-neuron network', va='bottom')

    network_sketch(ax0_1, yscaling=1.3)
    ax0_1.xaxis.set_ticks([])
    ax0_1.yaxis.set_ticks([])
    phlp.annotate_subplot(ax0_1, ncols=4, nrows=1, letter='A', linear_offset=0.065)
   
    
    #network raster
    ax1 = fig.add_subplot(gs[:, 1], frameon=True)
    phlp.remove_axis_junk(ax1)
    phlp.annotate_subplot(ax1, ncols=4, nrows=1, letter='B', linear_offset=0.065)
       
    x, y = networkSim.get_xy(T, fraction=fraction)
    # networkSim.plot_raster(ax1, T, x, y, markersize=0.1, alpha=1.,legend=False, pop_names=True)
    networkSim.plot_raster(ax1, T, x, y, markersize=0.2, marker='_', alpha=1.,legend=False, pop_names=True, rasterized=rasterized)
    ax1.set_ylabel('')
    ax1.xaxis.set_major_locator(plt.MaxNLocator(4))
    ax1.set_title('spiking activity', va='bottom')
    a = ax1.axis()
    ax1.vlines(x['TC'][0], a[2], a[3], 'k', lw=0.25)


    #population
    ax2 = fig.add_subplot(gs[:, 2], frameon=False)
    ax2.xaxis.set_ticks([])
    ax2.yaxis.set_ticks([])
    plot_population(ax2, params, isometricangle=np.pi/24, plot_somas=False,
                    plot_morphos=True, num_unitsE=1, num_unitsI=1,
                    clip_dendrites=True, main_pops=True, title='',
                    rasterized=rasterized)
    ax2.set_title('multicompartment\nneurons', va='bottom', fontweight='normal')
    phlp.annotate_subplot(ax2, ncols=4, nrows=1, letter='C', linear_offset=0.065)
    

    #LFP traces in all channels
    ax3 = fig.add_subplot(gs[:, 3], frameon=True)
    phlp.remove_axis_junk(ax3)
    plot_signal_sum(ax3, params, fname=os.path.join(params.savefolder, 'LFPsum.h5'),
                unit='mV', vlimround=0.8,
                T=T, ylim=[ax2.axis()[2], ax2.axis()[3]],
                rasterized=False)
    ax3.set_title('LFP', va='bottom')
    ax3.xaxis.set_major_locator(plt.MaxNLocator(4))
    phlp.annotate_subplot(ax3, ncols=4, nrows=1, letter='D', linear_offset=0.065)
    a = ax3.axis()
    ax3.vlines(x['TC'][0], a[2], a[3], 'k', lw=0.25)
    
    
    #draw some arrows:
    ax = plt.gca()
    ax.annotate("", xy=(0.27, 0.5), xytext=(.24, 0.5),
                xycoords="figure fraction",
            arrowprops=dict(facecolor='black', arrowstyle='simple'),
            )
    ax.annotate("", xy=(0.52, 0.5), xytext=(.49, 0.5),
                xycoords="figure fraction",
            arrowprops=dict(facecolor='black', arrowstyle='simple'),
            )
    ax.annotate("", xy=(0.78, 0.5), xytext=(.75, 0.5),
                xycoords="figure fraction",
            arrowprops=dict(facecolor='black', arrowstyle='simple'),
            )

    
    return fig