Example #1
0
    def plot(self, *args, **kwargs):
        iter_list = self.config['iter_list']
        ps = self.env.ps
        frac_total_text = self.config['p_bumps']['frac_total_text']

        fig = self._get_final_fig(
            (2.2, self.config['sweeps']['fig_size'][1]*.85)
        )
        ax = fig.add_subplot(111)
        globalAxesSettings(ax)
        data = aggr.IsBumpCollapsed(ps.bumpGamma, iter_list, ignoreNaNs=True)
        fractions, X, Y = data.getData()
        ax.hist(fractions, normed=True, rwidth=0.8, linewidth=0, bins=self.histBins)
        ax.set_xlabel(frac_total_text)
        ax.set_ylabel('p[%s]' % frac_total_text)
        ax.margins(0.02, None)
        #ax.yaxis.tick_right()
        #ax.yaxis.set_label_position('right')
        ax.xaxis.set_major_locator(ti.MultipleLocator(.5))
        ax.xaxis.set_minor_locator(ti.MultipleLocator(.1))
        ax.yaxis.set_major_locator(ti.MultipleLocator(4))
        ax.yaxis.set_minor_locator(ti.MultipleLocator(2))
        f = ti.ScalarFormatter()
        f.set_powerlimits((0, 4))
        f.set_scientific(True)
        ax.xaxis.set_major_formatter(f)
        ax.spines['right'].set_visible(False)
        ax.spines['top'].set_visible(False)
        #ax.yaxis.set_tick_params(which='both', direction='in')
        ax.set_ylim(prepareLims((0, 12), 0.01))
        fig.tight_layout()
        fname = self.config['output_dir'] + "/bumps_isBumpFracTotal_hist.pdf"
        fig.savefig(fname, dpi=300, transparent=True)
        plt.close()
Example #2
0
    def plotWeights(self, ax, d, exc_profile, inh_profile, inh_const,
                    linewidth, x_range):
        x0, x1, _ = x_range

        plt.hold('on')
        ax = plt.gca()
        globalAxesSettings(ax)

        ax.spines['top'].set_visible(False)
        ax.spines['right'].set_visible(False)
        ep, = plt.plot(d, exc_profile, linewidth=linewidth, color='red', label="E")
        ip, = plt.plot(d, inh_profile, linewidth=linewidth, color='blue', label="I")

        ax.set_xlabel(self.myc.get('xlabel', "'Distance'"))
        ax.set_ylabel('G (nS)')
        ax.yaxis.set_ticks([0, 1])
        ax.yaxis.set_ticklabels([0, '$g_{E/I}$'])

        leg1 = ['E$\\rightarrow$I', 'I$\\rightarrow$E']
        l1 = ax.legend([ep, ip], leg1, **self.myc['leg1_kwargs'])
        plt.setp(l1.get_title(), fontsize='x-small')

        # If we want the uniform random, draw it
        if self.myc.get('uniform_random', True):
            leg2 = ['I$\\rightarrow$E uniform\nrandom']
            icp, = plt.plot(d, [inh_const]*len(d), ':', color='blue')
            l2 = ax.legend([icp], leg2, **self.myc['leg2_kwargs'])
            plt.setp(l2.get_title(), fontsize='x-small')
            ax.add_artist(l1)

        ax.margins(0.02)
Example #3
0
def plotThresholdHist(var1, threshold1, var2, **kw):
    ax = kw.pop("ax", plt.gca())
    xlabel = kw.pop("xlabel", "")
    ylabel = kw.pop("ylabel", "p($\cdot$)")
    sigmaTitle = kw.pop("sigmaTitle", False)
    noise_sigma = kw.pop("noise_sigma", None)

    grp1Idx = var1 < threshold1
    grp2Idx = np.logical_not(grp1Idx)

    globalAxesSettings(ax)
    ax.hold("on")
    # import pdb; pdb.set_trace()
    grp1 = var2[grp1Idx]
    grp2 = var2[grp2Idx]
    h1 = ax.hist(grp1, **kw)
    h2 = ax.hist(grp2, **kw)

    print("mean(grp1): {0}".format(np.mean(grp1)))
    print("mean(grp2): {0}".format(np.mean(grp2)))

    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)

    if sigmaTitle and noise_sigma is not None:
        ax.set_title("$\sigma$ = {0} pA".format(int(noise_sigma)))

    return h1, h2
Example #4
0
def plotThresholdHist(var1, threshold1, var2, **kw):
    ax = kw.pop('ax', plt.gca())
    xlabel = kw.pop('xlabel', '')
    ylabel = kw.pop('ylabel', 'p($\cdot$)')
    sigmaTitle = kw.pop('sigmaTitle', False)
    noise_sigma = kw.pop('noise_sigma', None)

    grp1Idx = var1 < threshold1
    grp2Idx = np.logical_not(grp1Idx)

    globalAxesSettings(ax)
    ax.hold('on')
    #import pdb; pdb.set_trace()
    grp1 = var2[grp1Idx]
    grp2 = var2[grp2Idx]
    h1 = ax.hist(grp1, **kw)
    h2 = ax.hist(grp2, **kw)

    print("mean(grp1): {0}".format(np.mean(grp1)))
    print("mean(grp2): {0}".format(np.mean(grp2)))

    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)

    if sigmaTitle and noise_sigma is not None:
        ax.set_title('$\sigma$ = {0} pA'.format(int(noise_sigma)))

    return h1, h2
