Ejemplo n.º 1
0
 def _modified_bbox(self, bbox=None):
     if bbox is None:
         return Bbox.from_extents(0, -90, 360, 90)
     else:
         xmin = bbox.xmin + 360 if bbox.xmin < 0 else bbox.xmin
         xmax = bbox.xmax + 360 if bbox.xmax < 0 else bbox.xmax
         return Bbox.from_extents(xmin, bbox.ymin, xmax, bbox.ymax)
Ejemplo n.º 2
0
def find_selected_axes(canvas, x1, y1, x2, y2):
    """
    Finds the C{Axes} within a matplotlib C{FigureCanvas} that overlaps with a
    canvas area from C{(x1, y1)} to C{(x1, y1)}.  That axes and the
    corresponding X and Y axes ranges are returned as a 3-tuple.

    If no axes overlaps with the specified area, or more than one axes
    overlaps, a 3-tuple of C{None}s is returned.
    """
    axes = None
    bbox = Bbox.from_extents(x1, y1, x2, y2)

    for a in canvas.get_figure().get_axes():
        if bbox.overlaps(a.bbox):
            if axes is None:
                axes = a
            else:
                return None, None, None

    if axes is None:
        return None, None, None

    x1, y1, x2, y2 = limit_selection(bbox, axes)
    xlim, ylim = get_bbox_lims(
        Bbox.from_extents(x1, y1, x2, y2).inverse_transformed(axes.transData))
    return axes, xlim, ylim
Ejemplo n.º 3
0
    def plot(self, *args, **kwargs):
        ps = self.env.ps
        myc = self._get_class_config()
        iter_list = self.config['iter_list']
        l, b, r, t = myc['bbox_rect']

        gamma_all = np.empty(0)
        pbumps_all = np.empty(0)

        # Separate noise sigmas
        for ns_idx, noise_sigma in enumerate(ps.noise_sigmas):
            if ns_idx == 0:
                mi_title = 'Gamma power vs. P_Bumps'
            else:
                mi_title = None

            gammaData = aggr.GammaAggregateData('acVal',
                                                ps.bumpGamma[ns_idx],
                                                iter_list,
                                                normalizeTicks=False,
                                                collapseTrials=False)
            pbumpsData = aggr.IsBump(ps.bumpGamma[ns_idx],
                                     iter_list,
                                     ignoreNaNs=True,
                                     collapseTrials=False)
            gammaData, _, _ = gammaData.getData()
            pbumpsData, _, _ = pbumpsData.getData()
            gamma_all = np.hstack((gamma_all, gammaData.flatten()))
            pbumps_all = np.hstack((pbumps_all, pbumpsData.flatten()))

            fig = self._get_final_fig(myc['fig_size'])
            ax = fig.add_axes(Bbox.from_extents(l, b, r, t))
            self.plotDistribution(pbumpsData,
                                  gammaData,
                                  ax,
                                  noise_sigma=noise_sigma,
                                  ylabel='',
                                  yticks=False)
            fname = self.config[
                'output_dir'] + "/gamma_pbumps_probability_{0}.pdf"
            fig.savefig(fname.format(int(noise_sigma)),
                        dpi=300,
                        transparent=True)
            plt.close(fig)

            self.mutual_information(gammaData,
                                    pbumpsData,
                                    noise_sigma=noise_sigma,
                                    title=mi_title)

        # All together
        fig = self._get_final_fig(myc['fig_size'])
        ax = fig.add_axes(Bbox.from_extents(l, b, r, t))
        self.plotDistribution(pbumps_all, gamma_all, ax)
        #fig.tight_layout(**myc['tight_layout_kwargs'])
        fname = self.config['output_dir'] + "/gamma_pbumps_probability_all.pdf"
        fig.savefig(fname, dpi=300, transparent=True)
        plt.close(fig)

        self.mutual_information(gamma_all, pbumps_all)
Ejemplo n.º 4
0
def generate_arrow():
    dpi = 72
    dpi2 = dpi / 3

    F = plt.figure(num=None, figsize=(0.6, 0.325), dpi=dpi, facecolor='w')
    ax = plt.subplot(111)
    x = [0, 1, 1, 0, 0]
    y = [1, 1, 0, 0, 1]

    ed = ax.transAxes.transform([(0, 0), (1, 1)])
    bbox = Bbox.from_extents((ed[0, 0] + 1) / dpi, (ed[0, 1] + 1) / dpi,
                             ed[1, 0] / dpi, (ed[1, 1] - 2) / dpi)

    print('### generating arrow palette button ###')

    a = np.linspace(0, 1, 256).reshape(1, -1)
    a = np.vstack((a, a))

    for name, style in arrowstyle_list():
        ax.cla()
        ax.tick_params(length=0)
        ax.annotate('', [1, 0.5],
                    xytext=[0, 0.5],
                    arrowprops=dict(arrowstyle=style))
        filename = 'arrow_' + encode(name.encode()) + '.png'
        ed = ax.transAxes.transform([(0, 0), (1, 1)])
        bbox = Bbox.from_extents(ed[0, 0] / dpi, ed[0, 1] / dpi,
                                 ed[1, 0] / dpi, ed[1, 1] / dpi)
        plt.savefig(filename, dpi=dpi, format='png', bbox_inches=bbox)
Ejemplo n.º 5
0
def plotIToEBrokenAxis(sp,
                       gIdx,
                       neuronIdx,
                       trialNum=0,
                       axBoundaries=None,
                       axesProportions=(0.5, 0.5),
                       bottomLimits=None,
                       topLimits=None,
                       **kw):
    if axBoundaries is None:
        axBoundaries = [0, 0, 1, 1]
    left, bottom, right, top = axBoundaries
    title = kw.pop('title', 'E cell')
    fig = kw.pop('fig', plt.gcf())
    h = top - bottom
    w = right - left
    hBottom = h * axesProportions[0]
    hTop = h * axesProportions[1]

    axBottom = fig.add_axes(
        Bbox.from_extents(left, bottom, right, bottom + hBottom))
    axTop = fig.add_axes(Bbox.from_extents(left, top - hTop, right, top),
                         sharex=axBottom)

    _, gI = aggr.computeYX(sp, iterList)
    M = sp[0][gIdx][trialNum].data['g_EI']
    conns = M[neuronIdx, :]

    pconn.plotConnHistogram(conns, title=title, ax=axBottom, **kw)
    kw['ylabel'] = ''
    pconn.plotConnHistogram(conns, title=title, ax=axTop, **kw)
    annG = gI[0, gIdx]
    if annG - int(annG) == 0:
        annG = int(annG)
    #ann = '$g_I$ = {0} nS'.format(annG)
    #fig.text(left+0.95*w, bottom+0.9*h, ann, ha='right', va='bottom',
    #        fontsize='x-small')

    axBottom.set_xlim([0, annG])
    axBottom.set_xticks([0, annG])
    axBottom.xaxis.set_ticklabels([0, '$g_I$'])
    axBottom.set_ylim(bottomLimits)
    axBottom.set_yticks(bottomLimits)
    axBottom.yaxis.set_minor_locator(ti.NullLocator())
    axTop.set_ylim(topLimits)
    axTop.set_yticks([topLimits[1]])
    axTop.xaxis.set_visible(False)
    axTop.spines['bottom'].set_visible(False)

    divLen = 0.07
    d = .015
    kwargs = dict(transform=fig.transFigure, color='k', clip_on=False)
    axBottom.plot((left - divLen * w, left + divLen * w),
                  (bottom + hBottom + d, bottom + hBottom - d), **kwargs)
    axTop.plot((left - divLen * w, left + divLen * w),
               (top - hTop + d, top - hTop - d), **kwargs)

    return axBottom, axTop
Ejemplo n.º 6
0
    def plot(self, *args, **kwargs):
        ps = self.env.ps

        output_dir = self.config['output_dir']

        rateLeft = rasterLeft
        rateBottom = 0.2
        rateRight = rasterRight
        rateTop = self.myc['rateTop']

        for idx, noise_sigma in enumerate(ps.noise_sigmas):
            # E cells
            fig = self._get_final_fig(self.myc['fig_size'])
            ax = fig.add_axes(
                Bbox.from_extents(rateLeft, rateBottom, rateRight, rateTop))
            kw = {}
            if (idx != 0):
                kw['ylabel'] = ''

            rasters.plotAvgFiringRate(ps.bumpGamma[idx],
                                      spaceType='bump',
                                      noise_sigma=ps.noise_sigmas[idx],
                                      popType='E',
                                      r=rasterRC[idx][0],
                                      c=rasterRC[idx][1],
                                      ylabelPos=self.myc['ylabelPos'],
                                      color='red',
                                      tLimits=tLimits,
                                      ax=ax,
                                      **kw)
            fname = output_dir + "/bumps_rate_e{0}.pdf".format(noise_sigma)
            fig.savefig(fname, dpi=300, transparent=transparent)
            plt.close()

            # I cells
            fig = self._get_final_fig(self.myc['fig_size'])
            ax = fig.add_axes(
                Bbox.from_extents(rateLeft, rateBottom, rateRight, rateTop))
            kw = {}
            if (idx != 0):
                kw['ylabel'] = ''

            rasters.plotAvgFiringRate(ps.bumpGamma[idx],
                                      spaceType='bump',
                                      noise_sigma=ps.noise_sigmas[idx],
                                      popType='I',
                                      r=rasterRC[idx][0],
                                      c=rasterRC[idx][1],
                                      ylabelPos=self.myc['ylabelPos'],
                                      color='blue',
                                      tLimits=tLimits,
                                      ax=ax,
                                      **kw)
            fname = output_dir + "/bumps_rate_i{0}.pdf".format(noise_sigma)
            fig.savefig(fname, dpi=300, transparent=transparent)
            plt.close()
