Beispiel #1
0
    def PSFrange(self,junkAx):
        """
        Display function that you shouldn't call directly.
        """

        #ca=pyl.gca()
        pyl.sca(self.sp1)

        print self.starsScat

        newLim=[self.sp1.get_xlim(),self.sp1.get_ylim()]
        self.psfPlotLimits=newLim[:]
        w=num.where((self.points[:,0]>=self.psfPlotLimits[0][0])&(self.points[:,0]<=self.psfPlotLimits[0][1])&(self.points[:,1]>=self.psfPlotLimits[1][0])&(self.points[:,1]<=self.psfPlotLimits[1][1]))[0]

        if self.starsScat<>None:
            self.starsScat.remove()
            self.starsScat=None

        for ii in range(len(self.showing)):
            if self.showing[ii]: self.moffPatchList[ii][0].remove()

        for ii in range(len(self.showing)):
            if ii not in w: self.showing[ii]=0
            else: self.showing[ii]=1



        for ii in range(len(self.showing)):
            if self.showing[ii]:
                self.moffPatchList[ii]=self.sp4.plot(self.moffr,self.moffs[ii])
        self.sp4.set_xlim(0,30)
        self.sp4.set_ylim(0,1.02)

        pyl.draw()
Beispiel #2
0
def draw_hist(hpxmap, **kwargs):
    if isinstance(hpxmap, np.ma.MaskedArray):
        pix = np.where(~hpxmap.mask)
    else:
        pix = np.where((np.isfinite(hpxmap)) & (hpxmap != hp.UNSEEN))

    data = hpxmap[pix]
    kwargs.setdefault('bins', np.linspace(data.min(), data.max(), 100))
    kwargs.setdefault('histtype', 'step')
    kwargs.setdefault('normed', True)
    kwargs.setdefault('lw', 1.5)

    ax = plt.gca()
    n, b, p = ax.hist(data, **kwargs)

    ax2 = ax.twinx()
    plt.hist(data, cumulative=-1, color='r', **kwargs)
    ax2.set_ylabel('Cumulative', color='r')
    for tl in ax2.get_yticklabels():
        tl.set_color('r')
    ax2.set_ylim(0, 1)

    plt.sca(ax)
    quantiles = [5, 50, 95]
    percentiles = np.percentile(data, quantiles)
    for q, p in zip(quantiles, percentiles):
        draw_peak(p, color='r', label='%.1f (%g%%)' % (p, 100 - q))

    ax.set_xlim(kwargs['bins'].min(), kwargs['bins'].max())

    return quantiles, percentiles
def onMouseClick(event):
    # type: (matplotlib.backend_bases.MouseEvent) -> None
    axes = event.inaxes

    # Если кликнули вне какого-либо графика, то не будем ничего делать
    if axes is None:
        return

    global marker
    # Если маркер с текстом уже был создан, то удалим его
    if marker is not None:
        marker.remove()

    # В качестве текущих выберем оси, внутри которых кликнули мышью
    pylab.sca(axes)

    # Координаты клика в системе координат осей
    x = event.xdata
    y = event.ydata
    text = u'(X: {:.3f}; Y: {:.3f})'.format(x, y)

    # Выведем текст в точку, куда кликнули
    marker = pylab.text(x, y, text)

    # Обновим график
    pylab.show()
Beispiel #4
0
def add_subplot_name(offsets,subplot_names="abcdefghijklmnopq"):
    if len(offsets) != 2:
        raise Exception("Offsets for x and y coordinates should be provided")
    for iax,ax in enumerate(pylab.gcf().axes):
        pylab.sca(ax)
        pylab.text(offsets[0],1.+offsets[1],"({})".format(subplot_names[iax]),
                   transform=pylab.gca().transAxes)
Beispiel #5
0
    def test_zoom_to_fit(self):
        nside = 64
        ra, dec = 15, -45
        radius = 10.0
        pixels = cartosky.healpix.ang2disc(nside, ra, dec, radius)
        values = pixels

        fig, axes = plt.subplots(1, 3, figsize=(12, 3))
        for i, cls in enumerate(SKYMAPS):
            plt.sca(axes[i])
            m = cls(gridlines=False)
            m.draw_hpxmap(values, pixels, nside=nside, xsize=200)
            m.zoom_to_fit(values, pixels, nside)
            draw_labels = i == 0
            xlocs = np.linspace(ra - 2 * radius, ra + 2 * radius, 5)
            ylocs = np.linspace(dec - 2 * radius, dec + 2 * radius, 5)
            m.ax.gridlines(draw_labels=draw_labels,
                           xlocs=xlocs,
                           ylocs=ylocs,
                           linestyle=':')

            # m.draw_parallels(np.linspace(dec-2*radius,dec+2*radius,5),
            #                  labelstyle='+/-',labels=[1,0,0,0])
            # m.draw_meridians(np.linspace(ra-2*radius,ra+2*radius,5),
            #                  labelstyle='+/-',labels=[0,0,0,1])
            plt.title('Zoom to Fit (%s)' % cls.__name__)
Beispiel #6
0
def plot_bliss_coverage(fields, outfile=None, **kwargs):
    BANDS = ['g', 'r', 'i', 'z']
    filename = fileio.get_datafile('bliss-target-fields.csv')
    target = FieldArray.read(filename)
    target = target[~np.in1d(target.unique_id, fields.unique_id)]

    fig, ax = plt.subplots(2, 2, figsize=(16, 9))
    plt.subplots_adjust(wspace=0.01,
                        hspace=0.02,
                        left=0.01,
                        right=0.99,
                        bottom=0.01,
                        top=0.99)
    defaults = dict(edgecolor='none', s=12, alpha=0.2, vmin=-1, vmax=2)
    setdefaults(kwargs, defaults)

    for i, b in enumerate(BANDS):
        plt.sca(ax.flat[i])

        f = fields[fields['FILTER'] == b]
        t = target[target['FILTER'] == b]

        bmap = DECamMcBride()
        bmap.draw_des()
        bmap.draw_galaxy(10)

        proj = bmap.proj(t['RA'], t['DEC'])
        bmap.scatter(*proj, c='0.7', **kwargs)

        proj = bmap.proj(f['RA'], f['DEC'])
        bmap.scatter(*proj, c=f['TILING'], cmap=CMAPS[b], **kwargs)
        plt.gca().set_title('BLISS %s-band' % b)
Beispiel #7
0
    def plot(self, color_line='r', bgcolor='grey', color='yellow', lw=4, 
            hold=False, ax=None):

        xmax = self.xmax + 1
        if ax:
            pylab.sca(ax)
        pylab.fill_between([0,xmax], [0,0], [20,20], color='red', alpha=0.3)
        pylab.fill_between([0,xmax], [20,20], [30,30], color='orange', alpha=0.3)
        pylab.fill_between([0,xmax], [30,30], [41,41], color='green', alpha=0.3)

        if self.X is None:
            X = range(1, self.xmax + 1)

        pylab.fill_between(X, 
            self.df.mean()+self.df.std(), 
            self.df.mean()-self.df.std(), 
            color=color, interpolate=False)

        pylab.plot(X, self.df.mean(), color=color_line, lw=lw)
        pylab.ylim([0, 41])
        pylab.xlim([0, self.xmax+1])
        pylab.title("Quality scores across all bases")
        pylab.xlabel("Position in read (bp)")
        pylab.ylabel("Quality")
        pylab.grid(axis='x')
 def finish_trajectory_plot(self,axes,t,filename):
 
     # Plot histograms! 0 is the upper panel, 1 the lower.
     plt.sca(axes[1])
     
     bins = np.linspace(np.log10(swap.pmin),np.log10(swap.pmax),32,endpoint=True)
     bins = 10.0**bins
     colors = ['blue','red','black']
     labels = ['Training: Sims','Training: Duds','Test: Survey']
     
     for j,kind in enumerate(['sim','dud','test']):
         
         self.collect_probabilities(kind)
         p = self.probabilities[kind]
         
         # Sometimes all probabilities are lower than pmin! 
         # Snap to grid.
         p[p<swap.pmin] = swap.pmin
         # print "kind,bins,p = ",kind,bins,p
         
         # Pylab histogram:
         plt.hist(p, bins=bins, histtype='stepfilled', color=colors[j], alpha=0.7, label=labels[j])
         plt.legend(prop={'size':10})
     
     # Add timestamp in top righthand corner:
     plt.sca(axes[0])
     plt.text(1.3*swap.prior,0.27,t,color='gray')
     
     # Write out to file:
     plt.savefig(filename,dpi=300)
         
     return