Example #5
0
def plotCollapsedSweeps(noise_sigmas, data, **kw):
    '''Parameter sweeps collapsed into noise-dependent lines.'''
    ax          = kw.pop('ax', plt.gca())
    xlabel      = kw.pop('xlabel', "$\sigma_{noise}$")
    ylabel      = kw.pop('ylabel', '')
    xticks      = kw.pop('xticks', True)
    yticks      = kw.pop('yticks', True)
    #kw['color'] = kw.get('color', 'black')

    if (len(noise_sigmas) != len(data)):
        raise ValueError("len(noise_sigmas) != len(data)")

    stackedData = aggr.collapseSweeps(data)

    globalAxesSettings(ax)
    ax.plot(noise_sigmas, stackedData, "o-", **kw)

    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.margins(0.03, 0.03)
    ax.set_xticks(noise_sigmas)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    if (not xticks):
        ax.xaxis.set_ticklabels([])
    if (not yticks):
        ax.yaxis.set_ticklabels([])

    return ax
Example #6
0
    def plotDistribution(self, X, Y, ax, noise_sigma=None, **kw):
        xlabel = kw.get('xlabel', 'P(bump)')
        ylabel = kw.get('ylabel', '$Power_\gamma$')
        yticks = kw.get('yticks', True)
        bins   = kw.get('bins', [40, 50])
        range  = kw.get('range', [[0, 1], [-.2, .8]])
        title_size = kw.get('title_size', 'medium')

        H, xedges, yedges = np.histogram2d(
                X.flatten(),
                Y.flatten(),
                bins=bins,
                range=range,
                normed=True)

        globalAxesSettings(ax)
        ax.pcolormesh(xedges, yedges, H.T, vmin=0, rasterized=True)
        ax.set_xlabel(xlabel)
        ax.set_ylabel(ylabel)
        if noise_sigma is not None:
            ax.set_title("%d pA" % int(noise_sigma), size=title_size)
        else:
            ax.set_title("All", size=title_size)
        if not yticks:
            ax.yaxis.set_ticklabels([])
Example #7
0
def plotOneHist(data, bins=40, normed=False, **kw):
    ax = kw.pop('ax', plt.gca())
    globalAxesSettings(ax)
    ax.hist(data, bins=bins, normed=normed, histtype='step', align='mid', **kw)
    ax.minorticks_on()
    ax.xaxis.set_minor_locator(AutoMinorLocator(3))
    ax.yaxis.set_minor_locator(AutoMinorLocator(3))
    ax.xaxis.set_major_locator(MaxNLocator(4))
    ax.yaxis.set_major_locator(MaxNLocator(4))
Example #8
0
def plotGammaExample(ps, r, c, trialNum, tStart, tEnd, **kw):
    '''Plot examples of gamma activity.'''
    ax             = kw.pop('ax', plt.gca())
    noise_sigma    = kw.pop('noise_sigma', None)
    noise_sigma_xy = kw.pop('noise_sigma_xy', (0.95, 0.85))
    xscale_kw      = kw.pop('xscale_kw', None)
    yscale_kw      = kw.pop('yscale_kw', None)
    monIdx_e       = kw.pop('monIdx_e', 1)
    monIdx_i       = kw.pop('monIdx_i', 0)

    globalAxesSettings(ax)
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.spines['left'].set_visible(False)
    ax.spines['bottom'].set_visible(False)

    data = ps[r][c][trialNum].data
    monEList = data['stateMon_e']
    t, Isyn_e = extractSummedSignals(monEList, ['I_clamp_GABA_A'], tStart,
                                     tEnd, monIdx=monIdx_e)
    monIList = data['stateMon_i']
    t, Isyn_i = extractSummedSignals(monIList,
                                     ['I_clamp_AMPA', 'I_clamp_NMDA'],
                                     tStart, tEnd,
                                     monIdx=monIdx_i)
    Isyn_e *= 1e-3
    Isyn_i *= 1e-3
    plt.plot(t, Isyn_e, color='red')
    plt.plot(t, Isyn_i, color='blue')
    max = np.max(Isyn_e)
    min = np.min(Isyn_i)
    absmax = np.max([np.abs(max), np.abs(min)])

    ax.set_xlim([tStart, tEnd])
    ax.xaxis.set_ticks_position('none')
    ax.yaxis.set_ticks_position('none')
    ax.set_xticks([])
    ax.set_yticks([])
    ax.set_ylim([-absmax, absmax])

    if (noise_sigma is not None):
        txt = '$\sigma$ = {0} pA'.format(noise_sigma)
        ns_x, ns_y = noise_sigma_xy[0], noise_sigma_xy[1]
        ax.text(ns_x, ns_y, txt, transform=ax.transAxes, va='bottom', ha='right',
                size='x-small')

    # Scale bars
    if xscale_kw is not None:
        xscale_kw = dict(xscale_kw)
        xscale_kw.update(ax=ax)
        xScaleBar(**xscale_kw)

    if yscale_kw is not None:
        yscale_kw = dict(yscale_kw)
        yscale_kw.update(ax=ax)
        yScaleBar(**yscale_kw)
Example #9
0
 def plotColorbar(self, ax):
     globalAxesSettings(ax)
     collection = ax.pcolor(self.CX + self.CY*self.xSize, cmap=self.cmap,
             rasterized=True)
     ax.xaxis.set_ticks([])
     ax.yaxis.set_ticks([])
     ax.set_xlabel(xlabelTextShort, size='small')
     ax.set_ylabel(ylabelTextShort, size='small')
     ax.axis('scaled')
     return collection