Ejemplo n.º 7
0
    def plot(self, *args, **kwargs):
        ps = self.env.ps
        output_dir = self.config['output_dir']
        transparent = self.myc['transparent']

        for idx, noise_sigma in enumerate(ps.noise_sigmas):
            # E cells
            fig = self._get_final_fig(self.myc['fig_size'])
            l, b, r, t = self.myc['bbox']
            ax = fig.add_axes(Bbox.from_extents(l, b, r, t))
            kw = {}
            if (idx != 0):
                kw['ylabel'] = ''

            rasters.plotAvgFiringRate(
                ps.v[idx],
                spaceType='velocity',
                noise_sigma=noise_sigma,
                popType='E',
                r=rasterRC[idx][0],
                c=rasterRC[idx][1],
                color='red',
                ylabelPos=self.config['vel_rasters']['ylabelPos'],
                tLimits=self.config['vel_rasters']['tLimits'],
                trialNum=self.config['vel_rasters']['trialNum'],
                sigmaTitle=False,
                ax=ax,
                **kw)
            fname = output_dir + "/velocity_rate_e{0}.pdf".format(noise_sigma)
            fig.savefig(fname, dpi=300, transparent=transparent)
            plt.close()

            # I cells
            fig = self._get_final_fig(self.myc['fig_size'])
            ax = fig.add_axes(Bbox.from_extents(l, b, r, t))
            kw = {}
            if (idx != 0):
                kw['ylabel'] = ''

            rasters.plotAvgFiringRate(
                ps.v[idx],
                spaceType='velocity',
                noise_sigma=noise_sigma,
                popType='I',
                r=rasterRC[idx][0],
                c=rasterRC[idx][1],
                color='blue',
                ylabelPos=self.config['vel_rasters']['ylabelPos'],
                tLimits=self.config['vel_rasters']['tLimits'],
                trialNum=self.config['vel_rasters']['trialNum'],
                sigmaTitle=False,
                ax=ax,
                **kw)
            fname = output_dir + "/velocity_rate_i{0}.pdf".format(noise_sigma)
            fig.savefig(fname, dpi=300, transparent=transparent)
            plt.close()
Ejemplo n.º 8
0
def zoom_effect(ax_zoomed, ax_origin, xlims = None, orientation='below', **kwargs):
    """
    ax_zoomed : zoomed axes
    ax_origin:  the main axes
    (xmin,xmax) : the limits of the colored area in both plot axes.

    connect ax1 & ax2. The x-range of (xmin, xmax) in both axes will
    be marked.  The keywords parameters will be used ti create
    patches.

    """
    if xlims is None:
        tt = ax_zoomed.transScale + (ax_zoomed.transLimits + ax_origin.transAxes)
        transform = blended_transform_factory(ax_origin.transData, tt)

        bbox_zoomed=ax_zoomed.bbox
        bbox_origin=TransformedBbox(ax_zoomed.viewLim, transform)
    else:
        transform_zoomed=blended_transform_factory(ax_zoomed.transData, ax_zoomed.transAxes)
        transform_origin=blended_transform_factory(ax_origin.transData, ax_origin.transAxes)
    
        bbox_zoomed=TransformedBbox(Bbox.from_extents(xlims[0], 0, xlims[1], 1), transform_zoomed)
        bbox_origin=TransformedBbox(Bbox.from_extents(xlims[0], 0, xlims[1], 1), transform_origin)

    prop_patches = kwargs.copy()
    prop_patches["ec"] = "none"
    prop_patches["alpha"] = 0.2

    if orientation=='below':
        loc1a=2
        loc2a=3
        loc1b=1
        loc2b=4
    elif orientation=='above':
        loc1a=3
        loc2a=2
        loc1b=4
        loc2b=1
    else:
        raise Exception("orientation '%s' not recognized" % orientation)

    c1, c2, bbox_zoomed_patch, bbox_origin_patch, p = \
        connect_bbox(bbox_zoomed, bbox_origin,
                     loc1a=loc1a, loc2a=loc2a, loc1b=loc1b, loc2b=loc2b,
                     prop_lines=kwargs, prop_patches=prop_patches)

    ax_zoomed.add_patch(bbox_zoomed_patch)
    ax_origin.add_patch(bbox_origin_patch)
    ax_origin.add_patch(c1)
    ax_origin.add_patch(c2)
    ax_origin.add_patch(p)

    return c1, c2, bbox_zoomed_patch, bbox_origin_patch, p
Ejemplo n.º 9
0
def plotIToEBrokenAxis(sp, gIdx, neuronIdx, trialNum=0, axBoundaries=None,
                       axesProportions=(0.5, 0.5), bottomLimits=None,
                       topLimits=None, **kw):
    if axBoundaries is None:
        axBoundaries = [0, 0, 1, 1]
    left, bottom, right, top = axBoundaries
    title = kw.pop('title', 'E cell')
    fig   = kw.pop('fig', plt.gcf())
    h = top - bottom
    w = right - left
    hBottom = h*axesProportions[0]
    hTop = h*axesProportions[1]

    axBottom = fig.add_axes(Bbox.from_extents(left, bottom, right, bottom +
                                              hBottom))
    axTop = fig.add_axes(Bbox.from_extents(left, top - hTop, right, top),
                         sharex=axBottom)

    _, gI = aggr.computeYX(sp, iterList)
    M      = sp[0][gIdx][trialNum].data['g_EI']
    conns  = M[neuronIdx, :]

    pconn.plotConnHistogram(conns, title=title, ax=axBottom, **kw)
    kw['ylabel'] = ''
    pconn.plotConnHistogram(conns, title=title, ax=axTop, **kw)
    annG = gI[0, gIdx]
    if annG - int(annG) == 0:
        annG = int(annG)
    #ann = '$g_I$ = {0} nS'.format(annG)
    #fig.text(left+0.95*w, bottom+0.9*h, ann, ha='right', va='bottom',
    #        fontsize='x-small')

    axBottom.set_xlim([0, annG])
    axBottom.set_xticks([0, annG])
    axBottom.xaxis.set_ticklabels([0, '$g_I$'])
    axBottom.set_ylim(bottomLimits)
    axBottom.set_yticks(bottomLimits)
    axBottom.yaxis.set_minor_locator(ti.NullLocator())
    axTop.set_ylim(topLimits)
    axTop.set_yticks([topLimits[1]])
    axTop.xaxis.set_visible(False)
    axTop.spines['bottom'].set_visible(False)

    divLen = 0.07
    d = .015
    kwargs = dict(transform=fig.transFigure, color='k', clip_on=False)
    axBottom.plot((left-divLen*w, left+divLen*w), (bottom+hBottom + d,
                                                   bottom+hBottom - d),
                  **kwargs)
    axTop.plot((left-divLen*w, left+divLen*w), (top-hTop + d, top-hTop - d),
               **kwargs)

    return axBottom, axTop
Ejemplo n.º 10
0
    def plot(self, *args, **kwargs):
        ps = self.env.ps

        output_dir = self.config['output_dir']

        rateLeft    = rasterLeft
        rateBottom  = 0.2
        rateRight   = rasterRight
        rateTop     = self.myc['rateTop']

        for idx, noise_sigma in enumerate(ps.noise_sigmas):
            # E cells
            fig = self._get_final_fig(self.myc['fig_size'])
            ax = fig.add_axes(Bbox.from_extents(rateLeft, rateBottom, rateRight,
                rateTop))
            kw = {}
            if (idx != 0):
                kw['ylabel'] = ''

            rasters.plotAvgFiringRate(ps.bumpGamma[idx],
                    spaceType='bump',
                    noise_sigma=ps.noise_sigmas[idx],
                    popType='E',
                    r=rasterRC[idx][0], c=rasterRC[idx][1],
                    ylabelPos=self.myc['ylabelPos'],
                    color='red',
                    tLimits=tLimits,
                    ax=ax, **kw)
            fname = output_dir + "/bumps_rate_e{0}.pdf".format(noise_sigma)
            fig.savefig(fname, dpi=300, transparent=transparent)
            plt.close()

            # I cells
            fig = self._get_final_fig(self.myc['fig_size'])
            ax = fig.add_axes(Bbox.from_extents(rateLeft, rateBottom, rateRight,
                rateTop))
            kw = {}
            if (idx != 0):
                kw['ylabel'] = ''

            rasters.plotAvgFiringRate(ps.bumpGamma[idx],
                    spaceType='bump',
                    noise_sigma=ps.noise_sigmas[idx],
                    popType='I',
                    r=rasterRC[idx][0], c=rasterRC[idx][1],
                    ylabelPos=self.myc['ylabelPos'],
                    color='blue',
                    tLimits=tLimits,
                    ax=ax, **kw)
            fname = output_dir + "/bumps_rate_i{0}.pdf".format(noise_sigma)
            fig.savefig(fname, dpi=300, transparent=transparent)
            plt.close()
Ejemplo n.º 11
0
    def plot(self, *args, **kwargs):
        ps = self.env.ps
        plot_theta = self.myc.get('plot_theta', False)

        output_dir = self.config['output_dir']

        for ns_idx, noise_sigma in enumerate(ps.noise_sigmas):
            fig = self._get_final_fig(self.myc['fig_size'])

            # Plot theta signal if requested
            if plot_theta:
                tl, tb, tr, tt = self.myc['theta_rect']
                ax_theta = fig.add_axes(Bbox.from_extents(tl, tb, tr, tt))
                t = np.arange(tLimits[0], tLimits[1] + self.dt, self.dt)
                theta = (
                    self.const + .5 *
                    (1. + np.cos(2 * np.pi * self.freq * 1e-3 * t - np.pi)) *
                    (1 - self.const))
                ax_theta.fill_between(t,
                                      theta,
                                      edgecolor='None',
                                      color=self.myc['theta_color'])
                ax_theta.set_xlim([tLimits[0], tLimits[1]])
                ax_theta.set_ylim(-.02, 1.02)
                ax_theta.axis('off')

            ax = fig.add_axes(
                Bbox.from_extents(rasterLeft, rasterBottom, rasterRight,
                                  rasterTop))
            rasters.EIRaster(
                ps.bumpGamma[ns_idx],
                noise_sigma=noise_sigma,
                spaceType='bump',
                r=rasterRC[ns_idx][0],
                c=rasterRC[ns_idx][1],
                ylabelPos=self.myc['ylabelPos'],
                tLimits=tLimits,
                markersize=2 * self.config['scale_factor'],
                ylabel='' if self.myc['yticks'][ns_idx] == False else None,
                yticks=self.myc['yticks'][ns_idx],
                scaleBar=self.myc['scaleBar'][ns_idx],
                scaleX=self.myc['scaleX'],
                scaleY=self.myc['scaleY'],
                scaleTextYOffset=.03,
                scaleHeight=.005,
                ann_EI=True)

            fname = "%s/bumps_raster%d.%s" % (output_dir, int(noise_sigma),
                                              self.myc['fig_ext'])
            fig.savefig(fname, dpi=300, transparent=transparent)
            plt.close()