Beispiel #9
0
def plotWeights(date, target_fields, weights, options_basemap={}, **kwargs):
    defaults = dict(c=weights,
                    edgecolor='none',
                    s=50,
                    vmin=np.min(weights),
                    vmax=np.min(weights) + 300.,
                    cmap='Spectral')
    setdefaults(kwargs, defaults)

    defaults = dict(date=date, name='ortho')
    options_basemap = dict(options_basemap)
    setdefaults(options_basemap, defaults)
    fig, basemap = makePlot(**options_basemap)

    proj = basemap.proj(target_fields['RA'], target_fields['DEC'])
    basemap.scatter(*proj, **kwargs)

    # Try to draw the colorbar
    try:
        if len(fig.axes) == 2:
            # Draw colorbar in existing axis
            colorbar = plt.colorbar(cax=fig.axes[-1])
        else:
            colorbar = plt.colorbar()
        colorbar.set_label('Tiling')
    except TypeError:
        pass
    plt.sca(fig.axes[0])
Beispiel #10
0
def plot_ima_mass_matrix(start, finish, product=None, colorbar=True, ax=None, blocks=None, **kwargs):
    """ Integrate to produce a mass-matrix from start-finish, processing azimuths"""

    if (finish - start) < aspera_scan_time:
        raise ValueError("Duration too short: %d" % (finish - start))

    if not blocks:
        blocks = read_ima(start, finish, **kwargs)

    if ax is None:
        ax = plt.gca()

    plt.sca(ax)

    products_to_process = ("CO2", "H", "O", "Hsp", "alpha", "O2", "He")
    if product:
        if not hasattr(product, "__iter__"):
            products_to_process = [product]
        else:
            products_to_process = product

    img = np.zeros_like(blocks[0]["sumions"])

    for b in blocks:
        inx, = np.where((b["tmptime"] > start) & (b["tmptime"] < finish))
        if inx.shape[0]:
            for p in products_to_process:
                img += np.sum(b[p][:, :, inx], 2)

    plt.imshow(img, origin="lower")
    if colorbar:
        plt.colorbar(cax=celsius.make_colorbar_cax())

    return img
Beispiel #11
0
    def draw_inset_colorbar(self,
                            format=None,
                            label=None,
                            ticks=None,
                            fontsize=11,
                            **kwargs):
        defaults = dict(width="25%",
                        height="5%",
                        loc=7,
                        bbox_to_anchor=(0., -0.04, 1, 1))
        setdefaults(kwargs, defaults)

        ax = plt.gca()
        im = plt.gci()
        cax = inset_axes(ax, bbox_transform=ax.transAxes, **kwargs)
        cmin, cmax = im.get_clim()

        if (ticks is None) and (cmin is not None) and (cmax is not None):
            cmed = (cmax + cmin) / 2.
            delta = (cmax - cmin) / 10.
            ticks = np.array([cmin + delta, cmed, cmax - delta])

        tmin = np.min(np.abs(ticks[0]))
        tmax = np.max(np.abs(ticks[1]))

        if format is None:
            if (tmin < 1e-2) or (tmax > 1e3):
                format = '$%.1e$'
            elif (tmin > 0.1) and (tmax < 100):
                format = '$%.1f$'
            elif (tmax > 100):
                format = '$%i$'
            else:
                format = '$%.2g$'
                #format = '%.2f'

        kwargs = dict(format=format, ticks=ticks, orientation='horizontal')

        if format == 'custom':
            ticks = np.array([cmin, 0.85 * cmax])
            kwargs.update(format='$%.0e$', ticks=ticks)

        cbar = plt.colorbar(cax=cax, **kwargs)
        cax.xaxis.set_ticks_position('top')
        cax.tick_params(axis='x', labelsize=fontsize)

        if format == 'custom':
            ticklabels = cax.get_xticklabels()
            for i, l in enumerate(ticklabels):
                val, exp = ticklabels[i].get_text().split('e')
                ticklabels[i].set_text(r'$%s \times 10^{%i}$' %
                                       (val, int(exp)))
            cax.set_xticklabels(ticklabels)

        if label is not None:
            cbar.set_label(label, size=fontsize)
            cax.xaxis.set_label_position('top')

        plt.sca(ax)
        return cbar, cax
Beispiel #12
0
def onMouseClick(event):
    """Реагирует на клик мыши по графику"""
    axes = event.inaxes

    # Если кликнули вне графика, то не будем ничего делать
    if axes is None:
        return

    global marker
    global marker_x
    global marker_y
    # Если маркер с текстом уже был создан, то удалим его и все остальные
    if marker is not None:
        marker_x.remove()
        marker_y.remove()
        marker.remove()

    # В качестве текущих выберем оси, внутри которых кликнули мышью
    pylab.sca(axes)

    # Координаты клика в системе координат осей
    xx = event.xdata
    yy = event.ydata
    text = u'({:.3f}; {:.3f})'.format(xx, yy)

    # Выведем текст в точку, куда кликнули и рисуем перекрестье
    marker = pylab.text(xx, yy, text)
    marker_x = pylab.axvline(x=xx, c='r')
    marker_y = pylab.axhline(y=yy, c='r')

    # Обновим график
    pylab.show()
Beispiel #13
0
    def plot_path(self, axes, path, rendering_style=None, animate=False):
        plt.sca(axes)
        edges = zip(path, path[1:])

        if rendering_style is None:
            thisRendering = MatplotLibMap.renderingRules['calculated_path']
        else:
            thisRendering = rendering_style

        for i, edge in enumerate(edges):
            node_from = self._osm.nodes[edge[0]]
            node_to = self._osm.nodes[edge[1]]
            x_from = node_from.lon
            y_from = node_from.lat
            x_to = node_to.lon
            y_to = node_to.lat

            plt.plot(
                [x_from, x_to],
                [y_from, y_to],
                marker='',
                linestyle=thisRendering['linestyle'],
                linewidth=thisRendering['linewidth'],
                color=thisRendering['color'],
                solid_capstyle='round',
                solid_joinstyle='round',
                zorder=thisRendering['zorder'],
            )

            if animate:
                plt.draw()

        plt.draw()
def animate(i):
    # Animation function
    # This function is called frame_rate*tfinal times
    # Simulation has Nt steps
    # So, animation should be called every Nt/(frame_rate*tfinal) steps.

    fct_adj = int(Nt / (frame_rate * tfinal))

    for np in range(Np):

        x1 = r_um[0, np, i * fct_adj]
        y1 = r_um[1, np, i * fct_adj]
        z1 = r_um[2, np, i * fct_adj]
        beads_xy[np].center = (x1, y1)
        beads_yz[np].center = (y1, z1)
        beads_xz[np].center = (x1, z1)

        # print(i)
    #py.text(0,100,'time, t =',fontsize=12)
    time_string.set_text(
        time_template %
        (i * fct_adj * delta_t))  # Adjust time display by fct_adj factor
    py.sca(ax1)
    draw_geo(i * fct_adj * delta_t, ax1, ax2, ax3)

    return beads_xy
Beispiel #15
0
    def tsmaps(self):
        """TS maps for the spectral templates

        Each has 12*512**2 = 3.2M pixels. The following table has the number of pixels above the TS value labeling the column.
        %(tsmap_info)s
        """
        z = dict()
        cuts = (10, 16, 25, 100)
        keys = self.keys
        for key in keys:
            z[key] = [np.sum(self.tables[key] > x) for x in cuts]
        df = pd.DataFrame(z, index=cuts).T
        self.tsmap_info = html_table(
            df,
            href=False,
        )

        fig, axx = plt.subplots(2, 3, figsize=(18, 15))
        plt.subplots_adjust(hspace=-0.4, wspace=0.05, left=0.05)
        for ax, key in zip(axx.flatten(), keys):
            plt.sca(ax)
            healpy.mollview(self.tables[key],
                            hold=True,
                            min=10,
                            max=25,
                            title=key,
                            cbar=True,
                            cmap=plt.get_cmap('YlOrRd'))
            healpy.graticule(dmer=180, dpar=90, color='lightgrey')
        axx[1, 2].set_visible(False)
        return fig
Beispiel #16
0
 def test_skymap(self):
     fig, axes = plt.subplots(1, 3, figsize=(12, 3))
     for i, cls in enumerate(SKYMAPS):
         plt.sca(axes[i])
         m = cls()
         m.draw_milky_way()
         plt.title('Galactic Plane (%s)' % cls.__name__)