Example #10
0
def plot2DTrial(X, Y, C, ax=plt.gca(), xlabel=None, ylabel=None,
                colorBar=False, clBarLabel="", vmin=None, vmax=None, title="",
                clbarNTicks=2, xticks=True, yticks=True, cmap=None, cbar_kw={},
                sliceAnn=None, axis_setting='scaled', **kw):
    '''A low level function to plot a 2D trial-average data into a plot.'''
    kw['rasterized'] = kw.get('rasterized', True)
    cbar_kw['label']       = cbar_kw.get('label', '')
    cbar_kw['shrink']      = cbar_kw.get('shrink', 0.8)
    cbar_kw['pad']         = cbar_kw.get('pad', 0.05)
    cbar_kw['ticks']       = cbar_kw.get('ticks', ti.MultipleLocator(5))
    cbar_kw['rasterized']  = cbar_kw.get('rasterized', True)

    if xlabel is None:
        xlabel = xlabelText
    if ylabel is None:
        ylabel = ylabelText

    dx = X[0, 1] - X[0, 0]
    dy = Y[1, 0] - Y[0, 1]

    globalAxesSettings(ax)
    ax.minorticks_on()
    mappable = ax.imshow(C, vmin=vmin, vmax=vmax, cmap=cmap,
                         extent=(X[0, 0] - dx / 2., X[0, -1] + dx / 2.,
                                 Y[0, 0] - dy / 2., Y[-1, 0] + dy / 2.),
                         interpolation='none',
                         origin='lower',
                         **kw)
    cax = createColorbar(ax, mappable=mappable, **cbar_kw)
    if colorBar == False:
        cax.set_visible(False)
    if xlabel != "":
        ax.set_xlabel(xlabel, va='top')
        ax.xaxis.set_label_coords(0.5, -0.125)
    if ylabel != "":
        ax.set_ylabel(ylabel, ha='center')
        ax.yaxis.set_label_coords(-0.125, 0.5)
    ax.xaxis.set_ticks([X[0, 0], X[0, -1]])
    ax.yaxis.set_ticks([Y[0, 0], Y[-1, 0]])
    ax.xaxis.set_minor_locator(ti.AutoMinorLocator(6))
    ax.yaxis.set_minor_locator(ti.AutoMinorLocator(6))
    ax.axis(axis_setting)
    if not xticks:
        ax.xaxis.set_ticklabels([])
    if not yticks:
        ax.yaxis.set_ticklabels([])

    # slice annotations
    if sliceAnn is not None:
        for args in sliceAnn:
            args.update(ax=ax, X=X, Y=Y)
            plotSliceAnnotation(**args)


    return C, ax, cax
Example #11
0
 def plotColorbar(self, ax):
     globalAxesSettings(ax)
     collection = ax.pcolor(self.CX + self.CY * self.xSize,
                            cmap=self.cmap,
                            rasterized=True)
     ax.xaxis.set_ticks([])
     ax.yaxis.set_ticks([])
     ax.set_xlabel(xlabelTextShort, size='small')
     ax.set_ylabel(ylabelTextShort, size='small')
     ax.axis('scaled')
     return collection
Example #12
0
def setSignalAxes(ax, leftSpineOn):
    globalAxesSettings(ax)
    ax.minorticks_on()
    ax.xaxis.set_visible(False)
    ax.spines['top'].set_visible(False)
    ax.spines['bottom'].set_visible(False)
    ax.spines['right'].set_visible(False)
    if (leftSpineOn == False):
        ax.spines['left'].set_visible(False)
        ax.yaxis.set_visible(False)

    ax.yaxis.set_major_locator(MaxNLocator(2))
    ax.yaxis.set_minor_locator(AutoMinorLocator(2))
Example #13
0
def plotOneCorrAngleExample(dataSpace, rc, trialNum=0, **kw):
    populationType = kw.pop('populationType', 'E')
    ax = kw.pop('ax', plt.gca())

    r, c = rc[0], rc[1]
    print("Corr. angle. example; (r, c): ", r, c)

    globalAxesSettings(ax)
    correlations, angles = _getCorrAngleData(dataSpace, populationType)
    ax.plot(angles[r][c][trialNum], correlations[r][c][trialNum])
    ax.set_xlabel('Rotation angle (degrees)')
    ax.set_ylabel('Correlation')
    ax.xaxis.set_major_locator(ti.MultipleLocator(30))
    ax.xaxis.set_major_locator(ti.MultipleLocator(30))
Example #14
0
def plotDiffScatter(data, noise_sigmas, **kw):
    '''
    2D scatter plot of differences between (150-0)pA and (300-150)pA.

    **Parameters:**

    data : a list of 2D matrices
        2D parameter sweep for all noise_sigma levels.
    noise_sigmas : sequence of floats
        Noise sigma values, must be of the same length as data
    doSegmentation : bool, optional
        Whether to do segmentation or not
    '''
    ax              = kw.pop('ax', plt.gca())
    xlabel          = kw.pop('xlabel', '')
    ylabel          = kw.pop('ylabel', '')
    zerolines       = kw.pop('zerolines', True)
    doSegmentation  = kw.pop('doSegmentation', False)
    thresholds      = kw.pop('thresholds', None)
    mergeInfo       = kw.pop('mergeInfo', None)
    filterThreshold = kw.pop('filterThreshold', -np.infty)
    kw['edgecolor'] = kw.get('edgecolor', 'white')

    if (len(noise_sigmas) != len(data)):
        raise ValueError("len(noise_sigmas) != len(data)")

    stackedData = aggr.collapseSweeps(data)
    stackedData, _ = filterData(stackedData, filterThreshold)
    diffData = np.diff(stackedData, axis=0)

    if doSegmentation:
        differences = [
                diffData[0, :],
                diffData[1, :]]
        clusters = clustering.ThresholdClusters(differences, thresholds)
        if mergeInfo is not None:
            clusters = clusters.mergeClusters(mergeInfo)
        kw['c'] = clusters.assignClusters()

    globalAxesSettings(ax)
    ax.scatter(diffData[0, :], diffData[1, :], **kw)

    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    ax.axis('scaled')

    if (zerolines):
        zeroLines(ax)

    return ax