Ejemplo n.º 12
0
    def plot(self, *args, **kwargs):
        ps = self.env.ps
        output_dir = self.config['output_dir']
        transparent = self.myc['transparent']

        for idx, noise_sigma in enumerate(ps.noise_sigmas):
            # E cells
            fig = self._get_final_fig(self.myc['fig_size'])
            l, b, r, t = self.myc['bbox']
            ax = fig.add_axes(Bbox.from_extents(l, b, r, t))
            kw = {}
            if (idx != 0):
                kw['ylabel'] = ''

            rasters.plotAvgFiringRate(ps.v[idx],
                    spaceType='velocity',
                    noise_sigma=noise_sigma,
                    popType='E',
                    r=rasterRC[idx][0], c=rasterRC[idx][1],
                    color='red',
                    ylabelPos=self.config['vel_rasters']['ylabelPos'],
                    tLimits=self.config['vel_rasters']['tLimits'],
                    trialNum=self.config['vel_rasters']['trialNum'],
                    sigmaTitle=False,
                    ax=ax, **kw)
            fname = output_dir + "/velocity_rate_e{0}.pdf".format(noise_sigma)
            fig.savefig(fname, dpi=300, transparent=transparent)
            plt.close()

            # I cells
            fig = self._get_final_fig(self.myc['fig_size'])
            ax = fig.add_axes(Bbox.from_extents(l, b, r, t))
            kw = {}
            if (idx != 0):
                kw['ylabel'] = ''

            rasters.plotAvgFiringRate(ps.v[idx],
                    spaceType='velocity',
                    noise_sigma=noise_sigma,
                    popType='I',
                    r=rasterRC[idx][0], c=rasterRC[idx][1],
                    color='blue',
                    ylabelPos=self.config['vel_rasters']['ylabelPos'],
                    tLimits=self.config['vel_rasters']['tLimits'],
                    trialNum=self.config['vel_rasters']['trialNum'],
                    sigmaTitle=False,
                    ax=ax, **kw)
            fname = output_dir + "/velocity_rate_i{0}.pdf".format(noise_sigma)
            fig.savefig(fname, dpi=300, transparent=transparent)
            plt.close()
Ejemplo n.º 13
0
def main():
    fig, ax = plt.subplots()

    years = np.arange(2004, 2009)
    heights = [7900, 8100, 7900, 6900, 2800]
    box_colors = [
        (0.8, 0.2, 0.2),
        (0.2, 0.8, 0.2),
        (0.2, 0.2, 0.8),
        (0.7, 0.5, 0.8),
        (0.3, 0.8, 0.7),
    ]

    for year, h, bc in zip(years, heights, box_colors):
        bbox0 = Bbox.from_extents(year - 0.4, 0., year + 0.4, h)
        bbox = TransformedBbox(bbox0, ax.transData)
        ax.add_artist(RibbonBoxImage(ax, bbox, bc, interpolation="bicubic"))
        ax.annotate(str(h), (year, h), va="bottom", ha="center")

    ax.set_xlim(years[0] - 0.5, years[-1] + 0.5)
    ax.set_ylim(0, 10000)

    background_gradient = np.zeros((2, 2, 4))
    background_gradient[:, :, :3] = [1, 1, 0]
    background_gradient[:, :, 3] = [[0.1, 0.3], [0.3, 0.5]]  # alpha channel
    ax.imshow(background_gradient,
              interpolation="bicubic",
              zorder=0.1,
              extent=(0, 1, 0, 1),
              transform=ax.transAxes,
              aspect="auto")

    plt.show()
Ejemplo n.º 14
0
    def plot(self, *args, **kwargs):
        ylabel_coords = self.myc.get('ylabel_coords', None)
        x0, x1, dx = self.myc.get('x_range', (-.5, .5, .001))
        l, b, r, t = self.myc['bbox_rect']

        d = np.arange(x0, x1+dx, dx)
        y_dim = np.sqrt(3)/2.0
        ES_pAMPA_mu = y_dim/2.0
        ES_pAMPA_sigma = 0.5/6
        ES_pGABA_sigma = 0.5/6
        ES_pGABA_const = 0.013
        shift = 0.1

        # Excitatory surround
        ES_exc_profile         = np.exp(-(np.abs(d) - ES_pAMPA_mu)**2/2/ES_pAMPA_sigma**2)
        ES_exc_profile_shifted = np.exp(-(np.abs(d - shift) - ES_pAMPA_mu)**2/2/ES_pAMPA_sigma**2)
        ES_inh_profile         = (1-ES_pGABA_const)*np.exp(-d**2/2./ES_pGABA_sigma**2) + ES_pGABA_const

        fig = self._get_final_fig(self.myc['fig_size'])
        ax = fig.add_axes(Bbox.from_extents(l, b, r, t))
        self.plotWeights(ax, d, ES_exc_profile, ES_inh_profile, ES_pGABA_const,
                         linewidth=self.config['scale_factor'],
                         x_range=(x0, x1, dx))
        ax.set_xticks(self.myc.get('xticks', [-.5, .5]))
        ax.xaxis.set_minor_locator(ti.MultipleLocator(0.5))
        ax.xaxis.set_label_coords(x=0.5, y=-0.2)
        if ylabel_coords is not None:
            ax.yaxis.set_label_coords(ylabel_coords[0], ylabel_coords[1])
        fileName = self.get_fname("{base}_E_surr.pdf", base='fig_conn_func')
        plt.savefig(fileName, transparent=True)
Ejemplo n.º 15
0
def zoom_effect(ax1, ax2, xlim, **kwargs):

	trans1 = blended_transform_factory(ax1.transData, ax1.transAxes)
	trans2 = blended_transform_factory(ax2.transData, ax2.transAxes)

	bbox = Bbox.from_extents(xlim[0], 0, xlim[1], 1)

	tbbox1 = TransformedBbox(bbox, trans1)
	tbbox2 = TransformedBbox(bbox, trans2)

	
	prop_patches = kwargs.copy()
	prop_patches['ec'] = 'none'
	prop_patches['alpha'] = 0.1

	c1, c2, bbox_patch1, bbox_patch2, p = \
			connect_bboxes(tbbox1, tbbox2, loc1a=3, loc2a=2, loc1b=4, loc2b=1, prop_lines=kwargs, prop_patches=prop_patches)
	
	ax1.add_patch(bbox_patch1)
	ax2.add_patch(bbox_patch2)
	ax2.add_patch(c1)
	ax2.add_patch(c2)
	ax2.add_patch(p)

	return c1, c2, bbox_patch1, bbox_patch2, p
Ejemplo n.º 16
0
def main():
    fig, ax = plt.subplots()

    years = np.arange(2004, 2009)
    heights = [7900, 8100, 7900, 6900, 2800]
    box_colors = [
        (0.8, 0.2, 0.2),
        (0.2, 0.8, 0.2),
        (0.2, 0.2, 0.8),
        (0.7, 0.5, 0.8),
        (0.3, 0.8, 0.7),
    ]

    for year, h, bc in zip(years, heights, box_colors):
        bbox0 = Bbox.from_extents(year - 0.4, 0., year + 0.4, h)
        bbox = TransformedBbox(bbox0, ax.transData)
        ax.add_artist(RibbonBoxImage(ax, bbox, bc, interpolation="bicubic"))
        ax.annotate(str(h), (year, h), va="bottom", ha="center")

    ax.set_xlim(years[0] - 0.5, years[-1] + 0.5)
    ax.set_ylim(0, 10000)

    background_gradient = np.zeros((2, 2, 4))
    background_gradient[:, :, :3] = [1, 1, 0]
    background_gradient[:, :, 3] = [[0.1, 0.3], [0.3, 0.5]]  # alpha channel
    ax.imshow(background_gradient, interpolation="bicubic", zorder=0.1,
              extent=(0, 1, 0, 1), transform=ax.transAxes, aspect="auto")

    plt.show()
def test_clip_path():
    x = np.array([-3, -2, -1, 0., 1, 2, 3, 2, 1, 0, -1, -2, -3, 5])
    y = np.arange(len(x))

    fig, ax = plt.subplots()
    ax.plot(x, y, lw=1)

    bbox = Bbox.from_extents(-2, 3, 2, 12.5)
    rect = plt.Rectangle(bbox.p0,
                         bbox.width,
                         bbox.height,
                         facecolor='none',
                         edgecolor='k',
                         ls='--')
    ax.add_patch(rect)

    clipped_lines, ticks = clip_line_to_rect(x, y, bbox)
    for lx, ly in clipped_lines:
        ax.plot(lx, ly, lw=1, color='C1')
        for px, py in zip(lx, ly):
            assert bbox.contains(px, py)

    ccc = iter(['C3o', 'C2x', 'C3o', 'C2x'])
    for ttt in ticks:
        cc = next(ccc)
        for (xx, yy), aa in ttt:
            ax.plot([xx], [yy], cc)
Ejemplo n.º 18
0
    def setDirectory(self, rootPath, shape):
        super(BumpSweepWidget, self).setDirectory(rootPath, shape)

        sigmaBumpText = '$\sigma_{bump}^{-1}\ (neurons^{-1})$'
        self.cbar_kw.update(dict(
                label       = sigmaBumpText,
                ticks       = ti.MultipleLocator(0.1)))

        self.canvas.fig.clear()
        self.ax = self.canvas.fig.add_axes(
                Bbox.from_extents(self.sweepLeft, self.sweepBottom, self.sweepRight,
                                  self.sweepTop))
       
        self.aggrData = aggr.AggregateBumpReciprocal(self.dataSpace, self.iterList,
                self.NTrials, tStart=self.bumpTStart)
        sweeps.plotSweep(self.aggrData,
                self.noise_sigma,
                sigmaTitle=False,
                cbar=True, cbar_kw=self.cbar_kw,
                ax=self.ax,
                picker=True)

        c = self.ax.collections
        if (len(c) != 1):
            raise RuntimeError("Something went wrong! len(c) != 1")
        self.dataCollection = c[0]

        self.canvas.draw()
        self.dataRenewed.emit(self.dataSpace)
Ejemplo n.º 19
0
def zoom_effect01(ax1, ax2, xmin, xmax, **kwargs):
    """
    ax1 : the main axes
    ax1 : the zoomed axes
    (xmin,xmax) : the limits of the colored area in both plot axes.

    connect ax1 & ax2. The x-range of (xmin, xmax) in both axes will
    be marked.  The keywords parameters will be used ti create
    patches.
    """

    trans1 = blended_transform_factory(ax1.transData, ax1.transAxes)
    trans2 = blended_transform_factory(ax2.transData, ax2.transAxes)

    bbox = Bbox.from_extents(xmin, 0, xmax, 1)

    mybbox1 = TransformedBbox(bbox, trans1)
    mybbox2 = TransformedBbox(bbox, trans2)

    prop_patches = kwargs.copy()
    #    prop_patches["ec"] = "none"
    #    prop_patches["alpha"] = 0.1

    c1, c2, bbox_patch1, bbox_patch2, p = \
        connect_bbox(mybbox1, mybbox2,
                     loc1a=2, loc2a=3, loc1b=1, loc2b=4,
                     prop_lines=kwargs, prop_patches=prop_patches)

    ax1.add_patch(bbox_patch1)
    ax2.add_patch(bbox_patch2)
    ax2.add_patch(c1)
    ax2.add_patch(c2)
    ax2.add_patch(p)
    return c1, c2, bbox_patch1, bbox_patch2, p