Beispiel #17
0
    def draw_SD_points(self,
                       ax,
                       color='g',
                       edgecolor='k',
                       marker='o',
                       size=10,
                       extra=False,
                       zorder=1):
        '''
        draw the locations of all the semidual sites
        
        if extra is True it will draw only the edge sites required to fix the edge of the tiling
        '''
        if extra == True:
            xs = self.extraSDx
            ys = self.extraSDy
        else:
            xs = self.SDx
            ys = self.SDy

        pylab.sca(ax)
        pylab.scatter(xs,
                      ys,
                      c=color,
                      s=size,
                      marker=marker,
                      edgecolors=edgecolor,
                      zorder=zorder)

        return
Beispiel #18
0
def plot_any_band_cut(ax, cut, connected=True):

    colorlist = [
        'firebrick', 'dodgerblue', 'blueviolet', 'mediumblue', 'goldenrod',
        'cornflowerblue'
    ]

    pylab.sca(ax)

    shape = cut.shape

    for ind in range(0, shape[0]):
        colorInd = numpy.mod(ind, len(colorlist))
        if connected:
            pylab.plot(cut[ind, :],
                       color=colorlist[colorInd],
                       marker='',
                       markersize='5',
                       linestyle='-',
                       linewidth=3.5)
        else:
            pylab.plot(cut[ind, :],
                       color=colorlist[colorInd],
                       marker='.',
                       markersize='5',
                       linestyle='')

    pylab.title('some momentum cut')
    pylab.ylabel('Energy')
    pylab.xlabel('k_something')

    return
Beispiel #19
0
    def draw_resonator_end_points(self,
                                  ax,
                                  color='g',
                                  edgecolor='k',
                                  marker='o',
                                  size=10,
                                  zorder=1):
        '''will double draw some points'''
        x0s = self.resonators[:, 0]
        y0s = self.resonators[:, 1]

        x1s = self.resonators[:, 2]
        y1s = self.resonators[:, 3]

        pylab.sca(ax)
        pylab.scatter(x0s,
                      y0s,
                      c=color,
                      s=size,
                      marker=marker,
                      edgecolors=edgecolor,
                      zorder=zorder)
        pylab.scatter(x1s,
                      y1s,
                      c=color,
                      s=size,
                      marker=marker,
                      edgecolors=edgecolor,
                      zorder=zorder)
        return
Beispiel #20
0
def setupplot(secondax=False, **kwargs):
    ytickv = np.linspace(YR[0],YR[1],6)
    yticknames = map('{:0.0f}'.format, ytickv)
    tmp = dict(
        ylabel='Temperature [c]',
        yr=minmax(ytickv), ytickv=ytickv,
        yticknames=yticknames,
    )
    tmp.update(kwargs)
    ax = setup(**tmp)
    
    if secondax:
        subplt = kwargs.get('subplt',None)
        f = lambda x: '{:0.0f}'.format(1.8*x + 32.0)
        yticknames = map(f, ytickv)
        ax2 = ax.twinx()
        ax2.set_ylabel(r"Temperature [F]")
        ax2.set_ylim(minmax(ytickv))
        ax2.yaxis.set_major_locator(matplotlib.ticker.FixedLocator(ytickv))
        ax2.yaxis.set_major_formatter(matplotlib.ticker.FixedFormatter(yticknames))
        pylab.sca(ax)
        
        # setup(ax=ax.twinx(),
        #       subplt=subplt,
        #       ylabel='Temperature [F]',
        #       yr=minmax(ytickv), ytickv=ytickv, yticknames=yticknames)
        
    
    return ax
Beispiel #21
0
    def plot(self,
             color_line='r',
             bgcolor='grey',
             color='yellow',
             lw=4,
             hold=False,
             ax=None):

        xmax = self.xmax + 1
        if ax:
            pylab.sca(ax)
        pylab.fill_between([0, xmax], [0, 0], [20, 20], color='red', alpha=0.3)
        pylab.fill_between([0, xmax], [20, 20], [30, 30],
                           color='orange',
                           alpha=0.3)
        pylab.fill_between([0, xmax], [30, 30], [41, 41],
                           color='green',
                           alpha=0.3)

        if self.X is None:
            X = range(1, self.xmax + 1)

        pylab.fill_between(X,
                           self.df.mean() + self.df.std(),
                           self.df.mean() - self.df.std(),
                           color=color,
                           interpolate=False)

        pylab.plot(X, self.df.mean(), color=color_line, lw=lw)
        pylab.ylim([0, 41])
        pylab.xlim([0, self.xmax + 1])
        pylab.title("Quality scores across all bases")
        pylab.xlabel("Position in read (bp)")
        pylab.ylabel("Quality")
        pylab.grid(axis='x')
Beispiel #22
0
def animate(index, data, ax1):
    print(index, inv.log['plasma_iter'][index])
    color = cycle(sns.color_palette('Set3', 2 + len(inv.sf.coil)))
    pl.sca(ax1)
    ax1.cla()
    ax1.set_axis_off()
    ax1.set_xlim([2, 18])
    ax1.set_ylim((-15.0, 10.0))
    #pl.axis('equal')

    pl.tight_layout()

    #sf.coil = inv.log['sf_coil'][index]
    #sf.plasma_coil = inv.log['plasma_coil'][inv.log['plasma_iter'][index]-1]
    #eq.b = inv.log['b'][inv.log['plasma_iter'][index]-1]
    inv.eq.coil = inv.log['eq_coil'][index]
    inv.coil = inv.log['inv_coil'][index]

    #inv.set_force_feild(state='both')  # update force feild
    #inv.swing_fix(inv.Swing[0])
    #inv.solve_slsqp()

    #eq.run(update=False)
    #sf.contour(lw=1.25)

    inv.plot_coils()
    #sf.plot_coils(color=color,coils=sf.coil,label=True,plasma=False)
    sf.plot_coils(color=color, coils=eq.coil, label=False, plasma=False)
    #inv.plot_fix()
    #inv.rb.TFopp(False)  # L==length, V==volume
    inv.rb.TFfill()
Beispiel #23
0
 def ScatterPSFCommon(self, arg):
     """
     Display function that you shouldn't call directly.
     """
     w = np.where(self.goodStars)[0]
     W = np.where(self.goodStars != True)
     ##ca=pyl.gca()
     pyl.sca(self.sp1)
     xlim = self.sp1.get_xlim()
     ylim = self.sp1.get_ylim()
     title = self.sp1.get_title()
     self.sp1.cla()
     pyl.scatter(self.points[:, 0][w],
                 self.points[:, 1][w],
                 color='b',
                 picker=True,
                 zorder=9)
     pyl.scatter(self.points[:, 0][W],
                 self.points[:, 1][W],
                 picker=True,
                 color='r',
                 zorder=10)
     pyl.scatter(self.points[:, 0][arg],
                 self.points[:, 1][arg],
                 marker='d',
                 color='m',
                 zorder=0,
                 s=75)
     pyl.axis([xlim[0], xlim[1], ylim[0], ylim[1]])
     pyl.title(title)
Beispiel #24
0
 def plot_ash_infill(self, ax=None, color='#92B2E7', density=True):
     ax = ax if ax else plt.gca()
     self.hist_max = 0
     for i in range(self.shift_num):
         hist_range = (self.MIN + i * self.SHIFT,
                       self.MAX + i * self.SHIFT - self.bin_width)
         self.hist_range = hist_range
         hist, bin_edges = np.histogram(self.data,
                                        self.bin_num + 1,
                                        range=hist_range,
                                        density=density)
         self.hist_max = (max(hist)
                          if max(hist) > self.hist_max else self.hist_max)
         n, bin_edges, patches = ax.hist(self.data,
                                         self.bin_num + 1,
                                         range=hist_range,
                                         histtype='stepfilled',
                                         alpha=0.75 / self.shift_num,
                                         color=color,
                                         linewidth=0,
                                         density=density,
                                         rasterized=True)
     ymin, ymax = ax.get_ylim()
     xmin, xmax = ax.get_xlim()
     self.hist_max += self.hist_max * 0.1
     ymax = ymax if ymax > self.hist_max else self.hist_max
     ax.set_ylim(ymin, ymax)
     plt.sca(ax)