Example #15
0
def plot_1d_sweep(data, ax, xlabel, ylabel, xticks=True, yticks=True,
                  axis_setting='scaled', title='', **kwargs):
    '''Plot a 1D parameter Sweep.

    Parameters
    ----------
    data : AggregateData
        Data to plot. The first (Y/rows) dimension will be ignored.
    ax : mpl.Axes
        Matplotlib axes.
    xlabel, ylabel : str
        X/Y label strings
    xticks, yticks : bool
        Whether to plot ticks and number on the X/Y axes.
    kwargs : dict
        Keyword arguments that will be passed on to the plot function.
    '''
    plot_data, X, _ = data.getTrialData()
    X = X.flatten()

    logger_1d.info('min(data): %f', np.min(plot_data.flatten()))
    logger_1d.info('max(data): %f', np.max(plot_data.flatten()))

    globalAxesSettings(ax)
    ax.minorticks_on()

    if xlabel != "":
        ax.set_xlabel(xlabel, va='top')
        ax.xaxis.set_label_coords(0.5, -0.125)
    if ylabel != "":
        ax.set_ylabel(ylabel, ha='center')
        ax.yaxis.set_label_coords(-0.125, 0.5)

    ax.plot(X.flatten(), plot_data[0, :, :], 'o', color='g', markersize=5,
            markeredgecolor='white', **kwargs)
    if xlabel != "":
        ax.set_xlabel(xlabel, va='top')
        ax.xaxis.set_label_coords(0.5, -0.125)
    if ylabel != "":
        ax.set_ylabel(ylabel, ha='center')
        ax.yaxis.set_label_coords(-0.157, 0.5)
    ax.xaxis.set_ticks([X[0], X[-1]])
    ax.xaxis.set_minor_locator(ti.AutoMinorLocator(6))
    ax.yaxis.set_minor_locator(ti.AutoMinorLocator(6))
    ax.axis(axis_setting)
    if not xticks:
        ax.xaxis.set_ticklabels([])
    if not yticks:
        ax.yaxis.set_ticklabels([])
Example #16
0
def createColorbar(ax, **kwargs):
    cbLabel = kwargs.pop('label', '')
    #orientation = kwargs.get('orientation', 'horizontal')
    rasterized = kwargs.pop('rasterized', None)
    labelpad = kwargs.pop('labelpad', None)
    mappable = kwargs.pop('mappable', None)

    cax, kwargs = make_axes(ax, **kwargs)
    globalAxesSettings(cax)
    fig = ax.figure
    cb = fig.colorbar(mappable, ax=ax, cax=cax, **kwargs)
    cb.set_label(cbLabel, labelpad=labelpad)
    cb.solids.set_rasterized(rasterized)

    return cax
Example #17
0
def plotOneCorrAngleExample(dataSpace, rc, trialNum=0, **kw):
    '''A plot of one example of correlation coefficients of rotated
    autocorrelations.
    '''
    populationType = kw.pop('populationType', 'E')
    ax = kw.pop('ax', plt.gca())

    r, c = rc[0], rc[1]
    print("Corr. angle. example; (r, c): ", r, c)

    globalAxesSettings(ax)
    correlations, angles = _getCorrAngleData(dataSpace, populationType)
    ax.plot(angles[r][c][trialNum], correlations[r][c][trialNum])
    ax.set_xlabel('Rotation angle (degrees)')
    ax.set_ylabel('Correlation')
    ax.xaxis.set_major_locator(ti.MultipleLocator(30))
    ax.xaxis.set_major_locator(ti.MultipleLocator(30))
Example #18
0
def plotDetailedNoise(sp, NTrials, types, **kw):
    xlabel                = kw.pop('xlabel', '$\sigma_{noise}$ (pA)')
    ylabel                = kw.pop('ylabel', '')
    ylabelPos             = kw.pop('ylabelPos', -0.4)
    xticks                = kw.pop('xticks', True)
    yticks                = kw.pop('yticks', True)
    ax                    = kw.pop('ax', plt.gca())
    markersize            = kw.pop('markersize', 4)
    kw['markerfacecolor'] = kw.get('markerfacecolor', 'none')
    color                 = kw.pop('color', 'blue')
    ignoreNaNs            = kw.pop('ignoreNaNs', True)

    iterList = ['noise_sigma', 'g_AMPA_total']

    ax.hold('on')
    if isinstance(sp, aggr.AggregateData):
        data, X, Y = sp.getData()
    else:
        data, X, Y = aggr.aggregateType(sp, iterList, types, NTrials, **kw)
    if (ignoreNaNs):
        nans = np.isnan(data)
        data = ma.MaskedArray(data, mask=nans)
    print("    max(data): {0}".format(np.max(data)))
    print("    min(data): {0}".format(np.min(data)))
    noise_sigma = Y[:, 0]
    mean = np.mean(data, axis=1)

    globalAxesSettings(ax)
    noise_sigma_all = np.repeat(np.reshape(noise_sigma, (1, len(noise_sigma))),
            data.shape[1], axis=0).T
    p1, = ax.plot(noise_sigma_all.ravel(), data.ravel(), 'o', markeredgecolor=color,
            markersize=markersize, **kw)
    l1, = ax.plot(noise_sigma, mean, '-', color=color, markersize=markersize, **kw)
    ax.set_xlabel(xlabel)
    ax.text(ylabelPos, 0.5, ylabel, va='center', ha='center',
            transform=ax.transAxes, rotation=90)

    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    if (not yticks):
        ax.yaxis.set_ticklabels([])
    if (not xticks):
        ax.xaxis.set_ticklabels([])
    ax.margins(0.03, 0.03)

    return ax, p1, l1