Ejemplo n.º 20
0
def generate_color():
    dpi = 72
    dpi2 = dpi / 3

    F = plt.figure(num=None, figsize=(1.2, 0.75), dpi=dpi, facecolor='w')
    ax = plt.subplot(111)
    x = [0, 1, 1, 0, 0]
    y = [1, 1, 0, 0, 1]

    ed = ax.transAxes.transform([(0, 0), (1, 1)])
    bbox = Bbox.from_extents(ed[0, 0] / dpi, ed[0, 1] / dpi, ed[1, 0] / dpi,
                             ed[1, 1] / dpi)

    print('### generating color palette button ###')

    collist = color_list()
    for color in collist:
        ax.cla()
        ax.tick_params(length=0)
        ax.set_axis_off()
        plt.fill(x, y, color=color)
        if color == 'none':
            plt.plot([0, 1], [1, 0], color='red')
        filename = 'color_' + encode(color) + '.png'
        plt.savefig(filename, dpi=dpi2, format='png', bbox_inches=bbox)

    ax.cla()
    ax.tick_params(length=0)
    ax.set_axis_off()
    ax.text(0.5, 0.2, '?', ha='center', fontsize=30)
    filename = 'color_' + encode('other') + '.png'
    plt.savefig(filename, dpi=dpi2, format='png', bbox_inches=bbox)
Ejemplo n.º 21
0
def generate_colormap():
    dpi = 72
    dpi2 = dpi

    F = plt.figure(num=None, figsize=(2.4, 0.3), dpi=dpi, facecolor='w')
    x = [0, 1, 1, 0, 0]
    y = [1, 1, 0, 0, 1]

    print('### generating colormap palette button ###')
    idl_names = register_idl_colormaps()

    a = np.linspace(0, 1, 256).reshape(1, -1)
    a = np.vstack([a] * 20)

    maps = [colormap_list()[0]] + colormap_list() + idl_names
    for map in maps:
        ax = plt.subplot(111)
        ax.cla()
        ax.tick_params(length=0)
        ax.set_axis_off()
        plt.imshow(a, cmap=plt.get_cmap(map), origin='lower')
        filename = 'colormap_' + encode(map) + '.png'
        ed = ax.transAxes.transform([(0, 0), (1, 1)])
        bbox = Bbox.from_extents(ed[0, 0] / dpi, ed[0, 1] / dpi,
                                 ed[1, 0] / dpi, ed[1, 1] / dpi)
        plt.savefig(filename, dpi=dpi2, format='png', bbox_inches=bbox)
Ejemplo n.º 22
0
def zoom_effect(ax1, ax2, xmin, xmax, **kwargs):
    trans1 = blended_transform_factory(ax1.transData, ax1.transAxes)
    trans2 = blended_transform_factory(ax2.transData, ax2.transAxes)

    bbox = Bbox.from_extents(xmin, 0, xmax, 1)

    mybbox1 = TransformedBbox(bbox, trans1)
    mybbox2 = TransformedBbox(bbox, trans2)

    prop_patches = {**kwargs, "ec": "none", "alpha": 0.1}

    c1, c2, bbox_patch1, bbox_patch2, p = connect_bbox(
        mybbox1,
        mybbox2,
        loc1a=3,
        loc2a=2,
        loc1b=4,
        loc2b=1,
        prop_lines=kwargs,
        prop_patches=prop_patches)

    ax1.add_patch(bbox_patch1)
    ax2.add_patch(bbox_patch2)
    ax2.add_patch(c1)
    ax2.add_patch(c2)
    ax2.add_patch(p)

    return c1, c2, bbox_patch1, bbox_patch2, p
Ejemplo n.º 23
0
    def plot(self, *args, **kwargs):
        ps = self.env.ps
        output_dir = self.config['output_dir']
        l, b, r, t = self.myc['bbox']
        transparent = self.myc['transparent']

        tLimits  = [2.75e3, 2.875e3] # ms
        trialNum = 0

        for idx, noise_sigma in enumerate(ps.noise_sigmas):
            fig = self._get_final_fig(self.myc['fig_size'])
            ax = fig.add_axes(Bbox.from_extents(l, b, r, t))
            kw = dict(scaleBar=None)
            if idx == 2:
                kw['scaleBar'] = 25
            rasters.EIRaster(ps.v[idx],
                    noise_sigma=noise_sigma,
                    spaceType='velocity',
                    r=rasterRC[idx][0], c=rasterRC[idx][1],
                    ylabelPos=self.myc['ylabelPos'],
                    tLimits=tLimits,
                    trialNum=trialNum,
                    sigmaTitle=False,
                    ann_EI=True,
                    scaleX=0.75,
                    scaleY=-0.15,
                    ylabel='', yticks=False,
                    **kw)
            fname = output_dir + "/velocity_raster_zooms{0}.png"
            fig.savefig(fname.format(int(noise_sigma)), dpi=300,
                    transparent=transparent)
            plt.close()
Ejemplo n.º 24
0
 def get_bbox(self):
     """
     Leave some room around the bars
     """
     x = self.get_xticks()
     y = self.get_yticks()
     return Bbox.from_extents(-0.2, 0, x[-1] + 0.6, y[-1] + 1)
Ejemplo n.º 25
0
    def find_component_bounds(self, components: List[str], zoom: float = 1.2):
        """Find bounds of a set of components.

        Args:
            components (List[str]): A list of component names
            zoom (float): Fraction to expand the bounding vbox by

        Returns:
            List: List of x,y coordinates defining the bounding box
        """
        if len(components) == 0:
            self.logger.error('At least one component must be provided.')
        # initialize bounds
        bounds = [float("inf"), float("inf"), float("-inf"), float("-inf")]
        for name in components:
            # self.design.components[name]
            component = self.design.components[name]
            # return (minx, miny, maxx, maxy)
            newbounds = component.qgeometry_bounds()
            bbox = Bbox.from_extents(newbounds)
            newbounds = bbox.expanded(zoom, zoom).extents
            # re-calculate total bounds by adding current component
            bounds = [
                min(newbounds[0], bounds[0]),
                min(newbounds[1], bounds[1]),
                max(newbounds[2], bounds[2]),
                max(newbounds[3], bounds[3])
            ]

        return bounds
Ejemplo n.º 26
0
    def plot(self, *args, **kwargs):
        ps = self.env.ps

        xlabel = self.myc.get('xlabel', None)
        ylabel = self.myc.get('ylabel', None)
        xticks = self.myc['xticks']
        yticks = self.myc['yticks']
        l, b, r, t = self.myc['bbox']
        normalize_ticks = self.myc.get('normalize_ticks', False)
        normalize_type = self.myc.get('normalize_type', None)
        fname = self.myc.get('fname', "generic_1d_sweep_{ns}.pdf")

        for ns_idx, noise_sigma in enumerate(ps.noise_sigmas):
            file_name = self.get_fname(fname, ns=noise_sigma)
            fig = self._get_final_fig(self.config['sweeps']['fig_size'])
            ax = fig.add_axes(Bbox.from_extents(l, b, r, t))
            sweeps.plot_1d_sweep(
                self.get_data(ns_idx),
                ax,
                xlabel='' if xticks[ns_idx] == False else xlabel,
                xticks=xticks[ns_idx],
                ylabel='' if yticks[ns_idx] == False else ylabel,
                yticks=yticks[ns_idx],
                title=noise_sigma,
                axis_setting=self.myc.get('axis_setting', 'scaled'))
            ax.set_xlim(self.myc.get('xlim', (None, None)))
            ax.set_ylim(self.myc.get('ylim', (None, None)))
            ax.yaxis.set_minor_locator(ti.AutoMinorLocator(2))
            fig.savefig(file_name, dpi=300, transparent=True)
            plt.close(fig)
Ejemplo n.º 27
0
    def plot(self, *args, **kwargs):
        ps = self.env.ps
        output_dir = self.config['output_dir']
        iter_list = self.config['iter_list']
        l, b, r, t = self.myc['bbox_rect']

        for ns_idx, noise_sigma in enumerate(ps.noise_sigmas):
            fig = self._get_final_fig(self.myc['fig_size'])
            ax = fig.add_axes(Bbox.from_extents(l, b, r, t))
            kwargs = dict()
            if ns_idx != 1:
                kwargs['xlabel'] = ''
            if ns_idx != 0:
                kwargs['ylabel'] = ''
            self.plotSlopes(
                ax,
                ps.v[ns_idx],
                self.myc['positions'][ns_idx],
                noise_sigma=noise_sigma,
                iterList=iter_list,
                color='blue',
                ivel_range=self.myc.get('ivel_range', None),
                g_ann=self.myc.get('g_ann', True),
                **kwargs)

            fname = (self.config['output_dir'] +
                     "/velocity_slope_examples_{0}.pdf".format(int(noise_sigma)))
            plt.savefig(fname, dpi=300, transparent=True)
Ejemplo n.º 28
0
    def plot(self, *args, **kwargs):
        ps = self.env.ps
        output_dir = self.config['output_dir']

        logger.info("Plotting rasters")
        for idx, noise_sigma in enumerate(ps.noise_sigmas):
            logger.info("   Rasters: %d pA", noise_sigma)
            fig = self._get_final_fig(self.myc['fig_size'])
            l, b, r, t = self.myc['bbox']
            ax = fig.add_axes(Bbox.from_extents(l, b, r, t))
            kw = dict(scaleBar=None)
            if (idx != 0):
                kw['ylabel'] = ''
                kw['yticks'] = False
            if idx == 2:
                kw['scaleBar'] = 125
            rasters.EIRaster(ps.v[idx],
                    noise_sigma=noise_sigma,
                    spaceType='velocity',
                    r=rasterRC[idx][0], c=rasterRC[idx][1],
                    ylabelPos=self.config['vel_rasters']['ylabelPos'],
                    tLimits=self.config['vel_rasters']['tLimits'],
                    trialNum=self.config['vel_rasters']['trialNum'],
                    ann_EI=True,
                    scaleX=0.85,
                    scaleY=-0.15,
                    **kw)
            fname = output_dir + "/velocity_raster{0}.png"
            fig.savefig(fname.format(int(noise_sigma)), dpi=300,
                    transparent=self.myc['transparent'])
            plt.close()