Beispiel #25
0
def setupplot(secondax=False, **kwargs):
    ytickv = np.linspace(YR[0], YR[1], 6)
    yticknames = map('{:0.0f}'.format, ytickv)
    tmp = dict(
        ylabel='Temperature [c]',
        yr=minmax(ytickv),
        ytickv=ytickv,
        yticknames=yticknames,
    )
    tmp.update(kwargs)
    ax = setup(**tmp)

    if secondax:
        subplt = kwargs.get('subplt', None)
        f = lambda x: '{:0.0f}'.format(1.8 * x + 32.0)
        yticknames = map(f, ytickv)
        ax2 = ax.twinx()
        ax2.set_ylabel(r"Temperature [F]")
        ax2.set_ylim(minmax(ytickv))
        ax2.yaxis.set_major_locator(matplotlib.ticker.FixedLocator(ytickv))
        ax2.yaxis.set_major_formatter(
            matplotlib.ticker.FixedFormatter(yticknames))
        pylab.sca(ax)

        # setup(ax=ax.twinx(),
        #       subplt=subplt,
        #       ylabel='Temperature [F]',
        #       yr=minmax(ytickv), ytickv=ytickv, yticknames=yticknames)

    return ax
Beispiel #26
0
 def plot_time_course(self, data, mode='boolean', fontsize=16):
     # TODO sort columnsi alphabetically
     # FIXME: twiny labels are slightly shifted
     # TODO flip 
     if mode == 'boolean':
         cm = pylab.get_cmap('gray')
         pylab.clf() 
         data = pd.DataFrame(data).fillna(0.5)
         pylab.pcolor(data, cmap=cm, vmin=0, vmax=1, 
             shading='faceted')
         pylab.colorbar()
         ax1 = pylab.gca()
         ax1.set_xticks([])
         Ndata = len(data.columns)
         ax1.set_xlim(0, Ndata)
         ax = pylab.twiny()
         ax.set_xticks(pylab.linspace(0.5, Ndata+0.5, Ndata ))
         ax.set_xticklabels(data.columns, fontsize=fontsize, rotation=90)
         times = list(data.index)
         Ntimes = len(times)
         ax1.set_yticks([x+0.5 for x in times])
         ax1.set_yticklabels(times[::-1],  
                 fontsize=fontsize)
         pylab.sca(ax1)
     else:
         print('not implemented')
Beispiel #27
0
    def draw_inset_colorbar(self, format=None):
        ax = plt.gca()
        im = plt.gci()
        cax = inset_axes(ax, width="25%", height="5%", loc=7)
        cmin, cmax = im.get_clim()
        cmed = (cmax + cmin) / 2.
        delta = (cmax - cmin) / 10.

        ticks = np.array([cmin + delta, cmed, cmax - delta])
        tmin = np.min(np.abs(ticks[0]))
        tmax = np.max(np.abs(ticks[1]))

        if format is None:
            if (tmin < 1e-2) or (tmax > 1e3):
                format = '%.1e'
            elif (tmin > 0.1) and (tmax < 100):
                format = '%.1f'
            elif (tmax > 100):
                format = '%i'
            else:
                format = '%.2g'

        cbar = plt.colorbar(cax=cax,
                            orientation='horizontal',
                            ticks=ticks,
                            format=format)
        cax.xaxis.set_ticks_position('top')
        cax.tick_params(axis='x', labelsize=10)
        plt.sca(ax)
        return cbar
Beispiel #28
0
def extract_corners(im_rot):
    plot = False

    pts = get_corners_of_piece(im_rot)

    centre = np.mean(np.array(pts), axis=0)
    corner_size = (30, 30)
    if plot:
        f, axes = pylab.subplots(2, 2)
        axes = [axes[0][0], axes[0][1], axes[1][0], axes[1][1]]
    #print x>centre[0], y>centre[1]
    pts = sorted(pts, key=lambda pt: (pt[0] > centre[0], pt[1] > centre[1]))
    for i, (x, y) in enumerate(pts):
        pylab.sca(axes[i])
        print x > centre[0], y > centre[1]

        xmin, xmax = x - corner_size[0], x + corner_size[0]
        ymin, ymax = y - corner_size[1], y + corner_size[1]

        xmin = np.clip(xmin, 0, im_rot.shape[0])
        ymin = np.clip(ymin, 0, im_rot.shape[1])
        xmax = np.clip(xmax, 0, im_rot.shape[0] - 1)
        ymax = np.clip(ymax, 0, im_rot.shape[1] - 1)

        corner = im_rot[xmin:xmax, ymin:ymax]

        if plot:
            imshow(corner.T)
            axes[i].plot([corner_size[0]], [corner_size[1]])
Beispiel #29
0
 def set_plot(self, ax, fignum, figsize=(4, 4)):
     if ax is None:
         plt.close(fignum)
         plt.figure(fignum, figsize=figsize)
         ax = plt.gca()
     else:
         plt.sca(ax)
     return ax
Beispiel #30
0
def plot(ax,data,scatter=False):
    pl.sca(ax)
    pl.cla()
    ax.set_xticks(pos_x)
    ax.xaxis.set_ticklabels([])
    pl.xlim(min(pos_x),max(pos_x))
    ax.grid(b=True,which='both',color='k',linestyle='-')
    ax.set_aspect('equal', adjustable='box')
Beispiel #31
0
    def render(self, axes, plot_nodes=False):
        plt.sca(axes)
        for idx, nodeID in enumerate(self._osm.ways.keys()):
            wayTags = self._osm.ways[nodeID].tags
            wayType = None
            if 'highway' in wayTags.keys():
                wayType = wayTags['highway']

            if wayType in [
                           'primary',
                           'primary_link',
                           'unclassified',
                           'secondary',
                           'secondary_link',
                           'tertiary',
                           'tertiary_link',
                           'residential',
                           'trunk',
                           'trunk_link',
                           'motorway',
                           'motorway_link'
                            ]:
                oldX = None
                oldY = None

                if wayType in list(MatplotLibMap.renderingRules.keys()):
                    thisRendering = MatplotLibMap.renderingRules[wayType]
                else:
                    thisRendering = MatplotLibMap.renderingRules['default']

                for nCnt, nID in enumerate(self._osm.ways[nodeID].nds):
                    y = float(self._osm.nodes[nID].lat)
                    x = float(self._osm.nodes[nID].lon)

                    self._node_map[(x, y)] = nID

                    if oldX is None:
                        pass
                    else:
                        plt.plot([oldX,x],[oldY,y],
                                marker          = '',
                                linestyle       = thisRendering['linestyle'],
                                linewidth       = thisRendering['linewidth'],
                                color           = thisRendering['color'],
                                solid_capstyle  = 'round',
                                solid_joinstyle = 'round',
                                zorder          = thisRendering['zorder'],
                                picker=2
                        )

                        if plot_nodes == True and (nCnt == 0 or nCnt == len(self._osm.ways[nodeID].nds) - 1):
                            plt.plot(x, y,'ro', zorder=5)

                    oldX = x
                    oldY = y

        self._fig.canvas.mpl_connect('pick_event', self.__onclick__)
        plt.draw()
Beispiel #32
0
    def plotsim(self, experiments=None, fontsize=16, vmin=0, vmax=1, cmap='gray'):
        """

        :param experiments: if None, shows the steady state for each experiment and species
            if provided, must be a valid experiment name (see midas.experiments attribute)
            in which case, for that particular experiment, the steady state and all previous
            states are shown for each species.


        A simulation must be performed using :meth:`simulate`
        ::

            # those 2 calls are identical
            s.plotsim(experiments=8)
            s.plotsim(experiments=8)
            # This plot the steady states for all experiments
            s.plotsim()

        """
        # This is for all experiments is experiments is None
        cm = pylab.get_cmap(cmap)
        pylab.clf()

        if experiments is None: # takes the latest (steady state) of each experiments
            data = pd.DataFrame(self.debug_values[-1]).fillna(0.5)
        else:
            exp_name = self.midas.experiments.ix[experiments].name
            index_exp = list(self.midas.experiments.index).index(exp_name)

            data = [(k, [self.debug_values[i][k][index_exp] for i in range(0, len(self.debug_values))])
                    for k in self.debug_values[0].keys()]
            data = dict(data)
            data = pd.DataFrame(data).fillna(0.5)
            data = data.ix[data.index[::-1]]
        self.dummy = data

        pylab.pcolor(data, cmap=cm, vmin=vmin, vmax=vmax,
                shading='faceted', edgecolors='gray')
        pylab.colorbar()
        ax1 = pylab.gca()
        ax1.set_xticks([])
        Ndata = len(data.columns)
        ax1.set_xlim(0, Ndata)
        ax1.set_ylim(0, len(data))
        ax = pylab.twiny()

        # FIXME seems shifted. could not fix it xticklabels seems to reset the position of the ticks
        xr = pylab.linspace(0.5, Ndata-1.5, Ndata)
        ax.set_xticks(xr)
        ax.set_xticklabels(data.columns, fontsize=fontsize, rotation=90)
        times = list(data.index)
        Ntimes = len(times)
        ax1.set_yticks([x+0.5 for x in times])
        ax1.set_yticklabels(times[::-1],
                    fontsize=fontsize)
        pylab.sca(ax1)
        #pylab.title("Steady state for all experiments(x-axis)\n\n\n\n")
        pylab.tight_layout()