Example #19
0
def plotOneSlice(ax, x, y, **kw):
    xlabel = kw.pop('xlabel', '')
    ylabel = kw.pop('ylabel', '')
    ylabelPos = kw.pop('ylabelPos', -0.2)
    fmt = kw.pop('fmt', 'o-')
    xticks = kw.pop('xticks', True)
    yticks = kw.pop('yticks', True)
    errors = kw.pop('errors', True)
    kw['markersize'] = kw.get('markersize', 4)

    globalAxesSettings(ax)
    ndim = len(y.shape)
    if (ndim == 2):
        mean = np.mean(y, axis=1)  # axis 1: trials
        std = np.std(y, axis=1)
        if (errors):
            ax.errorbar(x, mean, std, fmt=fmt, **kw)
        else:
            ax.plot(x, mean, fmt, **kw)
    elif (ndim == 1):
        ax.plot(x, y, fmt, **kw)
    ax.set_xlabel(xlabel)
    ax.text(ylabelPos,
            0.5,
            ylabel,
            rotation=90,
            transform=ax.transAxes,
            va='center',
            ha='center')

    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.xaxis.set_major_locator(ti.MultipleLocator(1))
    ax.xaxis.set_minor_locator(ti.AutoMinorLocator(5))
    ax.yaxis.set_minor_locator(ti.AutoMinorLocator(3))
    w = x[-1] - x[0]
    margin = 0.025
    ax.set_xlim([-margin * w, x[-1] + margin * w])

    if (not xticks):
        ax.xaxis.set_ticklabels([])
    if (not yticks):
        ax.yaxis.set_ticklabels([])
Example #20
0
def plotDiffHistograms(data, noise_sigmas, **kw):
    '''
    **Parameters:**

    data : a list of 2D matrices
        2D parameter sweep for all noise_sigma levels.
    noise_sigmas : sequence of floats
        Noise sigma values, must be of the same length as data
    '''
    ax              = kw.pop('ax', plt.gca())
    which           = kw.pop('which', None)
    xlabel          = kw.pop('xlabel', '')
    ylabel          = kw.pop('ylabel', 'p($\cdot$)')
    filterThreshold = kw.pop('filterThreshold', -np.infty)
    kw['linewidth'] = kw.get('linewidth', 0.01)
    kw['edgecolor'] = kw.get('edgecolor', 'white')
    kw['rwidth']    = kw.get('rwidth', 0.8)

    if (len(noise_sigmas) != len(data)):
        raise ValueError("len(noise_sigmas) != len(data)")

    #import pdb; pdb.set_trace()
    stackedData = aggr.collapseSweeps(data)
    stackedData, _ = filterData(stackedData, filterThreshold)
    diffData = np.diff(stackedData, axis=0)

    if which is None:
        whichIdx = xrange(len(noise_sigmas) - 1)
    else:
        whichIdx = [which]

    globalAxesSettings(ax)
    for idx in whichIdx:
        nan_idx = np.logical_not(np.isnan(diffData[idx, :]))
        ax.hist(diffData[idx, nan_idx], normed=True,
                alpha=1./len(noise_sigmas), **kw)

    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)

    return ax
Example #21
0
    def _plot(self, X, Y, **kw):
        ax          = kw.pop('ax', plt.gca())
        xlabel      = kw.pop('xlabel', '')
        ylabel      = kw.pop('ylabel', '')
        yticks      = kw.pop('yticks', True)
        sigmaTitle  = kw.pop('sigmaTitle', False)
        noise_sigma = kw.pop('noise_sigma', None)

        globalAxesSettings(ax)

        kw['edgecolor'] = 'white'
        if (self.colors is not None):
            kw['c'] = self.colors
        kw['cmap'] = self.cmap
        kw['picker'] = True
        if (self.colormap2D):
            kw['vmin'] = 0
            kw['vmax'] = self.xSize * self.ySize - 1

        collection = ax.scatter(X.flatten(), Y.flatten(), **kw)

        ax.set_xlabel(xlabel)
        ax.set_ylabel(ylabel)
        if not yticks:
            ax.yaxis.set_ticklabels([])

        ax.spines['top'].set_visible(False)
        ax.spines['right'].set_visible(False)
        ax.margins(0.05)
        ax.autoscale_view(tight=True)

        if sigmaTitle and noise_sigma is not None:
            ax.set_title('$\sigma$ = {0} pA'.format(int(noise_sigma)))

        # Picking - for interactive mode
        #ax.figure.canvas.mpl_connect('pick_event', self.onpick)

        self.ax = ax
        return ax
Example #22
0
    def plotWeights(self, ax, d, exc_profile, inh_profile, inh_const,
                    linewidth, x_range):
        x0, x1, _ = x_range

        plt.hold('on')
        ax = plt.gca()
        globalAxesSettings(ax)

        ax.spines['top'].set_visible(False)
        ax.spines['right'].set_visible(False)
        ep, = plt.plot(d,
                       exc_profile,
                       linewidth=linewidth,
                       color='red',
                       label="E")
        ip, = plt.plot(d,
                       inh_profile,
                       linewidth=linewidth,
                       color='blue',
                       label="I")

        ax.set_xlabel(self.myc.get('xlabel', "'Distance'"))
        ax.set_ylabel('G (nS)')
        ax.yaxis.set_ticks([0, 1])
        ax.yaxis.set_ticklabels([0, '$g_{E/I}$'])

        leg1 = ['E$\\rightarrow$I', 'I$\\rightarrow$E']
        l1 = ax.legend([ep, ip], leg1, **self.myc['leg1_kwargs'])
        plt.setp(l1.get_title(), fontsize='x-small')

        # If we want the uniform random, draw it
        if self.myc.get('uniform_random', True):
            leg2 = ['I$\\rightarrow$E uniform\nrandom']
            icp, = plt.plot(d, [inh_const] * len(d), ':', color='blue')
            l2 = ax.legend([icp], leg2, **self.myc['leg2_kwargs'])
            plt.setp(l2.get_title(), fontsize='x-small')
            ax.add_artist(l1)

        ax.margins(0.02)