Ejemplo n.º 29
0
    def zoom_by_factor(self, factor, x, y):
        """Zoom by factor around point defined by x, y coordinates"""
        # Compute ratios around x,y
        current_bbox = self.current_bbox()
        left = (x - current_bbox.xmin) / current_bbox.width
        right = (current_bbox.xmax - x) / current_bbox.width
        bottom = (y - current_bbox.ymin) / current_bbox.height
        top = (current_bbox.ymax - y) / current_bbox.height

        # Apply zoom factor on sizes
        width, height = self.width() / factor, self.height() / factor
        limits = self.limits()
        if width > limits.width:
            width = limits.width
        if height > limits.height:
            height = limits.height

        # Apply new sizes with same ratios around x,y
        bbox = Bbox.from_extents(
            x - left * width,
            y - bottom * height,
            x + right * width,
            y + top * height,
        )

        self.apply_bbox(self.constrained_bbox(bbox, limits))
Ejemplo n.º 30
0
        def __init__(self, axes, zorder, features, plasmid_size, radius,
                     feature_width, spacing, arrow_head_length, label,
                     face_properties, label_properties, omit_oversized_labels,
                     feature_formatter):
            super().__init__()
            self._axes = axes
            self.zorder = zorder
            self._features = features
            self._plasmid_size = plasmid_size
            self._radius = radius
            self._feature_width = feature_width
            self._spacing = spacing

            self._all_indicators = []
            for feature in features:
                indicators_for_feature = []
                for loc in feature.locs:
                    # Set proper positions in 'draw()' method
                    bbox = Bbox.from_extents(0, 0, 0, 0)
                    # Draw features as curved arrows (feature indicator)
                    indicator = axes.add_artist(
                        Feature_Indicator(axes, self.zorder + 1, feature, loc,
                                          bbox, arrow_head_length,
                                          face_properties, label_properties,
                                          omit_oversized_labels,
                                          feature_formatter))
                    indicators_for_feature.append(indicator)
                self._all_indicators.append(indicators_for_feature)
Ejemplo n.º 31
0
def zoom_effect01(ax1, ax2, xmin, xmax, **kwargs):
    u"""
    ax1 : the main axes
    ax1 : the zoomed axes
    (xmin,xmax) : the limits of the colored area in both plot axes.
    connect ax1 & ax2. The x-range of (xmin, xmax) in both axes will
    be marked.  The keywords parameters will be used ti create
    patches.
    """
    trans1 = blended_transform_factory(ax1.transData, ax1.transAxes)
    trans2 = blended_transform_factory(ax2.transData, ax2.transAxes)
    bbox = Bbox.from_extents(xmin, 0, xmax, 1)
    mybbox1 = TransformedBbox(bbox, trans1)
    mybbox2 = TransformedBbox(bbox, trans2)
    prop_patches=kwargs.copy()
    prop_patches["ec"]="none"
    prop_patches["alpha"]=0.2
    c1, c2, bbox_patch1, bbox_patch2, p = \
        connect_bbox(mybbox1, mybbox2,
                     loc1a=3, loc2a=2, loc1b=4, loc2b=1,
                     prop_lines=kwargs, prop_patches=prop_patches)
    ax1.add_patch(bbox_patch1)
    ax2.add_patch(bbox_patch2)
    ax2.add_patch(c1)
    ax2.add_patch(c2)
    ax2.add_patch(p)
    return c1, c2, bbox_patch1, bbox_patch2, p
Ejemplo n.º 32
0
    def plot(self, *args, **kwargs):
        ps = self.env.ps

        xlabel = self.myc.get('xlabel', None)
        ylabel = self.myc.get('ylabel', None)
        xticks = self.myc['xticks']
        yticks = self.myc['yticks']
        l, b, r, t = self.myc['bbox']
        normalize_ticks = self.myc.get('normalize_ticks', False)
        normalize_type = self.myc.get('normalize_type', None)
        fname = self.myc.get('fname', "generic_1d_sweep_{ns}.pdf")

        for ns_idx, noise_sigma in enumerate(ps.noise_sigmas):
            file_name = self.get_fname(fname, ns=noise_sigma)
            fig = self._get_final_fig(self.config['sweeps']['fig_size'])
            ax = fig.add_axes(Bbox.from_extents(l, b, r, t))
            sweeps.plot_1d_sweep(
                self.get_data(ns_idx),
                ax,
                xlabel='' if xticks[ns_idx] == False else xlabel,
                xticks=xticks[ns_idx],
                ylabel='' if yticks[ns_idx] == False else ylabel,
                yticks=yticks[ns_idx],
                title=noise_sigma,
                axis_setting=self.myc.get('axis_setting', 'scaled'))
            ax.set_xlim(self.myc.get('xlim', (None, None)))
            ax.set_ylim(self.myc.get('ylim', (None, None)))
            ax.yaxis.set_minor_locator(ti.AutoMinorLocator(2))
            fig.savefig(file_name, dpi=300, transparent=True)
            plt.close(fig)
Ejemplo n.º 33
0
    def setDirectory(self, rootPath, shape):
        super(GridSweepWidget, self).setDirectory(rootPath, shape)

        self.canvas.fig.clear()
        self.ax = self.canvas.fig.add_axes(
                Bbox.from_extents(self.sweepLeft, self.sweepBottom, self.sweepRight,
                                  self.sweepTop))
        self.cbar_kw.update({
            'label'      : 'Gridness score',
            'ticks'      : ti.MultipleLocator(0.5)})

        sweeps.plotGridTrial(self.dataSpace, self.varList, self.iterList,
                self.noise_sigma,
                trialNumList=[],
                sigmaTitle=False,
                ignoreNaNs=True,
                r=5, c=15,
                cbar=True, cbar_kw=self.cbar_kw,
                ax=self.ax,
                picker=True)

        c = self.ax.collections
        if (len(c) != 1):
            raise RuntimeError("Something went wrong! len(c) != 1")
        self.dataCollection = c[0]

        self.canvas.draw()
        self.dataRenewed.emit(self.dataSpace)
Ejemplo n.º 34
0
def generate_plinestyle():
    dpi = 72
    dpi2 = dpi * 5 if isMPL2 else dpi

    F = plt.figure(num=None, figsize=(0.4, 0.25), dpi=dpi, facecolor='w')
    ax = plt.subplot(111)
    x = [0, 1, 1, 0, 0]
    y = [1, 1, 0, 0, 1]
    ed = ax.transAxes.transform([(0, 0), (1, 1)])
    bbox = Bbox.from_extents(ed[0, 0] / dpi, ed[0, 1] / dpi, ed[1, 0] / dpi,
                             ed[1, 1] / dpi)

    print('### generating patch linestyle palette button ###')
    plinestylelist = plinestyle_list()

    x = [0, 0.5, 1]
    y = [0.5, 0.5, 0.5]
    for plinestyle in plinestylelist:
        ax.cla()
        ax.tick_params(length=0)
        ax.set_axis_off()
        plt.axhspan(0.5,
                    0.5,
                    linestyle=plinestyle,
                    edgecolor='black',
                    facecolor='white',
                    linewidth=2)
        filename = 'plinestyle_' + encode(str(plinestyle)) + '.png'
        plt.savefig(filename, dpi=dpi2, format='png', bbox_inches=bbox)

        # plt produces blured image on MPL2.0
        if isMPL2:
            im = wx.Image(filename)
            w, h = im.GetSize()
            im.Rescale(w / 5, h / 5).SaveFile(filename, wx.BITMAP_TYPE_PNG)
Ejemplo n.º 35
0
    def plot(self, *args, **kwargs):
        # 1st autocorrelation peak (gamma power)
        types = ('gamma', 'acVal')
        fig = self._get_final_fig(detailFigSize)
        ax = fig.add_axes(Bbox.from_extents(detailLeft, detailBottom, detailRight,
            detailTop))
        _, p13, l13 = details.plotDetailedNoise(EI13PS, detailedNTrials, types, ax=ax,
                ylabelPos=self.ylabelPos,
                xlabel='', xticks=False,
                color='red', markerfacecolor='red', zorder=10)
        _, p31, l31 = details.plotDetailedNoise(EI31PS, detailedNTrials, types, ax=ax,
                xlabel='', xticks=False,
                ylabel='$1^{st}$\nautocorrelation\npeak', ylabelPos=self.ylabelPos,
                color='#505050')
        ax.xaxis.set_visible(False)
        ax.spines['bottom'].set_visible(False)
        ax.yaxis.set_major_locator(ti.MultipleLocator(0.6))
        ax.yaxis.set_minor_locator(ti.AutoMinorLocator(6))
        ax.set_ylim(prepareLims((0, 0.6), margin=0.03))
        leg = self.myc['legend']
        l = ax.legend([p31, p13], leg, **self.myc['legend_kwargs'])
        plt.setp(l.get_title(), fontsize='small')


        fname = self.config['output_dir'] + "/gamma_detailed_noise_power.pdf"
        plt.savefig(fname, dpi=300, transparent=True)
        plt.close()

        # Gamma frequency
        types = ('gamma', 'freq')
        fig = self._get_final_fig(detailFigSize)
        ax = fig.add_axes(Bbox.from_extents(detailLeft, detailBottom, detailRight,
            detailTop))
        _, p13, l13 = details.plotDetailedNoise(EI13PS, detailedNTrials, types, ax=ax,
                ylabelPos=self.ylabelPos,
                xlabel='',
                color='red', markerfacecolor='red', zorder=10)
        _, p31, l31 = details.plotDetailedNoise(EI31PS, detailedNTrials, types, ax=ax,
                ylabel='Oscillation\nfrequency (Hz)', ylabelPos=self.ylabelPos,
                color='#505050')
        ax.yaxis.set_major_locator(ti.MultipleLocator(30))
        ax.yaxis.set_minor_locator(ti.AutoMinorLocator(3))
        ax.set_ylim(prepareLims((30, 90), margin=0.03))

        fname = self.config['output_dir'] + "/gamma_detailed_noise_freq.pdf"
        plt.savefig(fname, dpi=300, transparent=True)
        plt.close()