Beispiel #33
0
    def ScatterPSF(self, event):
        """
        Display function that you shouldn't call directly.
        """

        ca = pyl.gca()
        if event is not None:
            me = event.mouseevent

        if self.starsScat != None:
            self.starsScat.remove()
            self.starsScat = None

        npoints = len(self.points[:, 0])
        showingbool = np.array(self.showing).astype(np.bool)
        pointsshowing = self.points[showingbool, :]
        ranks = np.zeros(len(pointsshowing[:, 0]))
        if event is not None:
            args = np.argsort(np.abs(me.xdata - pointsshowing[:, 0]))
        else:
            args = np.argsort(np.abs(0.0 - pointsshowing[:, 0]))
        for ii in range(len(args)):
            ranks[args[ii]] += ii
        if event is not None:
            args = np.argsort(np.abs(me.ydata - pointsshowing[:, 1]))
        else:
            args = np.argsort(np.abs(0.0 - pointsshowing[:, 1]))
        for ii in range(len(args)):
            ranks[args[ii]] += ii

        args = np.arange(npoints)[showingbool]
        self.selected_star = np.argmin(ranks[np.argsort(pointsshowing[:, 0])])
        arg = args[np.argsort(pointsshowing[:, 0])[self.selected_star]]

        self.starsScat = self.sp4.scatter(self.starsFlatR[arg],
                                          self.starsFlatF[arg],
                                          facecolor='none',
                                          edgecolor='b',
                                          zorder=10)
        self.sp4.set_xlim(0, self.moffatWidth)
        self.sp4.set_ylim(0, 1.02)

        self.sp5.imshow(self.subsecs[arg])
        #self.sp5.set_xlabel("x,y = {:.1f}, {:.1f}".format(self.points[:, 4][arg],self.points[:, 5][arg]))

        self.ScatterPSFCommon(arg)

        if event is not None:
            if me.button == 3:
                self.goodStars[arg] = not self.goodStars[arg]
                self.ScatterPSFCommon(arg)

        self.conn1 = self.sp1.callbacks.connect('ylim_changed', self.PSFrange)
        self.conn3 = pyl.connect('key_press_event', self.ScatterPSF_keys)
        ## The above two lines need to be here again.
        ## This allows for zooming/inspecting in whatever order, over & over.
        pyl.sca(ca)
        pyl.draw()
Beispiel #34
0
    def plot_trajectory(self, axes):

        plt.sca(axes[0])
        N = np.linspace(0,
                        len(self.trajectory) / Ntrajectory + 1,
                        len(self.trajectory) / Ntrajectory,
                        endpoint=True)
        N[0] = 0.5
        mdn_trajectory = np.array([])
        sigma_trajectory_m = np.array([])
        sigma_trajectory_p = np.array([])
        for i in range(len(N)):
            sorted_arr = np.sort(self.trajectory[i * Ntrajectory:(i + 1) *
                                                 Ntrajectory])
            sigma_p = sorted_arr[int(0.84 * Ntrajectory)] - sorted_arr[int(
                0.50 * Ntrajectory)]
            sigma_m = sorted_arr[int(0.50 * Ntrajectory)] - sorted_arr[int(
                0.16 * Ntrajectory)]
            mdn_trajectory = np.append(mdn_trajectory,
                                       sorted_arr[int(0.50 * Ntrajectory)])
            sigma_trajectory_p = np.append(sigma_trajectory_p, sigma_p)
            sigma_trajectory_m = np.append(sigma_trajectory_m, sigma_m)

        if self.kind == 'sim':
            colour = 'blue'
        elif self.kind == 'dud':
            colour = 'red'
        elif self.kind == 'test':
            colour = 'black'

        if self.status == 'undecided':
            facecolour = colour
        else:
            facecolour = 'white'

        plt.plot(mdn_trajectory,
                 N,
                 color=colour,
                 alpha=0.1,
                 linewidth=1.0,
                 linestyle="-")

        NN = N[-1]
        if NN > swap.Ncmax: NN = swap.Ncmax
        plt.scatter(mdn_trajectory[-1],
                    NN,
                    edgecolors=colour,
                    facecolors=facecolour,
                    alpha=0.5)
        plt.plot([
            mdn_trajectory[-1] - sigma_trajectory_m[-1],
            mdn_trajectory[-1] + sigma_trajectory_p[-1]
        ], [NN, NN],
                 color=colour,
                 alpha=0.3)
        # if self.kind == 'sim': print self.trajectory[-1], N[-1]

        return
Beispiel #35
0
def prob_plot(all_p):
    """
    4D array: Taste x Trials x Nrns x State
    Generates swarmplots with trials as dots, different states colored and different nrns
    along the x axis
    Different tastes are placed in different subplots
    """
    count = 0
    all_p_frame = pd.DataFrame()
    for taste in range(all_p.shape[0]):
        for trial in range(all_p.shape[1]):
            for nrn in range(all_p.shape[2]):
                for state in range(all_p.shape[3]):
                    this_point = {
                        'taste': taste,
                        'trial': trial,
                        'neuron': nrn,
                        'state': state,
                        'firing_p': all_p[taste, trial, nrn, state]
                    }
                    all_p_frame = pd.concat(
                        [all_p_frame,
                         pd.DataFrame(this_point, index=[count])])
                    count += 1

# =============================================================================
#     fig, ax = plt.subplots(nrows = all_p.shape[0], ncols = 1, sharey = True)
#     for taste in range(all_p.shape[0]):
#         #plt.subplot(all_p.shape[0],1,taste+1)
#         plt.sca(ax[taste])
#         sns.boxplot(data = all_p_frame.query('taste == %i' % taste), x = 'neuron', y = 'firing_p',hue = 'state',dodge=True)
#
# =============================================================================
    count = 0
    nrows = np.int(np.floor(np.sqrt(all_p.shape[2])))
    ncols = np.int(np.ceil(all_p.shape[2] / nrows))
    fig, ax = plt.subplots(nrows=nrows, ncols=ncols, sharey=True)
    for rows in range(nrows):
        for cols in range(ncols):
            if count >= all_p.shape[2]:
                break
            plt.sca(ax[rows, cols])
            #ax = plt.gca()
            #ax.legend_ = None
            #plt.draw()
            #ax[rows,cols].legend().set_visible(False)
            this_plot = sns.boxplot(data=all_p_frame.query('neuron == %i' %
                                                           count),
                                    x='state',
                                    y='firing_p',
                                    hue='taste',
                                    dodge=True)
            this_plot.legend_ = None
            plt.draw()
            count += 1

    return fig
Beispiel #36
0
def add_subplot_name(offsets, subplot_names="abcdefghijklmnopq"):
    if len(offsets) != 2:
        raise Exception("Offsets for x and y coordinates should be provided")
    for iax, ax in enumerate(pylab.gcf().axes):
        pylab.sca(ax)
        pylab.text(offsets[0],
                   1. + offsets[1],
                   "({})".format(subplot_names[iax]),
                   transform=pylab.gca().transAxes)
Beispiel #37
0
 def decorator(ax=None):
     ax1 = ax if ax else gca()
     ax2 = ax1.twiny()
     ax2.set_ylim(y for y in ax1.get_ylim())
     ax2.set_xlim(func(x) for x in ax1.get_xlim())
     if not ax:
         sca(ax1)
         draw()
     return ax2