Example #23
0
    def _plot(self, X, Y, **kw):
        ax = kw.pop('ax', plt.gca())
        xlabel = kw.pop('xlabel', '')
        ylabel = kw.pop('ylabel', '')
        yticks = kw.pop('yticks', True)
        sigmaTitle = kw.pop('sigmaTitle', False)
        noise_sigma = kw.pop('noise_sigma', None)

        globalAxesSettings(ax)

        kw['edgecolor'] = 'white'
        if (self.colors is not None):
            kw['c'] = self.colors
        kw['cmap'] = self.cmap
        kw['picker'] = True
        if (self.colormap2D):
            kw['vmin'] = 0
            kw['vmax'] = self.xSize * self.ySize - 1

        collection = ax.scatter(X.flatten(), Y.flatten(), **kw)

        ax.set_xlabel(xlabel)
        ax.set_ylabel(ylabel)
        if not yticks:
            ax.yaxis.set_ticklabels([])

        ax.spines['top'].set_visible(False)
        ax.spines['right'].set_visible(False)
        ax.margins(0.05)
        ax.autoscale_view(tight=True)

        if sigmaTitle and noise_sigma is not None:
            ax.set_title('$\sigma$ = {0} pA'.format(int(noise_sigma)))

        # Picking - for interactive mode
        #ax.figure.canvas.mpl_connect('pick_event', self.onpick)

        self.ax = ax
        return ax
Example #24
0
def plotOneSlice(ax, x, y, **kw):
    xlabel           = kw.pop('xlabel', '')
    ylabel           = kw.pop('ylabel', '')
    ylabelPos        = kw.pop('ylabelPos', -0.2)
    fmt              = kw.pop('fmt', 'o-')
    xticks           = kw.pop('xticks', True)
    yticks           = kw.pop('yticks', True)
    errors           = kw.pop('errors', True)
    kw['markersize'] = kw.get('markersize', 4)

    globalAxesSettings(ax)
    ndim = len(y.shape)
    if (ndim == 2):
        mean = np.mean(y, axis=1) # axis 1: trials
        std  = np.std(y, axis=1)
        if (errors):
            ax.errorbar(x, mean, std, fmt=fmt, **kw)
        else:
            ax.plot(x, mean, fmt, **kw)
    elif (ndim == 1):
        ax.plot(x, y, fmt, **kw)
    ax.set_xlabel(xlabel)
    ax.text(ylabelPos, 0.5, ylabel, rotation=90, transform=ax.transAxes,
            va='center', ha='center')

    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.xaxis.set_major_locator(ti.MultipleLocator(1))
    ax.xaxis.set_minor_locator(ti.AutoMinorLocator(5))
    ax.yaxis.set_minor_locator(ti.AutoMinorLocator(3))
    w = x[-1] - x[0]
    margin = 0.025
    ax.set_xlim([-margin*w, x[-1]+margin*w])

    if (not xticks):
        ax.xaxis.set_ticklabels([])
    if (not yticks):
        ax.yaxis.set_ticklabels([])
Example #25
0
    def plotDistribution(self, X, Y, ax, noise_sigma=None, **kw):
        xlabel = kw.get('xlabel', 'P(bump)')
        ylabel = kw.get('ylabel', '$Power_\gamma$')
        yticks = kw.get('yticks', True)
        bins = kw.get('bins', [40, 50])
        range = kw.get('range', [[0, 1], [-.2, .8]])
        title_size = kw.get('title_size', 'medium')

        H, xedges, yedges = np.histogram2d(X.flatten(),
                                           Y.flatten(),
                                           bins=bins,
                                           range=range,
                                           normed=True)

        globalAxesSettings(ax)
        ax.pcolormesh(xedges, yedges, H.T, vmin=0, rasterized=True)
        ax.set_xlabel(xlabel)
        ax.set_ylabel(ylabel)
        if noise_sigma is not None:
            ax.set_title("%d pA" % int(noise_sigma), size=title_size)
        else:
            ax.set_title("All", size=title_size)
        if not yticks:
            ax.yaxis.set_ticklabels([])