Ejemplo n.º 36
0
    def plot(self, *args, **kwargs):
        ps = self.env.ps
        myc = self._get_class_config()

        iter_list = self.config["iter_list"]
        l, b, r, t = self.myc["bbox_rect"]
        legend = self.myc.get("legend", True)
        legend_kwargs = myc["legend_kwargs"]

        xlabel = self.myc.get("xlabel", "P(bumps)")
        ylabel = "Gridness score"

        fig = self._get_final_fig(myc["fig_size"])
        ax = fig.add_axes(Bbox.from_extents(l, b, r, t))

        scatterColors = ["green", "red", "blue"]
        scatterOrders = [2, 3, 1]

        for ns_idx, noise_sigma in enumerate(ps.noise_sigmas):
            isBumpData = aggr.IsBump(ps.bumpGamma[ns_idx], iter_list, ignoreNaNs=True)
            gridData = aggr.GridnessScore(ps.grids[ns_idx], iter_list, ignoreNaNs=True, normalizeTicks=False)

            scatterPlot = scatter.ScatterPlot(
                isBumpData,
                gridData,
                None,
                None,
                None,
                None,
                None,
                c=scatterColors[ns_idx],
                s=6 * self.config["scale_factor"],
                linewidth=0.3,
                xlabel=xlabel,
                ylabel=ylabel,
                ax=ax,
                zorder=scatterOrders[ns_idx],
            )
            scatterPlot.plot()

        ax.xaxis.set_major_locator(ti.MultipleLocator(0.2))
        ax.yaxis.set_major_locator(ti.MultipleLocator(0.5))
        if legend:
            leg = ["0", "150", "300"]
            l = ax.legend(leg, **legend_kwargs)
            plt.setp(l.get_title(), size="small")
        # ax.set_ylabel(ax.get_ylabel(), y=0., ha='left')

        # Normal scale
        fname = self.config["output_dir"] + "/bumps_scatter_grids_vs_bumpFracTotal.pdf"
        fig.savefig(fname, dpi=300, transparent=True)

        # Exponential scale
        ax.set_xscale("exponential")
        ax.xaxis.set_major_locator(ti.MultipleLocator(0.5))
        ax.xaxis.set_minor_locator(ti.MultipleLocator(0.1))
        ax.set_xlim([-0.3, 1.002])
        fname = self.config["output_dir"] + "/bumps_scatter_grids_vs_bumpFracTotal_exp.pdf"
        fig.savefig(fname, dpi=300, transparent=True)
Ejemplo n.º 37
0
    def get_grid_info(self, x1, y1, x2, y2):
        """
        lon_values, lat_values : list of grid values. if integer is given,
                           rough number of grids in each direction.
        """

        extremes = self.extreme_finder(self.inv_transform_xy, x1, y1, x2, y2)

        # min & max rage of lat (or lon) for each grid line will be drawn.
        # i.e., gridline of lon=0 will be drawn from lat_min to lat_max.

        lon_min, lon_max, lat_min, lat_max = extremes
        lon_levs, lon_n, lon_factor = self.grid_locator1(lon_min, lon_max)
        lat_levs, lat_n, lat_factor = self.grid_locator2(lat_min, lat_max)

        if lon_factor is None:
            lon_values = np.asarray(lon_levs[:lon_n])
        else:
            lon_values = np.asarray(lon_levs[:lon_n] / lon_factor)
        if lat_factor is None:
            lat_values = np.asarray(lat_levs[:lat_n])
        else:
            lat_values = np.asarray(lat_levs[:lat_n] / lat_factor)

        lon_lines, lat_lines = self._get_raw_grid_lines(
            lon_values, lat_values, lon_min, lon_max, lat_min, lat_max)

        ddx = (x2 - x1) * 1.e-10
        ddy = (y2 - y1) * 1.e-10
        bb = Bbox.from_extents(x1 - ddx, y1 - ddy, x2 + ddx, y2 + ddy)

        grid_info = {
            "extremes":
            extremes,
            "lon_lines":
            lon_lines,
            "lat_lines":
            lat_lines,
            "lon":
            self._clip_grid_lines_and_find_ticks(lon_lines, lon_values,
                                                 lon_levs, bb),
            "lat":
            self._clip_grid_lines_and_find_ticks(lat_lines, lat_values,
                                                 lat_levs, bb),
        }

        tck_labels = grid_info["lon"]["tick_labels"] = {}
        for direction in ["left", "bottom", "right", "top"]:
            levs = grid_info["lon"]["tick_levels"][direction]
            tck_labels[direction] = self.tick_formatter1(
                direction, lon_factor, levs)

        tck_labels = grid_info["lat"]["tick_labels"] = {}
        for direction in ["left", "bottom", "right", "top"]:
            levs = grid_info["lat"]["tick_levels"][direction]
            tck_labels[direction] = self.tick_formatter2(
                direction, lat_factor, levs)

        return grid_info
Ejemplo n.º 38
0
    def plot(self, *args, **kwargs):
        ps = self.env.ps
        normalize_type = self.myc.get('normalize_type', (None, None))
        l, b, r, t = self.myc['bbox']
        fname = self.myc.get('fname', "gamma_power_generic_{ns}.pdf")

        for ns_idx, noise_sigma in enumerate(ps.noise_sigmas):
            metadata = GenericExtractor(ps.bumpGamma[ns_idx],
                                        normalize=self.myc['normalize_ticks'],
                                        normalize_type=normalize_type)
            data = aggr.GammaAggregateData(self.myc['what'],
                                           ps.bumpGamma[ns_idx],
                                           None,
                                           normalizeTicks=True,
                                           ignoreNaNs=True,
                                           metadata_extractor=metadata)

            if self.myc.get('filter_with_gridness', False):
                gridData = aggr.GridnessScore(ps.grids[ns_idx],
                                              None,
                                              normalizeTicks=True,
                                              collapseTrials=True,
                                              ignoreNaNs=True)
                gridFilter = aggr.GTFilter(gridData,
                                           self.myc['gridness_threshold'])
                data = data.filter_data(gridFilter)

            fig = self._get_final_fig(self.config['sweeps']['fig_size'])
            ax = fig.add_axes(Bbox.from_extents(l, b, r, t))
            sweeps.plotSweep(data,
                             noise_sigma=ps.noise_sigmas[ns_idx],
                             ax=ax,
                             xlabel=self.myc['xlabel'] if
                             self.myc['xticks'][ns_idx] is not False else '',
                             xticks=self.myc['xticks'][ns_idx],
                             ylabel=self.myc['ylabel'] if
                             self.myc['yticks'][ns_idx] is not False else '',
                             yticks=self.myc['yticks'][ns_idx],
                             sigmaTitle=self.myc['sigma_title'],
                             cbar=self.myc['cbar'][ns_idx],
                             cbar_kw=self.myc['cbar_kw'],
                             vmin=self.myc['vmin'],
                             vmax=self.myc['vmax'],
                             annotations=self.myc['ann'])

            if self.myc['plot_grid_contours'][ns_idx]:
                gridData = aggr.GridnessScore(ps.grids[ns_idx],
                                              None,
                                              ignoreNaNs=True,
                                              normalizeTicks=True)
                contours = sweeps.Contours(
                    gridData, self.config['sweeps']['grid_contours'])
                contours.plot(ax, **self.config['sweeps']['contours_kwargs'])

            ax.axis('tight')
            fig.savefig(self.get_fname(fname, ns=noise_sigma),
                        dpi=300,
                        transparent=True)
            plt.close(fig)
Ejemplo n.º 39
0
 def translated_bbox(self, bbox, dx, dy):
     """Translate bbox by dx and dy"""
     return Bbox.from_extents(
         bbox.xmin + dx,
         bbox.ymin + dy,
         bbox.xmax + dx,
         bbox.ymax + dy,
     )
Ejemplo n.º 40
0
    def plot(self, *args, **kwargs):
        ps = self.env.ps
        plot_theta = self.myc.get('plot_theta', False)

        output_dir = self.config['output_dir']

        for ns_idx, noise_sigma in enumerate(ps.noise_sigmas):
            fig = self._get_final_fig(self.myc['fig_size'])

            # Plot theta signal if requested
            if plot_theta:
                tl, tb, tr, tt = self.myc['theta_rect']
                ax_theta = fig.add_axes(Bbox.from_extents(tl, tb, tr, tt))
                t = np.arange(tLimits[0], tLimits[1]+self.dt, self.dt)
                theta = (self.const +
                         .5 * (1. + np.cos(2*np.pi*self.freq*1e-3*t - np.pi)) *
                         (1 - self.const))
                ax_theta.fill_between(t, theta, edgecolor='None',
                                      color=self.myc['theta_color'])
                ax_theta.set_xlim([tLimits[0], tLimits[1]])
                ax_theta.set_ylim(-.02, 1.02)
                ax_theta.axis('off')

            ax = fig.add_axes(Bbox.from_extents(rasterLeft, rasterBottom,
                                                rasterRight, rasterTop))
            rasters.EIRaster(
                ps.bumpGamma[ns_idx],
                noise_sigma=noise_sigma,
                spaceType='bump',
                r=rasterRC[ns_idx][0], c=rasterRC[ns_idx][1],
                ylabelPos=self.myc['ylabelPos'],
                tLimits=tLimits,
                markersize=2*self.config['scale_factor'],
                ylabel='' if self.myc['yticks'][ns_idx] == False else None,
                yticks=self.myc['yticks'][ns_idx],
                scaleBar=self.myc['scaleBar'][ns_idx],
                scaleX=self.myc['scaleX'],
                scaleY=self.myc['scaleY'],
                scaleTextYOffset=.03, scaleHeight=.005,
                ann_EI=True)

            fname = "%s/bumps_raster%d.%s" % (output_dir, int(noise_sigma),
                                              self.myc['fig_ext'])
            fig.savefig(fname, dpi=300, transparent=transparent)
            plt.close()
Ejemplo n.º 41
0
 def get_bbox(self):
     """
     Leave some room around the bars
     """
     max_fn = self.fn.max()
     min_fn = self.fn.min()
     max_time = self.time.max()
     min_time = self.time.min()
     return Bbox.from_extents(min_time, min_fn, max_time, max_fn)
Ejemplo n.º 42
0
 def _modified_bbox(self, bbox=None):
     if bbox is None:
         return Bbox.from_extents(
             np.min(self.lon),
             np.min(self.lat),
             np.max(self.lon),
             np.max(self.lat)
         )
     return bbox