Beispiel #38
0
def plot_mex_orbits_bar(start=None, finish=None, ax=None, height=0.02, number_every=10, sharex=False, labels=True):
    """docstring for plot_mex_orbits_bar"""

    fig = plt.gcf()
    if ax is None:
        ax = plt.gca()

    xlims = plt.xlim()

    p = ax.get_position()
    if sharex:
        if isinstance(sharex, bool):
            sharex = ax
    else:
        sharex = None
    new_ax = fig.add_axes([p.x0, p.y1, p.x1 - p.x0, height], sharex=sharex)

    if start is None:
        start = xlims[0]
    if finish is None:
        finish = xlims[1]

    plt.xlim(start, finish)
    plt.ylim(0., 1.)

    x = np.array([1., 0., 0., 1., 1.])
    y = np.array([1., 1., 0., 0., 1.])

    orbit_count = 0
    orbit_list = list(mex.orbits.values())
    for o in orbit_list:
        if o.number % 2 == 0:
            continue
        if (o.start < finish) & (o.finish > start):
            dx = o.finish - o.start
            plt.fill(x * dx + o.start, y, 'k', edgecolor='none')
            orbit_count = orbit_count + 1

    if number_every is None:
        number_every = int(orbit_count / 10)

    if number_every:
        numbered_orbits = [o for o in orbit_list if (o.number % number_every) == 0]

    ticks = [o.periapsis for o in numbered_orbits]
    nums  = [o.number for o in numbered_orbits]
    new_ax.yaxis.set_major_locator(mpl.ticker.NullLocator())

    new_ax.xaxis.set_major_locator(mpl.ticker.FixedLocator(ticks))
    new_ax.xaxis.set_major_formatter(mpl.ticker.FixedFormatter(nums))
    # new_ax.xaxis.set_major_locator(mpl.ticker.MaxNLocator(nbins=5, steps=[1,2,5,10]))
    new_ax.tick_params(axis='x', direction='out', bottom=False, top=True, labelbottom=False, labeltop=True)
    if labels:
        plt.ylabel("MEX", rotation='horizontal')

    plt.sca(ax)
    return new_ax
Beispiel #39
0
 def test_draw_explicit_hpxmap(self):
     """ Test an explicit healpix map """
     pix = hpxmap = np.arange(525, 535)
     fig, axes = plt.subplots(1, 3, figsize=(12, 3))
     for i, cls in enumerate(SKYMAPS):
         plt.sca(axes[i])
         m = cls()
         m.draw_hpxmap(hpxmap, pix, nside, xsize=400)
         plt.title('Partial HEALPix Map (%s)' % cls.__name__)
Beispiel #40
0
    def __onclick__(self, event):
        threshold = 0.001
        print("Clicked mouse")

        if self._node1 is not None and self._node2 is not None:
            return None

        if isinstance(event.artist, Line2D):
            thisline = event.artist
            xdata = thisline.get_xdata()
            ydata = thisline.get_ydata()
            ind = event.ind
            point = (float(np.take(xdata, ind)[0]), float(np.take(ydata, ind)[0]))
            node_id = self._node_map[point]

            if self._node1 is None:
                self._node1 = Node(node_id, point[0], point[1])
                self._mouse_click1 = (event.mouseevent.xdata, event.mouseevent.ydata)

                for axes in self._main_rendering_axes:
                    plt.sca(axes)
                    plt.plot(self._mouse_click1[0], self._mouse_click1[1], 'ro', zorder=100)

                plt.draw()
                return self._node1
            else:
                # Do not allow clicking of node id's within 100 node distances
                if abs(point[0] - self._node1.lon) < threshold and abs(point[1] - self._node1.lat) < threshold:
                    return None

                self._node2 = Node(node_id, point[0], point[1])
                self._mouse_click2 = (event.mouseevent.xdata, event.mouseevent.ydata)
                print("Both points marked")

                for axes in self._main_rendering_axes:
                    plt.sca(axes)
                    plt.plot(self._mouse_click2[0], self._mouse_click2[1], 'ro', zorder=100)

                plt.draw()

                # Now both the points have been marked. Now try to find a path.
                path_dijkstra, paths_considered_dijkstra = shortest_path.dijkstra(self._graph, self._node1.id, self._node2.id)
                path_astar, paths_considered_astar = shortest_path.astar(self._graph, self._node1.id, self._node2.id, self._osm)
                path_bidirectional_dijkstra, paths_considered_from_start_bidirectional_dijkstra, paths_considered_from_end_bidirectional_dijkstra = shortest_path.bidirectional_dijkstra(self._graph, self._node1.id, self._node2.id)

                self.plot_path(self._get_axes('dijkstra', 'main'), path_dijkstra, MatplotLibMap.renderingRules['correct_path'], animate=False)
                self.plot_considered_paths(self._get_axes('dijkstra', 'paths_considered'), path_dijkstra, (paths_considered_dijkstra, 'green'))

                self.plot_path(self._get_axes('astar', 'main'), path_astar, MatplotLibMap.renderingRules['correct_path'], animate=False)
                self.plot_considered_paths(self._get_axes('astar', 'paths_considered'), path_astar, (paths_considered_astar, 'green'))

                self.plot_path(self._get_axes('bidirectional_dijkstra', 'main'), path_bidirectional_dijkstra, MatplotLibMap.renderingRules['correct_path'], animate=False)
                self.plot_considered_paths(self._get_axes('bidirectional_dijkstra', 'paths_considered'), path_bidirectional_dijkstra, (paths_considered_from_start_bidirectional_dijkstra, 'green'), (paths_considered_from_end_bidirectional_dijkstra, 'red'))

                plt.savefig("shortest_path.png")
                return self._node2
Beispiel #41
0
    def finish_history_plot(self,axes,t,filename):

        plt.sca(axes)

        # Timestamp:
        plt.text(100,swap.Imax+0.02,t,color='gray')

        plt.savefig(filename,dpi=300)

        return
Beispiel #42
0
def ex3_1(simpleTime = 0.5):
    y = np.array([1, 3, 5, 1, 1])
    D = 2*np.pi/(len(y)*simpleTime)
    yy = np.fft.fftshift(np.fft.fft(y))
    image1 = subplot(2, 1, 1)
    image2 = subplot(2, 1, 2)
    plt.sca(image1)
    plotT(np.array([i*D for i in xrange(-2, 3)]), np.abs(np.array(yy)), plt)
    plt.sca(image2)
    plotT(np.array([i*D for i in xrange(-2, 3)]), np.angle(np.array(yy)), plt)
    plt.show()
Beispiel #43
0
    def plot_history(self,axes):

        plt.sca(axes)
        I = self.traininghistory['Skill']
        N = np.linspace(1, len(I), len(I), endpoint=True)

        # Information contributions:
        plt.plot(N, I, color="green", alpha=0.2, linewidth=2.0, linestyle="-")
        plt.scatter(N[-1], I[-1], color="green", alpha=0.5)

        return
Beispiel #44
0
    def plot_considered_paths(self, axes, path, *paths_considered_tuples):
        plt.sca(axes)
        edges = zip(path, path[1:])

        # Render all the paths considered
        for path_considered_tuple in paths_considered_tuples:
            paths_considered = path_considered_tuple[0]
            color = path_considered_tuple[1]
            for i, edge in enumerate(paths_considered):
                node_from = self._osm.nodes[edge[0]]
                node_to = self._osm.nodes[edge[1]]
                x_from = node_from.lon
                y_from = node_from.lat
                x_to = node_to.lon
                y_to = node_to.lat

                plt.plot([x_from,x_to],[y_from,y_to],
                        marker          = '',
                        linestyle       = '-',
                        linewidth       = 1,
                        color           = color,
                        solid_capstyle  = 'round',
                        solid_joinstyle = 'round',
                        zorder          = 0,
                        )

        # Render all the paths considered
        for i, edge in enumerate(edges):
            node_from = self._osm.nodes[edge[0]]
            node_to = self._osm.nodes[edge[1]]
            x_from = node_from.lon
            y_from = node_from.lat
            x_to = node_to.lon
            y_to = node_to.lat

            # if i == 0:
            #     x_from = self._mouse_click1[0]
            #     y_from = self._mouse_click1[1]
            #
            # if i == len(path) - 2:
            #     x_to = self._mouse_click2[0]
            #     y_to = self._mouse_click2[1]

            plt.plot([x_from,x_to],[y_from,y_to],
                    marker          = '',
                    linestyle       = '-',
                    linewidth       = 3,
                    color           = 'black',
                    solid_capstyle  = 'round',
                    solid_joinstyle = 'round',
                    zorder          = 1,
                    )

        plt.draw()