Example #26
0
    def plotSlopes(self, ax, dataSpace, pos, noise_sigma, iterList, **kw):
        # kwargs
        trialNum   = kw.pop('trialNum', 0)
        markersize = kw.pop('markersize', 4)
        color      = kw.pop('color', 'blue')
        lineColor  = kw.pop('lineColor', 'black')
        xlabel     = kw.pop('xlabel', 'Velocity current (pA)')
        ylabel     = kw.pop('ylabel', 'Bump speed\n(neurons/s)')
        xticks     = kw.pop('xticks', True)
        yticks     = kw.pop('yticks', True)
        g_ann      = kw.pop('g_ann', True)
        sigma_ann  = kw.pop('sigma_ann', True)
        ivel_range = kw.pop('ivel_range', None)
        kw['markeredgecolor'] = color

        r = pos[0]
        c = pos[1]
        d = dataSpace[r][c].getAllTrialsAsDataSet().data
        a = d['analysis']
        IvelVec = dataSpace[r][c][trialNum].data['IvelVec']
        if ivel_range is None:
            ivel_range = len(IvelVec)
        else:
            ivel_range = min(ivel_range, len(IvelVec))
        slopes = a['bumpVelAll']
        lineFit = a['lineFitLine']
        fitIvelVec = a['fitIvelVec']

        nTrials = slopes.shape[0]
        avgSlope = np.mean(slopes, axis=0)
        stdSlope = np.std(slopes, axis=0)

        if (ax is None):
            ax = plt.gca()
        plt.hold('on')
        globalAxesSettings(ax)

        ax.plot(IvelVec[0:ivel_range], slopes[:, 0:ivel_range].T, 'o',
                markerfacecolor='none', markersize=markersize, **kw)
        #ax.errorbar(IvelVec, avgSlope, stdSlope, fmt='o-',
        #        markersize=markersize, color=color, alpha=0.5, **kw)
        ax.plot(fitIvelVec, lineFit, '-', linewidth=1, color=lineColor, **kw)

        ax.set_xlabel(xlabel)
        ax.set_ylabel(ylabel)
        ax.spines['top'].set_visible(False)
        ax.spines['right'].set_visible(False)
        ax.xaxis.set_major_locator(ti.MultipleLocator(50))
        ax.xaxis.set_minor_locator(ti.MultipleLocator(10))
        ax.yaxis.set_major_locator(ti.MultipleLocator(25))
        #ax.yaxis.set_minor_locator(ti.MultipleLocator(10))
        ax.margins(0.05)

        if (not xticks):
            ax.xaxis.set_ticklabels([])
        if (not yticks):
            ax.yaxis.set_ticklabels([])

        # Annotations
        if (sigma_ann):
            sigma_txt = '$\sigma$ = {0} pA'.format(noise_sigma)
            ax.set_title(sigma_txt, y=1.3, va='bottom')

        if (g_ann):
            Y, X = aggr.computeVelYX(dataSpace, iterList, r, c)
            gE = Y[r, c]
            gI = X[r, c]
            g_txt = '$g_E$ = {0}\n$g_I$ = {1} nS'.format(gE, gI)
        else:
            g_txt = ''

        txt = '{0}'.format(g_txt)
        ax.text(0.05, 1.3, txt, transform=ax.transAxes, va='top',
                ha='left', size='x-small')