Ejemplo n.º 43
0
    def plot(self, *args, **kwargs):
        iter_list = self.config["iter_list"]
        sigma_bump_text = self.config["bump_sigma"]["sigma_bump_text"]

        EI13Root = "simulation_data/main_network/detailed_noise/gamma_bump/EI-1_3"
        EI31Root = "simulation_data/main_network/detailed_noise/gamma_bump/EI-3_1"
        detailedShape = (31, 9)

        EI13PS = JobTrialSpace2D(detailedShape, EI13Root)
        EI31PS = JobTrialSpace2D(detailedShape, EI31Root)
        detailedNTrials = 5

        ylabelPos = -0.17
        detailFigSize = (3.8, 2.6)
        detailLeft = 0.18
        detailBottom = 0.26
        detailRight = 0.95
        detailTop = 0.95

        iter_list = ["noise_sigma", "g_AMPA_total"]

        types = ("bump", "sigma")
        fig = plt.figure(figsize=detailFigSize)
        ax = fig.add_axes(Bbox.from_extents(detailLeft, detailBottom, detailRight, detailTop))

        data13 = aggr.AggregateBumpReciprocal(
            EI13PS, iter_list, detailedNTrials, tStart=bumpTStart, normalizeTicks=False
        )
        _, p13, l13 = details.plotDetailedNoise(
            data13,
            None,
            None,
            ax=ax,
            ylabel=sigma_bump_text,
            ylabelPos=ylabelPos,
            color="red",
            markerfacecolor="red",
            zorder=10,
        )

        data31 = aggr.AggregateBumpReciprocal(
            EI31PS, iter_list, detailedNTrials, tStart=bumpTStart, normalizeTicks=False
        )
        _, p31, l31 = details.plotDetailedNoise(data31, None, None, ax=ax, ylabelPos=ylabelPos, color="#505050")

        # ax.set_yscale("log")
        # ax.set_ylim([1.5, 300])
        leg = ["a", "b"]
        l = ax.legend(
            [p31, p13], leg, loc=(0.85, 0.1), fontsize="small", frameon=False, numpoints=1, handletextpad=0.05
        )
        plt.setp(l.get_title(), fontsize="small")

        fname = self.config["output_dir"] + "/bumps_detailed_noise_sigma.pdf"
        plt.savefig(fname, dpi=300, transparent=True)
        plt.close()
Ejemplo n.º 44
0
    def plot(self, *args, **kwargs):
        ps = self.env.ps
        output_dir = self.config['output_dir']

        exampleFigSize = (1.6, 1.4)
        exLeft = 0.4
        exBottom = 0.32
        exRight = 0.95
        exTop = 0.85
        exampleRC = ((5, 15), (15, 5))
        for exIdx, example in enumerate(exampleRC):
            kw = dict()
            if exIdx == 1:
                kw['xlabel'] = ''

            fig = self._get_final_fig(exampleFigSize)
            ax = fig.add_axes(
                Bbox.from_extents(exLeft, exBottom, exRight, exTop))
            plotEToI(ps.conn,
                     example[0],
                     self.neuronIdx,
                     ylabel='',
                     title='',
                     rwidth=0.8,
                     linewidth=0,
                     **kw)
            ax.yaxis.set_minor_locator(ti.NullLocator())
            ax.set_xlabel(ax.xaxis.get_label_text(), labelpad=-5)
            fname = output_dir + "/figure_connections_examples_E2I{0}.pdf"
            plt.savefig(fname.format(exIdx), dpi=300, transparent=True)
            plt.close()

            fig = self._get_final_fig(exampleFigSize)
            axBoundaries = (exLeft, exBottom, exRight, exTop)
            axBottom, axTop = plotIToEBrokenAxis(ps.conn,
                                                 example[1],
                                                 self.neuronIdx,
                                                 ylabel='',
                                                 title='',
                                                 axBoundaries=axBoundaries,
                                                 axesProportions=(0.75, 0.2),
                                                 bottomLimits=(0, 60),
                                                 topLimits=(800, 900),
                                                 rwidth=0.8,
                                                 linewidth=0,
                                                 **kw)
            axBottom.set_xlabel(axBottom.xaxis.get_label_text(), labelpad=-5)
            fig.text(exLeft - 0.27,
                     0.5 * (self.bottom + self.top),
                     'Count',
                     rotation=90,
                     ha='center',
                     va='center')
            fname = output_dir + "/figure_connections_examples_I2E{0}.pdf"
            plt.savefig(fname.format(exIdx), dpi=300, transparent=True)
            plt.close()
Ejemplo n.º 45
0
def plotBumpSnapshots(FR, FRt, tstep, **kw):
    '''Snapshots of bumps in time.'''
    fig             = kw.pop('fig')
    timeTitles      = kw.pop('timeTitles', True)
    axesCoords      = kw.pop('axesCoords', (0.12, 0.01, 0.92, 0.7))
    axesDiv         = kw.pop('axesDiv', .01)
    bumpQuality     = kw.pop('bumpQuality', False)
    bumpQualityText = kw.pop('bumpQualityText', '')
    bumpQualityX    = kw.pop('bumpQualityX', -.9)
    maxRateColor    = kw.pop('maxRateColor', 'w')

    left, bottom, right, top = axesCoords
    width  = right - left
    height = top - bottom

    indexes = range(0, FRt.shape[0], tstep)
    oneWidth = float(width) / len(indexes)
    l = left
    bot = bottom
    max = np.max(FR[:, :, indexes])
    lastIndex = len(indexes) - 1
    idx = 0
    for it in indexes:
        print(it)
        t = bot + height
        r = l + oneWidth - axesDiv
        print(l, bot, r, top)

        ax = fig.add_axes(Bbox.from_extents(l, bot, r, top))
        plotBump(ax, FR[:, :, it], vmin=0, vmax=max, rasterized=True, **kw)
        if idx == lastIndex:
            rateText = "%.0f Hz" % max
            ax.text(1.05, .95, rateText, ha='left', va='top',
                    color=maxRateColor, transform=ax.transAxes, size='small',
                    weight='bold', clip_on=False)

        if bumpQuality and it == 0:
            txt = '{0:.2f}'.format(bumpQuality)
            ax.text(bumpQualityX, .5, txt, va='center', ha='center',
                    transform=ax.transAxes)

        if timeTitles:
            yTitle = 1.02
            ax.text(.5, yTitle, "{0}".format(FRt[it]*1e-3), size='medium',
                    transform=ax.transAxes, va='bottom', ha='center')
            if it == 0:
                ax.text(.5, yTitle + .3, "t(s)", ha='center', va='bottom',
                        transform=ax.transAxes)
                ax.text(bumpQualityX, yTitle, bumpQualityText, ha='center',
                        va='bottom', transform=ax.transAxes)

        l += oneWidth
        idx += 1

    return max  # Hack, but hopefully ok for now
Ejemplo n.º 46
0
    def onselect(self, eclick, erelease):
        if self.coord is None:
            return
        left, bottom = min(eclick.xdata, erelease.xdata), min(eclick.ydata, erelease.ydata)
        right, top = max(eclick.xdata, erelease.xdata), max(eclick.ydata, erelease.ydata)
        region = Bbox.from_extents(left, bottom, right, top)

        selectedIds = []
        for (xy, idd) in zip(self.matrix.values, self.matrix.ids):
            if region.contains(xy[0], xy[1]):
                selectedIds.append(idd)
        self.coord.notifyModules(selectedIds)
Ejemplo n.º 47
0
    def onselect(self, eclick, erelease):
        if (self.coord is None): return

        left, bottom = min(eclick.xdata, erelease.xdata), min(eclick.ydata, erelease.ydata)
        right, top = max(eclick.xdata, erelease.xdata), max(eclick.ydata, erelease.ydata)
        region = Bbox.from_extents(left, bottom, right, top)
        
        selectedIds = []
        for (x, y, idd) in zip(self.Xs, self.Ys, self.stats.ids):
            if region.contains(x, y):
                selectedIds.append(idd)
        self.coord.notifyModules(selectedIds)
Ejemplo n.º 48
0
 def get_grid_info(self,
                   x1, y1, x2, y2):
     """
     lon_values, lat_values : list of grid values. if integer is given,
                        rough number of grids in each direction.
     """
     extremes = self.extreme_finder(self.inv_transform_xy, x1, y1, x2, y2)
     lon_min, lon_max, lat_min, lat_max = extremes
     lon_levs, lon_n, lon_factor = \
               self.grid_locator1(lon_min, lon_max)
     lat_levs, lat_n, lat_factor = \
               self.grid_locator2(lat_min, lat_max)
     if lon_factor is None:
         lon_values = np.asarray(lon_levs[:lon_n])
     else:
         lon_values = np.asarray(lon_levs[:lon_n]/lon_factor)
     if lat_factor is None:
         lat_values = np.asarray(lat_levs[:lat_n])
     else:
         lat_values = np.asarray(lat_levs[:lat_n]/lat_factor)
     lon_lines, lat_lines = self._get_raw_grid_lines(lon_values,
                                                     lat_values,
                                                     lon_min, lon_max,
                                                     lat_min, lat_max)
     ddx = (x2-x1)*1.e-10
     ddy = (y2-y1)*1.e-10
     bb = Bbox.from_extents(x1-ddx, y1-ddy, x2+ddx, y2+ddy)
     grid_info = {}
     grid_info["extremes"] = extremes
     grid_info["lon_lines"] = lon_lines
     grid_info["lat_lines"] = lat_lines
     grid_info["lon"] = self._clip_grid_lines_and_find_ticks(lon_lines,
                                                             lon_values,
                                                             lon_levs,
                                                             bb)
     grid_info["lat"] = self._clip_grid_lines_and_find_ticks(lat_lines,
                                                             lat_values,
                                                             lat_levs,
                                                             bb)
     grid_info["lon"]["tick_labels"] = dict()
     tck_labels = grid_info["lon"]["tick_labels"]
     for direction in ["left", "bottom", "right", "top"]:
         levs = grid_info["lon"]["tick_levels"][direction]
         tck_labels[direction] = self.tick_formatter1(direction,
                                                      lon_factor, levs)
     grid_info["lat"]["tick_labels"] = dict()
     tck_labels = grid_info["lat"]["tick_labels"]
     for direction in ["left", "bottom", "right", "top"]:
         levs = grid_info["lat"]["tick_levels"][direction]
         tck_labels[direction] = self.tick_formatter2(direction,
                                                      lat_factor, levs)
     return grid_info
Ejemplo n.º 49
0
    def get_ax(self, fig):
        color_bar_pos = self._get_class_config()['cbar_kw']['location']
        l, b, w, h = self.config['sweeps']['bbox']
        if color_bar_pos == 'right':
            left = l
        elif color_bar_pos == 'left':
            left = .12
        else:
            left = .2

        right = left + w
        top = b + h
        return fig.add_axes(Bbox.from_extents(left, b, right, top))