Beispiel #45
0
def ex3_2(fftSize=512, oututSize = 2048):
    samplingRate = 80000
    t = np.arange(0, 1.0, 1.0/samplingRate)
    x = np.cos(2*np.pi*20000*t) + 2*np.cos(2*np.pi*21000*t)
    xs = np.fft.fft(x[:fftSize], oututSize)
    image1 = subplot(2, 1, 1)
    image2 = subplot(2, 1, 2)
    plt.sca(image1)
    plotT(np.array([i for i in xrange(fftSize)]), np.array(x[:fftSize]), plt)
    plt.sca(image2)
    plotT(np.array([i for i in xrange(oututSize)]), np.abs(np.array(xs)), plt)
    plt.show()
Beispiel #46
0
def plot(ax,data,scatter=False):
    pl.sca(ax)
    pl.cla()
    cf = pl.contourf(pos_z, pos_r, numpy.transpose(data),8,alpha=.75,linewidth=1,cmap='jet')
    #cf = pl.pcolormesh(pos_z, pos_r, numpy.transpose(data))
    ax.set_yticks(pos_r)
    ax.set_xticks(pos_z)
    ax.xaxis.set_ticklabels([])
    ax.yaxis.set_ticklabels([])
    pl.xlim(min(pos_z),max(pos_z))
    pl.ylim(min(pos_r),max(pos_r))
    ax.grid(b=True,which='both',color='k',linestyle='-')
    ax.set_aspect('equal', adjustable='box')
Beispiel #47
0
    def select_axes(self, axes):
        """
        Set the scope on a certain axes

        Args:
            axes (int): 0, lowest, -1 highest, increasing y-order

        Returns:
            matplotlib.axes.axes: The axes intance
        """
        ax = self.axes[axes]
        p.sca(ax)
        return ax
Beispiel #48
0
    def plot_trajectory(self,axes,highlight=False):

        plt.sca(axes[0])
        N = np.linspace(0, len(self.trajectory)/Ntrajectory+1, len(self.trajectory)/Ntrajectory, endpoint=True);
        N[0] = 0.5
        mdn_trajectory=np.array([]);
        sigma_trajectory_m=np.array([]);
        sigma_trajectory_p=np.array([]);
        for i in range(len(N)):
	    sorted_arr=np.sort(self.trajectory[i*Ntrajectory:(i+1)*Ntrajectory])
            sigma_p=sorted_arr[int(0.84*Ntrajectory)]-sorted_arr[int(0.50*Ntrajectory)]
            sigma_m=sorted_arr[int(0.50*Ntrajectory)]-sorted_arr[int(0.16*Ntrajectory)]
            mdn_trajectory=np.append(mdn_trajectory,sorted_arr[int(0.50*Ntrajectory)]);
            sigma_trajectory_p=np.append(sigma_trajectory_p,sigma_p);
            sigma_trajectory_m=np.append(sigma_trajectory_m,sigma_m);

        if self.kind == 'sim':
            colour = 'blue'
        elif self.kind == 'dud':
            colour = 'red'
        elif self.kind == 'test':
            colour = 'black'

        if self.status == 'undecided':
            facecolour = colour
        else:
            facecolour = 'white'

        if highlight:
            # Thicker, darker line:
            plt.plot(mdn_trajectory,N,color=colour,alpha=0.5,linewidth=2.0, linestyle="-")
        else:
            # Thinner, fainter line:
            plt.plot(mdn_trajectory,N,color=colour,alpha=0.1,linewidth=1.0, linestyle="-")

        NN = N[-1]
        if NN > swap.Ncmax: NN = swap.Ncmax
        if highlight:
            # Heavier symbol:
            plt.scatter(mdn_trajectory[-1], NN, edgecolors=colour, facecolors=facecolour, alpha=0.8);
            plt.plot([mdn_trajectory[-1]-sigma_trajectory_m[-1],mdn_trajectory[-1]+sigma_trajectory_p[-1]],[NN,NN],color=colour,alpha=0.5);
        else:
            # Fainter symbol:
            plt.scatter(mdn_trajectory[-1], NN, edgecolors=colour, facecolors=facecolour, alpha=0.5);
            plt.plot([mdn_trajectory[-1]-sigma_trajectory_m[-1],mdn_trajectory[-1]+sigma_trajectory_p[-1]],[NN,NN],color=colour,alpha=0.3);
        
        
        
        # if self.kind == 'sim': print self.trajectory[-1], N[-1]

        return
Beispiel #49
0
def plot_field_topology(description, ax=None, colorbar=True, fname=None, limits=True,
                    circ_axis=True, vmin=0., vmax=100., labels=True, full_range=True, **kwargs):
    """
    Brain field topology maps.  Ammended/edited by Rob as well, so include him.
    """

    if not description in ALL_DESCRIPTIONS:
        raise KeyError("%s not one of accepted descriptions: %s" %
                                        (description, str(ALL_DESCRIPTIONS)))

    if ax is None:
        ax = plt.gca()
    plt.sca(ax)

    if fname is None:
        fname = get_file()

    data = readsav(fname, verbose=False)

    img = data[description]

    if full_range:
        img2 = np.hstack((img, img, img))
        out = plt.imshow(img2, origin='lower', extent=(-360., 720., -90., 90.),
                            interpolation='nearest', vmin=vmin, vmax=vmax, **kwargs)
    else:
        out = plt.imshow(img, origin='lower', extent=(0., 360., -90., 90.),
                                interpolation='nearest', vmin=vmin, vmax=vmax, **kwargs)

    if limits:
        plt.xlim(0., 360.)
        plt.ylim(-90., 90)

    if circ_axis:
        ax.xaxis.set_major_locator(celsius.CircularLocator())
        ax.yaxis.set_major_locator(celsius.CircularLocator())

    if labels:
        plt.ylabel("Latitude / deg")
        plt.xlabel("Longitude / deg")

    if colorbar:
        c = plt.colorbar(cax=celsius.make_colorbar_cax())
        if labels:
            c.set_label(description.replace('_', ' '))

        out = (out, c)

    return out
Beispiel #50
0
def plot_swea_l2_summary(swea_data, max_times=4096, cmap=None, norm=None,
        labels=True, ax=None, colorbar=True):

    energy_range = (2, 4000.)
    def_range    = (1e6, 1e9)

    if ax is None:
        ax = plt.gca()
    else:
        plt.sca(ax)

    if cmap is None: cmap = 'Spectral_r'
    if norm is None: norm = LogNorm(def_range[0], def_range[1])

    if not 'def' in swea_data:
        print('Data is empty?')
        # extent = (t[0], t[-1], swea_data['energy'][0], swea_data['energy'][-1])
        d = np.empty(4).reshape((2,2)) + np.nan
        t = plt.xlim()
    else:
        d = swea_data['def']
        t = swea_data['time']

        if d.shape[1] > max_times:
            n = int(np.floor(d.shape[1] / max_times))
            d = d[:,::n]
            t = t[::n]

        energy_range = (swea_data['energy'][0], swea_data['energy'][-1])

    extent = (t[0], t[-1], energy_range[0], energy_range[1])

    img = plt.imshow(
        d, extent=extent, interpolation='nearest', origin='lower',
        norm=norm, cmap=cmap
    )
    plt.xlim(t[0], t[-1])

    plt.yscale('log')
    plt.ylim(energy_range[0], energy_range[1])

    if labels:
        plt.ylabel("E / eV")

    if colorbar:
        plt.colorbar(cax=celsius.make_colorbar_cax()).set_label('SWEA D.E.F.')

    return img
Beispiel #51
0
def makeplot(refl, winds, w, stride, map, gs, title, file_name, box=None):
    pylab.figure()
    axmain = pylab.axes((0, 0.025, 1, 0.9))

    gs_x, gs_y = gs
    nx, ny = refl.shape
    xs, ys = np.meshgrid(gs_x * np.arange(nx), gs_y * np.arange(ny))

    pylab.contourf(xs, ys, refl, levels=np.arange(10, 80, 10))
    pylab.colorbar()
    pylab.contour(xs, ys, w, levels=np.arange(-10, 0, 2), colors='#666666', style='--')
    pylab.contour(xs, ys, w, levels=np.arange(2, 12, 2), colors='#666666', style='-')
    
    u, v = winds
    wind_slice = tuple([ slice(None, None, stride) ] * 2)
    pylab.quiver(xs[wind_slice], ys[wind_slice], u[wind_slice], v[wind_slice])

    if box:
        lb_y, lb_x = [ b.start for b in box ]
        ub_y, ub_x = [ b.stop for b in box ]

        box_xs = gs_x * np.array([ lb_x, lb_x, ub_x, ub_x, lb_x])
        box_ys = gs_y * np.array([ lb_y, ub_y, ub_y, lb_y, lb_y])

        map.plot(box_xs, box_ys, '#660099')

        axins = zoomed_inset_axes(pylab.gca(), 4, loc=4)
        pylab.sca(axins)

        pylab.contourf(xs[box], ys[box], refl[box], levels=np.arange(10, 80, 10))
        pylab.contour(xs[box], ys[box], w[box], levels=np.arange(-10, 0, 2), colors='#666666', style='--')
        pylab.contour(xs[box], ys[box], w[box], levels=np.arange(2, 12, 2), colors='#666666', style='-')
        pylab.quiver(xs[box], ys[box], u[box], v[box])

        drawPolitical(map)

        pylab.xlim([lb_x * gs_x, ub_x * gs_x - 1])
        pylab.ylim([lb_y * gs_y, ub_y * gs_y - 1])

        mark_inset(axmain, axins, loc1=1, loc2=3, fc='none', ec='k')

    pylab.sca(axmain)
    drawPolitical(map)

    pylab.suptitle(title)
    pylab.savefig(file_name)
    pylab.close()
    return