Example #27
0
def plotEIRaster(ESpikes, ISpikes, tLimits, ylabel=None, **kw):
    '''Plot a raster plot E and I spikes.'''
    # kw arguments
    ax           = kw.pop('ax', plt.gca())
    yticks       = kw.pop('yticks', True)
    yticks_style = kw.pop('yticks_style', 'separate')
    ylabelPos    = kw.pop('ylabelPos', -0.22)
    EColor       = kw.pop('ecolor', 'red')
    IColor       = kw.pop('icolor', 'blue')
    title        = kw.pop('title', True)
    ann          = kw.pop('ann', False)
    ann_EI       = kw.pop('ann_EI', False)
    sigmaTitle   = kw.pop('sigmaTitle', True)
    noise_sigma  = kw.pop('noise_sigma', None)
    scaleBar     = kw.pop('scaleBar', None)
    scaleX       = kw.pop('scaleX', 0.75)
    scaleY       = kw.pop('scaleY', 0.05)
    scaleText    = kw.pop('scaleText', 'ms')
    scaleTextYOffset = kw.pop('scaleTextYOffset', .075)
    scaleHeight  = kw.pop('scaleHeight', .02)
    scaleTextSize= kw.pop('scaleTextSize', 'small')
    reshape_senders = kw.pop('reshape_senders', True)
    kw['markersize'] = kw.get('markersize', 1.0)

    if ylabel is None:
        ylabel = 'Neuron #'

    ESpikes = ESpikes.windowed(tLimits)
    ISpikes = ISpikes.windowed(tLimits)

    ESenders, ETimes = ESpikes.rasterData()
    ISenders, ITimes = ISpikes.rasterData()

    if reshape_senders:
        # TO REMOVE: this is to transform the neuron number from row-wise to
        # column wise indexes. A better solution has to be devised in the
        # future
        logger.warn('Nx, Ny are fixed in the code. Make sure the torus size '
                    'is the same as specified here.')
        Nx, Ny = 34, 30
        N = Nx * Ny
        if (N != ESpikes.N or N != ISpikes.N):
            raise ValueError("Fix the number of neurons in plotEIRaster")
        Ex = ESenders % Nx
        Ey = ESenders // Ny
        ESenders = Ey + Ex * Ny
        Ix = ISenders % Nx
        Iy = ISenders // Ny
        ISenders = Iy + Ix * Ny

    ISenders += ESpikes.N

    globalAxesSettings(ax)
    ax.minorticks_on()
    ax.xaxis.set_visible(False)
    ax.spines['top'].set_visible(False)
    ax.spines['bottom'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.yaxis.set_major_locator(ti.LinearLocator(2))
    ax.yaxis.set_minor_locator(ti.NullLocator())

    ax.plot(ETimes, ESenders+1, '.', color='red',  mec='none', **kw)
    ax.plot(ITimes, ISenders+1, '.', color='blue', mec='none', **kw)

    ax.set_xlim(tLimits)
    ax.set_ylim([1, ESpikes.N+ISpikes.N])
    if (yticks_style == 'separate'):
        ax.set_yticks([1, ESpikes.N, ESpikes.N+ISpikes.N])
    ax.invert_yaxis()
    ax.text(ylabelPos, 0.5, ylabel, va='center', ha='center',
            transform=ax.transAxes, rotation=90)
    if (not yticks):
        ax.yaxis.set_ticklabels([])

    # Annotations
    if (sigmaTitle):
        ax.set_title('$\sigma$ = {0} pA'.format(int(noise_sigma)), y=1.02,
                va='bottom', ha='center')
    if (ann):
        Y, X = aggr.computeYX(space, iterList, r=r, c=c)
        gE = Y[r, c]
        gI = X[r, c]
        txt = '$g_E$ = {0} nS\n$g_I$ = {1} nS'.format(gE, gI)
        ax.text(0.99, 1.02, txt, va='bottom', ha='right', size='small',
                transform=ax.transAxes)

    if (ann_EI):
        ax.text(-0.05, 0.75, 'E', va='center', ha='center', size='small',
                transform=ax.transAxes, color='red', weight='bold')
        ax.text(-0.05, 0.25, 'I', va='center', ha='center', size='small',
                transform=ax.transAxes, color='blue', weight='bold')

    if (scaleBar is not None):
        xScaleBar(scaleBar, x=scaleX, y=scaleY, ax=ax, size=scaleTextSize,
                unitsText=scaleText, textYOffset=scaleTextYOffset,
                height=scaleHeight)


    return ax
Example #28
0
def plotEIRaster(ESpikes, ISpikes, tLimits, ylabel=None, **kw):
    '''Plot a raster plot E and I spikes.'''
    # kw arguments
    ax = kw.pop('ax', plt.gca())
    yticks = kw.pop('yticks', True)
    yticks_style = kw.pop('yticks_style', 'separate')
    ylabelPos = kw.pop('ylabelPos', -0.22)
    EColor = kw.pop('ecolor', 'red')
    IColor = kw.pop('icolor', 'blue')
    title = kw.pop('title', True)
    ann = kw.pop('ann', False)
    ann_EI = kw.pop('ann_EI', False)
    sigmaTitle = kw.pop('sigmaTitle', True)
    noise_sigma = kw.pop('noise_sigma', None)
    scaleBar = kw.pop('scaleBar', None)
    scaleX = kw.pop('scaleX', 0.75)
    scaleY = kw.pop('scaleY', 0.05)
    scaleText = kw.pop('scaleText', 'ms')
    scaleTextYOffset = kw.pop('scaleTextYOffset', .075)
    scaleHeight = kw.pop('scaleHeight', .02)
    scaleTextSize = kw.pop('scaleTextSize', 'small')
    reshape_senders = kw.pop('reshape_senders', True)
    kw['markersize'] = kw.get('markersize', 1.0)

    if ylabel is None:
        ylabel = 'Neuron #'

    ESpikes = ESpikes.windowed(tLimits)
    ISpikes = ISpikes.windowed(tLimits)

    ESenders, ETimes = ESpikes.rasterData()
    ISenders, ITimes = ISpikes.rasterData()

    if reshape_senders:
        # TO REMOVE: this is to transform the neuron number from row-wise to
        # column wise indexes. A better solution has to be devised in the
        # future
        logger.warn('Nx, Ny are fixed in the code. Make sure the torus size '
                    'is the same as specified here.')
        Nx, Ny = 34, 30
        N = Nx * Ny
        if (N != ESpikes.N or N != ISpikes.N):
            raise ValueError("Fix the number of neurons in plotEIRaster")
        Ex = ESenders % Nx
        Ey = ESenders // Ny
        ESenders = Ey + Ex * Ny
        Ix = ISenders % Nx
        Iy = ISenders // Ny
        ISenders = Iy + Ix * Ny

    ISenders += ESpikes.N

    globalAxesSettings(ax)
    ax.minorticks_on()
    ax.xaxis.set_visible(False)
    ax.spines['top'].set_visible(False)
    ax.spines['bottom'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.yaxis.set_major_locator(ti.LinearLocator(2))
    ax.yaxis.set_minor_locator(ti.NullLocator())

    ax.plot(ETimes, ESenders + 1, '.', color='red', mec='none', **kw)
    ax.plot(ITimes, ISenders + 1, '.', color='blue', mec='none', **kw)

    ax.set_xlim(tLimits)
    ax.set_ylim([1, ESpikes.N + ISpikes.N])
    if (yticks_style == 'separate'):
        ax.set_yticks([1, ESpikes.N, ESpikes.N + ISpikes.N])
    ax.invert_yaxis()
    ax.text(ylabelPos,
            0.5,
            ylabel,
            va='center',
            ha='center',
            transform=ax.transAxes,
            rotation=90)
    if (not yticks):
        ax.yaxis.set_ticklabels([])

    # Annotations
    if (sigmaTitle):
        ax.set_title('$\sigma$ = {0} pA'.format(int(noise_sigma)),
                     y=1.02,
                     va='bottom',
                     ha='center')
    if (ann):
        Y, X = aggr.computeYX(space, iterList, r=r, c=c)
        gE = Y[r, c]
        gI = X[r, c]
        txt = '$g_E$ = {0} nS\n$g_I$ = {1} nS'.format(gE, gI)
        ax.text(0.99,
                1.02,
                txt,
                va='bottom',
                ha='right',
                size='small',
                transform=ax.transAxes)

    if (ann_EI):
        ax.text(-0.05,
                0.75,
                'E',
                va='center',
                ha='center',
                size='small',
                transform=ax.transAxes,
                color='red',
                weight='bold')
        ax.text(-0.05,
                0.25,
                'I',
                va='center',
                ha='center',
                size='small',
                transform=ax.transAxes,
                color='blue',
                weight='bold')

    if (scaleBar is not None):
        xScaleBar(scaleBar,
                  x=scaleX,
                  y=scaleY,
                  ax=ax,
                  size=scaleTextSize,
                  unitsText=scaleText,
                  textYOffset=scaleTextYOffset,
                  height=scaleHeight)

    return ax