Ejemplo n.º 50
0
    def get_grid_info(self, x1, y1, x2, y2):
        """
        lon_values, lat_values : list of grid values. if integer is given,
                           rough number of grids in each direction.
        """

        extremes = self.extreme_finder(self.inv_transform_xy, x1, y1, x2, y2)

        # min & max rage of lat (or lon) for each grid line will be drawn.
        # i.e., gridline of lon=0 will be drawn from lat_min to lat_max.

        lon_min, lon_max, lat_min, lat_max = extremes
        lon_levs, lon_n, lon_factor = self.grid_locator1(lon_min, lon_max)
        lat_levs, lat_n, lat_factor = self.grid_locator2(lat_min, lat_max)

        lon_values = lon_levs[:lon_n] / _deprecate_factor_none(lon_factor)
        lat_values = lat_levs[:lat_n] / _deprecate_factor_none(lat_factor)

        lon_lines, lat_lines = self._get_raw_grid_lines(lon_values,
                                                        lat_values,
                                                        lon_min, lon_max,
                                                        lat_min, lat_max)

        ddx = (x2-x1)*1.e-10
        ddy = (y2-y1)*1.e-10
        bb = Bbox.from_extents(x1-ddx, y1-ddy, x2+ddx, y2+ddy)

        grid_info = {
            "extremes": extremes,
            "lon_lines": lon_lines,
            "lat_lines": lat_lines,
            "lon": self._clip_grid_lines_and_find_ticks(
                lon_lines, lon_values, lon_levs, bb),
            "lat": self._clip_grid_lines_and_find_ticks(
                lat_lines, lat_values, lat_levs, bb),
        }

        tck_labels = grid_info["lon"]["tick_labels"] = {}
        for direction in ["left", "bottom", "right", "top"]:
            levs = grid_info["lon"]["tick_levels"][direction]
            tck_labels[direction] = self.tick_formatter1(
                direction, lon_factor, levs)

        tck_labels = grid_info["lat"]["tick_labels"] = {}
        for direction in ["left", "bottom", "right", "top"]:
            levs = grid_info["lat"]["tick_levels"][direction]
            tck_labels[direction] = self.tick_formatter2(
                direction, lat_factor, levs)

        return grid_info
Ejemplo n.º 51
0
def cust_mark_inset(parent_axes, inset_axes, x1,x2,y1,y2, loc11,loc12,loc21,loc22,**kwargs):
	print parent_axes.transData
	print inset_axes.viewLim
	rect = TransformedBbox(Bbox.from_extents([x1,y1,x2,y2]), parent_axes.transData)
  
	pp = BboxPatch(rect, **kwargs)
	parent_axes.add_patch(pp)

	p1 = BboxConnector(inset_axes.bbox, rect, loc1=loc11,loc2=loc12, **kwargs)
	inset_axes.add_patch(p1)
	p1.set_clip_on(False)
	p2 = BboxConnector(inset_axes.bbox, rect, loc1=loc21,loc2=loc22, **kwargs)
	inset_axes.add_patch(p2)
	p2.set_clip_on(False)
    def zoomEffect(self, ax, xmin, xmax, **kwargs):
            """
            ax : the main axes
            (xmin,xmax) : the limits of the colored area in the axis
        
            """
            trans = blended_transform_factory(ax.transData, ax.transAxes)
            bbox = Bbox.from_extents(xmin, 0, xmax, 1)
            mybbox = TransformedBbox(bbox, trans)
            
            prop_patches=kwargs.copy()
            prop_patches["ec"]="none"
            prop_patches["alpha"]=0.2
 
            bbox_patch = BboxPatch(mybbox, **prop_patches)            
            ax.add_patch(bbox_patch)
Ejemplo n.º 53
0
    def plot(self, *args, **kwargs):
        ps = self.env.ps
        iter_list = self.config["iter_list"]
        l, b, r, t = self.myc["bbox_rect"]

        scatterColors = ["green", "red", "blue"]
        scatterOrders = [2, 3, 1]

        # E cells
        fig = self._get_final_fig(self.myc["fig_size"])
        ax = fig.add_axes(Bbox.from_extents(l, b, r, t))
        ax.hold("on")
        xlabel = "Mean E firing rate (Hz)"

        for ns_idx, noise_sigma in enumerate(ps.noise_sigmas):
            grid_data = aggr.GridnessScore(ps.grids[ns_idx], iter_list, ignoreNaNs=True, normalizeTicks=False)
            fre_data = aggr.AvgPopulationFR(
                "FR_e/avg", ps.grids[ns_idx], iter_list, ignoreNaNs=True, normalizeTicks=False
            )
            color = scatterColors[ns_idx]
            scatterPlot = scatter.ScatterPlot(
                fre_data,
                grid_data,
                None,
                None,
                None,
                None,
                None,
                c=color,
                s=self.myc["dot_size"] * self.config["scale_factor"],
                linewidth=0.3,
                xlabel=xlabel,
                ylabel=self.myc["ylabel"],
                yticks=self.myc["yticks"],
                zorder=scatterOrders[ns_idx],
            )
            scatterPlot.plot()
        ax.xaxis.set_major_locator(ti.MultipleLocator(10))
        ax.yaxis.set_major_locator(ti.MultipleLocator(0.5))
        ax.yaxis.set_minor_locator(ti.MultipleLocator(0.25))

        leg = ["0", "150", "300"]
        l = ax.legend(leg, **self.myc["legend_kwargs"])
        plt.setp(l.get_title(), size=self.myc["legend_kwargs"]["fontsize"])

        fname = self.get_fname("/scatter_FRE_vs_grids.pdf")
        fig.savefig(fname, dpi=300, transparent=True)
Ejemplo n.º 54
0
    def plot(self, *args, **kwargs):
        ps = self.env.ps
        output_dir = self.config['output_dir']

        exampleFigSize = (1.6, 1.4)
        exLeft   = 0.4
        exBottom = 0.32
        exRight  = 0.95
        exTop    = 0.85
        exampleRC = ( (5, 15), (15, 5) )
        for exIdx, example in enumerate(exampleRC):
            kw = dict()
            if exIdx == 1:
                kw['xlabel'] = ''

            fig = self._get_final_fig(exampleFigSize)
            ax = fig.add_axes(Bbox.from_extents(exLeft, exBottom, exRight, exTop))
            plotEToI(ps.conn, example[0], self.neuronIdx, ylabel='', title='',
                    rwidth=0.8,
                    linewidth=0,
                    **kw)
            ax.yaxis.set_minor_locator(ti.NullLocator())
            ax.set_xlabel(ax.xaxis.get_label_text(), labelpad=-5)
            fname = output_dir + "/figure_connections_examples_E2I{0}.pdf"
            plt.savefig(fname.format(exIdx), dpi=300, transparent=True)
            plt.close()


            fig = self._get_final_fig(exampleFigSize)
            axBoundaries = (exLeft, exBottom, exRight, exTop)
            axBottom, axTop = plotIToEBrokenAxis(ps.conn, example[1],
                                                 self.neuronIdx,
                                                 ylabel='', title='',
                                                 axBoundaries=axBoundaries,
                                                 axesProportions=(0.75, 0.2),
                                                 bottomLimits=(0, 60),
                                                 topLimits=(800, 900),
                                                 rwidth=0.8,
                                                 linewidth=0,
                                                 **kw)
            axBottom.set_xlabel(axBottom.xaxis.get_label_text(), labelpad=-5)
            fig.text(exLeft - 0.27, 0.5*(self.bottom+self.top), 'Count',
                    rotation=90, ha='center', va='center')
            fname = output_dir + "/figure_connections_examples_I2E{0}.pdf"
            plt.savefig(fname.format(exIdx), dpi=300, transparent=True)
            plt.close()
Ejemplo n.º 55
0
def _bbox_fixed_margin(left, bottom, right, top, fig=None):
    if not fig:
        fig = plt.gcf()

    fig_inches = fig.get_size_inches()
    fig_w_in, fig_h_in = fig_inches
    fontsize_rel_h = 12.0/(72*fig_h_in)
    fontsize_rel_w = 12.0/(72*fig_w_in)

    box_left_rel = left*fontsize_rel_w
    box_bottom_rel = bottom*fontsize_rel_h
    box_right_rel = 1 - right*fontsize_rel_w
    box_top_rel = 1 - top*fontsize_rel_h

    return Bbox.from_extents(box_left_rel,
                             box_bottom_rel,
                             box_right_rel,
                             box_top_rel)
Ejemplo n.º 56
0
    def get_position(self, figure, return_all=False):
        """Update the subplot position from ``figure.subplotpars``.
        """
        gridspec = self.get_gridspec()
        nrows, ncols = gridspec.get_geometry()
        rows, cols = np.unravel_index([self.num1, self.num2], (nrows, ncols))
        fig_bottoms, fig_tops, fig_lefts, fig_rights = \
            gridspec.get_grid_positions(figure)

        fig_bottom = fig_bottoms[rows].min()
        fig_top = fig_tops[rows].max()
        fig_left = fig_lefts[cols].min()
        fig_right = fig_rights[cols].max()
        figbox = Bbox.from_extents(fig_left, fig_bottom, fig_right, fig_top)

        if return_all:
            return figbox, rows[0], cols[0], nrows, ncols
        else:
            return figbox
Ejemplo n.º 57
0
    def plot(self, *args, **kwargs):
        myc = self._get_class_config()
        sweepc = self._get_sweep_config()
        ps = self.env.ps
        iter_list = self.config["iter_list"]
        xlabel = self.myc.get("xlabel", None)
        ylabel = self.myc.get("ylabel", None)
        xticks = myc["xticks"]
        yticks = myc["yticks"]
        vmin = self.myc.get("vmin", self.bump_vmin)
        vmax = self.myc.get("vmax", self.bump_vmax)
        normalize_type = self.myc.get("normalize_type", (None, None))
        l, b, r, t = self.myc["bbox"]
        fname = self.myc.get("fname", "bumps_pbumps_generic_{ns}.pdf")

        for ns_idx, noise_sigma in enumerate(ps.noise_sigmas):
            file_name = self.get_fname(fname, ns=noise_sigma)
            fig = self._get_final_fig(self.config["sweeps"]["fig_size"])
            ax = fig.add_axes(Bbox.from_extents(l, b, r, t))
            metadata = GenericExtractor(
                ps.bumpGamma[ns_idx], normalize=self.myc["normalize_ticks"], normalize_type=normalize_type
            )
            data = aggr.IsBump(ps.bumpGamma[ns_idx], iter_list, ignoreNaNs=True, metadata_extractor=metadata)
            sweeps.plotSweep(
                data,
                noise_sigma=noise_sigma,
                sigmaTitle=self.myc.get("sigmaTitle", True),
                xlabel="" if xticks[ns_idx] == False else xlabel,
                xticks=xticks[ns_idx],
                ylabel="" if yticks[ns_idx] == False else ylabel,
                yticks=yticks[ns_idx],
                ax=ax,
                cbar=self.myc["cbar"][ns_idx],
                cbar_kw=myc["cbar_kw"],
                vmin=vmin,
                vmax=vmax,
                annotations=self.get_ann()[ns_idx],
                axis_setting=self.myc.get("axis_setting", "scaled"),
            )
            ax.axis("tight")
            fig.savefig(file_name, dpi=300, transparent=True)
            plt.close(fig)