Beispiel #52
0
def axman(name, xlabel=None, ylabel=None, title=None, clear=True):
    """`axman` is axis manager. Manages clearing, updating and maintaining a global
    handle to a named plot.

    """
    ax = AX[name]
    prev_ax = pl.gca()
    with update_ax(ax, clear=clear):
        pl.sca(ax)
        yield ax
        if xlabel:
            ax.set_xlabel(xlabel)
        if ylabel:
            ax.set_ylabel(ylabel)
        ax.set_title(title or name)  # `title` overrides `name`.
        #ax.figure.tight_layout()
        pl.sca(prev_ax)
Beispiel #53
0
def plotConfusion(confusion, grid, title, file_name, inset=None, fudge=16):
    pylab.figure()
    axmain = pylab.axes()

    tick_labels = [ "Missing", "Correct\nNegative", "False\nAlarm", "Miss", "Hit" ]
    min_label = -1

    xs, ys = grid.getXY()

    pylab.pcolormesh(xs, ys, confusion, cmap=confusion_cmap, vmin=min_label, vmax=(min_label + len(tick_labels) - 1))

    tick_locs = np.linspace(-1, min_label + len(tick_labels) - 2, len(tick_labels))
    tick_locs += (tick_locs[1] - tick_locs[0]) / 2
    bar = pylab.colorbar()
    bar.locator = FixedLocator(tick_locs)
    bar.formatter = FixedFormatter(tick_labels)
    pylab.setp(pylab.getp(bar.ax, 'ymajorticklabels'), fontsize='large')
    bar.update_ticks()

    grid.drawPolitical()

    if inset:
        lb_y, lb_x = [ b.start for b in inset ]
        ub_y, ub_x = [ b.stop + fudge for b in inset ]

        inset_exp = (slice(lb_y, ub_y), slice(lb_x, ub_x))

        axins = zoomed_inset_axes(pylab.gca(), 2, loc=4)
        pylab.sca(axins)

        pylab.pcolormesh(xs[inset_exp], ys[inset_exp], confusion[inset_exp], cmap=confusion_cmap, vmin=min_label, vmax=(min_label + len(tick_labels) - 1))
        grid.drawPolitical()

        gs_x, gs_y = grid.getGridSpacing()

        pylab.xlim([lb_x * gs_x, (ub_x - 1) * gs_x])
        pylab.ylim([lb_y * gs_y, (ub_y - 1) * gs_y])

        mark_inset(axmain, axins, loc1=1, loc2=3, fc='none', ec='k')

    pylab.sca(axmain)
    pylab.suptitle(title)
    pylab.savefig(file_name)
    pylab.close()
    return
def smooth_data_4(gps_data, K=5, show=False):
    gps_lat = [data[0] for data in gps_data]
    gps_lng = [data[1] for data in gps_data]
    gps_lat = signal.medfilt(gps_lat, K)
    gps_lng = signal.medfilt(gps_lng, K)
    if show == True:
        ax1 = pylab.subplot(211)
        ax2 = pylab.subplot(212)
        Z = [i for i in range(len(gps_data))]
        pylab.sca(ax1)
        pylab.plot(Z, gps_lat)
        pylab.sca(ax2)
        pylab.plot(Z, gps_lng)
        pylab.show()
    for i in range(len(gps_data)):
        gps_data[i][0] = gps_lat[i]
        gps_data[i][1] = gps_lng[i]
    return gps_data
Beispiel #55
0
def set_jointplot(row, col, nrows, ncols, clearaxes=True,
                  top=1,
                  ratio=2):

    if not clearaxes:
        f, axarr = pylab.subplots(nrows, sharex=True, num=1)
        f.subplots_adjust(hspace=0.05)
        pylab.setp([a.get_xticklabels() for a in f.axes[:-1]], visible=False)

        # need to set axes[0] as current axes.
        pylab.sca(axarr[0])

    else:

        # need to set axes[1] as current axes.
        axes = pylab.gca()
        ax2 = axes.figure.axes[-1]
        pylab.sca(ax2)
Beispiel #56
0
def plot_static_l2_summary(static_data, plot_type='Energy',
        max_times=4096, cmap=None, norm=None,
        labels=True, ax=None, colorbar=True):

    if not 'static_kind' in static_data:
        raise ValueError("Data supplied not from static?")

    if not static_data['static_kind'] == 'c0':
        raise ValueError("I only know about C0, for now")

    if cmap is None: cmap = 'Spectral_r'
    if norm is None: norm = LogNorm(1e3, 1e9)

    if ax is None:
        ax = plt.gca()
    else:
        plt.sca(ax)

    imgs = []

    x0, x1 = plt.xlim()

    for extent, data in static_data['blocks']:
        if extent[1] < x0: continue
        if extent[0] > x1: continue

        img = plt.imshow(
            data, extent=extent, interpolation='nearest', origin='lower',
            norm=norm, cmap=cmap
        )
        imgs.append(img)
    plt.yscale('log')
    # plt.xlim(t0, t1)
    plt.ylim(extent[2], extent[3])

    if labels:
        plt.ylabel("E / eV")

    if colorbar:
        plt.colorbar(cax=celsius.make_colorbar_cax()).set_label('static D.E.F.')

    return imgs
Beispiel #57
0
    def finish_trajectory_plot(self,axes,filename,t=None,final=None):

        # If we are not plotting the histogram, the second axis is False...

        if axes[1] is not False:

            # Plot histograms! 0 is the upper panel, 1 the lower.
            plt.sca(axes[1])

            bins = np.linspace(np.log10(swap.pmin),np.log10(swap.pmax),32,endpoint=True)
            bins = 10.0**bins
            colors = ['blue','red','black']
            labels = ['Training: Sims','Training: Duds','Test: Survey']
            thresholds = self.thresholds()

            for j,kind in enumerate(['sim','dud','test']):

                self.collect_probabilities(kind)
                p = self.probabilities[kind]

                # Sometimes all probabilities are lower than pmin!
                # Snap to grid.
                p[p<swap.pmin] = swap.pmin
                # print "kind,bins,p = ",kind,bins,p

                # Final plot - only show subjects above threshold:
                if final:
                    p = p[p>thresholds['rejection']]

                # Pylab histogram:
                plt.hist(p, bins=bins, histtype='stepfilled', color=colors[j], alpha=0.7, label=labels[j])
                plt.legend(prop={'size':10})

        if t is not None:
            # Add timestamp in top righthand corner:
            plt.sca(axes[0])
            plt.text(1.3*swap.prior,0.27,t,color='gray')

        # Write out to file:
        plt.savefig(filename,dpi=300)

        return
def cal_fft(gps_data, show=False):
    gps_lat = [data[0] for data in gps_data]
    gps_lng = [data[1] for data in gps_data]
    gps_lat = numpy.fft.fft(gps_lat)
    gps_lng = numpy.fft.fft(gps_lng)
    print gps_lat
    print gps_lng
    if show == True:
        ax1 = pylab.subplot(211)
        ax2 = pylab.subplot(212)
        Z = [i for i in range(len(gps_data))]
        pylab.sca(ax1)
        pylab.plot(Z, gps_lat)
        pylab.sca(ax2)
        pylab.plot(Z, gps_lng)
        pylab.show()
    for i in range(len(gps_data)):
        gps_data[i][0] = gps_lat[i]
        gps_data[i][1] = gps_lng[i]
    return gps_data