Пример #1
0
def plot_Kiel_diagram(starl):
    """
    Plot Kiel diagram.
    """
    x = starl['temperature']
    y = starl['g']
    age = starl['age'] / 1e6
    points = np.array([x, y]).T.reshape(-1, 1, 2)
    segments = np.concatenate([points[:-1], points[1:]], axis=1)

    cmap = pl.cm.spectral
    norm = pl.Normalize(age.min(), age.max())
    lc = LineCollection(segments, cmap=cmap, norm=norm)
    lc.set_array(age)
    lc.set_linewidth(3)
    pl.gca().add_collection(lc)
    pl.xlim(x.max(), x.min())
    pl.ylim(y.max(), y.min())
    pl.xlabel('Effective temperature [K]')
    pl.ylabel('log(surface gravity [cm s$^{-2}$]) [dex]')

    ax0 = pl.gca()
    ax1 = pl.mpl.colorbar.make_axes(ax0)[0]
    norm = pl.mpl.colors.Normalize(age.min(), age.max())
    cb1 = pl.mpl.colorbar.ColorbarBase(ax1,
                                       cmap=cmap,
                                       norm=norm,
                                       orientation='vertical')
    cb1.set_label('Age [Myr]')
    pl.axes(ax0)
Пример #2
0
def d3():
    rtimes, rt, rp = np.loadtxt("data/data.txt").T
    mask = np.logical_and(rtimes > 1391000000, rtimes < 1393000000)
    rtimes = rtimes[mask]
    rt = rt[mask]
    rtimes = map(datetime.datetime.fromtimestamp, rtimes)
    rtimes = matplotlib.dates.date2num(rtimes)
    fig, axis = plt.subplots()

    axis.xaxis_date()
    fig.autofmt_xdate()
    axis.plot_date(rtimes, rt, "-", linewidth=3, color="black")

    forecast_list = []
    for fname in glob.glob("data/forecast.1391*.txt"):
        stamp = fname.split(".")[1]
        times, tempa = np.loadtxt(fname).T
        times = map(datetime.datetime.fromtimestamp, times)
        times = matplotlib.dates.date2num(times)

        points = np.array([times, tempa]).T.reshape(-1, 1, 2)
        segments = np.concatenate([points[:-1], points[1:]], axis=1)
        lc = LineCollection(segments,
                            cmap=plt.get_cmap("jet"),
                            norm=plt.Normalize(0, 1))
        lc.set_array(np.linspace(0, 1, len(times)))
        lc.set_linewidth(1)
        axis.add_collection(lc)

        axis.plot_date(times, tempa, "-", linewidth=2)

    return fig_to_html(fig)
Пример #3
0
def draw_disp_grid(boxsize, grid):
    """ draw a slice of the displacement grid """
    pl.rcParams.update(latexParams)
    pl.figure(figsize=(6.64, 6.64), dpi=100)

    limit = max(-grid.min(), grid.max())
    norm = pl.Normalize(vmin=-limit, vmax=limit)

    slice = grid[:, 0]
    pl.subplot(221)
    n = grid.shape[1]
    x = arange(n) * (boxsize / n)
    pl.imshow(slice[0], extent=(0, boxsize, 0, boxsize), norm=norm)
    pl.colorbar().set_label(r'$\rm Mpc/h$')
    pl.ylabel(r'$y \; \rm Mpc/h$')
    pl.title(r'$\Psi_x$')

    pl.subplot(222)
    pl.imshow(slice[1], extent=(0, boxsize, 0, boxsize), norm=norm)

    pl.title(r'$\Psi_y$')
    pl.colorbar().set_label(r'$\rm Mpc/h$')

    pl.subplot(223)

    pl.imshow(slice[2], extent=(0, boxsize, 0, boxsize), norm=norm)
    pl.colorbar().set_label(r'$\rm Mpc/h$')
    #pl.ylabel(r'$y \; \rm Mpc/h$')
    pl.title(r'$\Psi_z$')

    pl.show()
Пример #4
0
def my_square_scatter(axes,
                      x_array,
                      y_array,
                      z_array,
                      min_z=None,
                      max_z=None,
                      size=0.5,
                      **kwargs):
    size = float(size)

    if min_z is None:
        min_z = z_array.min()
    if max_z is None:
        max_z = z_array.max()

    normal = pylab.Normalize(min_z, max_z)
    colors = pylab.cm.jet(normal(z_array))

    for x, y, c in zip(x_array, y_array, colors):
        square = pylab.Rectangle((x - size / 2, y - size / 2),
                                 size,
                                 size,
                                 color=c,
                                 **kwargs)
        axes.add_patch(square)

    axes.autoscale()

    cax, _ = cbar.make_axes(axes)
    cb2 = cbar.ColorbarBase(cax, cmap=pylab.cm.jet, norm=normal)

    return True
Пример #5
0
def cline(x, y, z, clim, cmap):  # color line
    norm = pl.Normalize(clim[0], clim[1])
    points = np.array([x, y]).T.reshape(-1, 1, 2)
    segments = np.concatenate([points[:-1], points[1:]], axis=1)
    lc = LineCollection(segments, cmap=cmap, norm=norm)
    if not hasattr(z, "__iter__"):  # single value check
        z = np.array([z])
    lc.set_array(z)
    lc.set_linewidth(1)
    pl.gca().add_collection(lc)
Пример #6
0
def plot_E_s(arrays, x, y, x0, y0, corner_indices, save_name=None):
    figsize = 6
    fig, ax = plt.subplots(1, 1, figsize=(figsize, figsize))
    arrays = [np.abs(E_s) / np.abs(E_s).mean() for E_s in arrays]
    vmin = min([E_s.min().value for E_s in arrays])
    vmax = max([E_s.max().value for E_s in arrays])

    norm = plt.Normalize(vmin, vmax)
    to_colour = lambda w: plt.cm.jet(norm(w))

    def _get_artists(artists, start):
        _, img = plot_2d_image(arrays[start],
                               x,
                               y,
                               title="Scattered electric field",
                               corner_indices=corner_indices,
                               colorizer=to_colour,
                               ax=ax)
        sc = ax.scatter(x0[start].value,
                        y0[start].value,
                        c='green',
                        label='source')
        ax.set_xlim(x.min().value, x.max().value)
        ax.set_ylim(y.min().value, y.max().value)
        ax.legend()
        artists.append(img)
        artists.append(sc)
        return artists

    def init():
        start = 0
        ax.clear()
        artists = []
        artists = _get_artists(artists, start)
        mappable = plt.cm.ScalarMappable(norm=norm, cmap=plt.cm.jet)
        add_colorbar(mappable,
                     label='rel. electric field amplitude [{}]'.format(
                         arrays[0].unit),
                     ax=ax)
        return artists

    def update(start):
        ax.clear()
        artists = []
        artists = _get_artists(artists, start)
        return artists

    ani = FuncAnimation(fig,
                        update,
                        frames=range(1, len(arrays)),
                        init_func=init,
                        blit=True)

    ani.save(save_name, fps=5.)  #len(arrays) / 6.)
Пример #7
0
    def XVsY2DMap(self,
                  ax,
                  xVal,
                  yVal,
                  zVal,
                  cmap=None,
                  title=None,
                  xlabel=None,
                  xlim=None,
                  ylabel=None,
                  ylim=None,
                  zlabel=None,
                  zMax=None,
                  zMin=None):

        m = Basemap(llcrnrlon=self.glonlim[0],
                    llcrnrlat=self.glatlim[0],
                    urcrnrlon=self.glonlim[-1],
                    urcrnrlat=self.glatlim[-1],
                    resolution='l')

        m.drawcoastlines()

        # Lines at constant "latitude"
        parallelsLim = self._RoundLim([yVal[0], yVal[-1]])
        m.drawparallels(arange(parallelsLim[0], parallelsLim[1], 20.),
                        labels=[True, False, False, True])

        # Lines at constant "longitude"
        meridiansLim = self._RoundLim([xVal[0], xVal[-1]])
        m.drawmeridians(arange(meridiansLim[0], meridiansLim[1], 30.),
                        labels=[True, False, False, True])

        X, Y = meshgrid(xVal, yVal)
        ipc = m.pcolor(X,
                       Y,
                       transpose(zVal),
                       cmap=cmap,
                       edgecolors='None',
                       norm=pylab.Normalize(),
                       vmax=zMax,
                       vmin=zMin)
        # m.contour(X, Y, transpose(self.data2D['dip']), colors='k', linestyles='--')

        ax.set_xlim(xlim)
        ax.set_ylim(ylim)
        ax.set_title(title)
        # ax.set_xlabel( xlabel )
        # ax.set_ylabel( ylabel )

        cbpn = m.colorbar(ipc)
        cbpn.set_label(zlabel)
    def __animate_nestmates(self, pos, crop):

        normal = pl.Normalize(0, 1)
        colors = cmap(normal(crop))

        for p, c in zip(pos, colors):
            if not isinstance(pos, str):
                rect = pl.Rectangle([p, 0], 1, 3, color=c)
                self.ax.add_patch(rect)
            else:
                pos = [ast.literal_eval(x) for x in pos]
                rect = pl.Rectangle(pos, 1, 1, color=c)
                self.ax.add_patch(rect)
Пример #9
0
def plot_data(ax):
      
    #-- rectangle lower left corner positions

    h = 0.7  # height of the rectangles
    Y = np.arange(1-h/2,7+h/2,1)  # y-coord
    X = [1,   2,  1, 2, 4,   0.6, 200]  # x-coord
    W = [200, 14, 3, 2, 564, 1.4, 1e4]  # width (+1) of the rectangles

    vs = [0, -.5, 0.7, 0.8, 0.2, -0.3, 0.4]  # [experimental --> theoretical] in [-1,1]
    normal = pl.Normalize(-1,1)
    colors = pl.cm.jet(normal(vs))

    X_txt = [5, 18, 4, 4, 7, 1.3, 800]
    txt = ['ICLS/GFM', 'droplet assembly',
           'hydrodynamic interaction I',
           'hydrodynamic interaction II',
           'droplets in turbulence',
           'liquid-infused surfaces','DLCD']

    for i,y in enumerate(Y): 
        rect = patches.Rectangle( (X[i],y), W[i]-1,h, color=colors[i])
        ax.add_patch(rect)
        ax.text(X_txt[i],y+0.2, txt[i])

    cax, _ = cbar.make_axes(ax) 
    cb2 = cbar.ColorbarBase(cax, cmap=pl.cm.jet,norm=normal)

    ax.plot([1,1],[0,8], linestyle='--',color='C7', alpha=0.5)
    
    #-- plot limit
    
    xmin = 0.5
    xmax = 1.5e4
    ymin = 0.4
    ymax = 7.6
    
    ax.set_xlim(xmin, xmax)
    ax.set_ylim(ymin, ymax)
    
    ax.set_xscale('log')
    
    ax.set_xlabel(r'$N$')
    ax.set_ylabel(r'Paper')
    
    return ax
Пример #10
0
def add_colorbar_to_axes(ax, cmap, norm=None, vmin=None, vmax=None):
    """
    Add colorbar to axes easily.

    Args:
        ax: Axes
        cmap: str or cmap
        norm: Normalize or None
        vmin: lower limit of color if norm is None
        vmax: upper limit of color if norm is None
    """
    divider = make_axes_locatable(ax)
    cax = divider.append_axes('right', size='5%', pad=0.05)
    if norm is None:
        norm = plt.Normalize(vmin=vmin, vmax=vmax)
    sm = plt.cm.ScalarMappable(norm, cmap=plt.cm.get_cmap(cmap))
    ax.figure.colorbar(sm, cax=cax, orientation='vertical')
    def __init__(self, save_name=False, ant=False):
        self._df_file = self.get_data()
        self._df_file = '~/Agent-based-ants/Good_model/Data/singlerun_step_data.csv' if self._df_file is None else self._df_file
        self.save_name = save_name
        self.ant = ant
        self.validate()

        if re.search("[$.](.+)", self._df_file).group(1) == 'csv':
            self.df = pd.read_csv(self._df_file)
        elif re.search("[$.](.+)", self._df_file).group(1) in [
                'xls', 'xlsx', 'xlsm', 'xlsb'
        ]:
            self.df = pd.excel_read(self._df_file)

        self.fig, self.ax = plt.subplots(figsize=(max(self.df.position) + 3,
                                                  5))
        normal = pl.Normalize(0, 1)
        self.cax, _ = cbar.make_axes(self.ax)
        self.cb2 = cbar.ColorbarBase(self.cax, cmap=cmap, norm=normal)

        # self.repeat_df = self.df[self.df.id <=23]
        self.repeat_df = self.df
Пример #12
0
def plot_2d_image(a, x, y, colorbar_name=None, title=None, xlabel='x', ylabel='y', cmap='bone', colorizer=None, corner_indices=None, ax=None, save_name=None):
    if ax is None:
        fig, ax = plt.subplots(1,1, figsize=(5,5))
    if colorizer is None:
        norm = plt.Normalize(a.min().value, a.max().value)
        colorizer = plt.cm.get_cmap(cmap)(norm)
    img = ax.imshow(colorizer(a.T.value), interpolation='nearest', origin='lower',
               extent=(x.min().value, x.max().value, y.min().value, y.max().value))
    if corner_indices is not None:
        ax.plot(Quantity([x[corner_indices[0]], x[-corner_indices[0]], x[-corner_indices[0]], x[corner_indices[0]], x[corner_indices[0]]]).value,
                 Quantity([y[corner_indices[1]], y[corner_indices[1]], y[-corner_indices[1]], y[-corner_indices[1]], y[corner_indices[1]]]).value, c='red')
    if title is not None:
        ax.set_title(title)
    if xlabel is not None:
        ax.set_xlabel('{} [{}]'.format(xlabel, x.unit))
    if ylabel is not None:
        ax.set_ylabel('{} [{}]'.format(ylabel, y.unit))
    if colorbar_name is not None:
        plt.colorbar(label='{} [{}]'.format(colorbar_name, a.unit))
    if save_name is not None:
        plt.savefig(save_name)
    return ax, img
    def animation(self):
        if self.save_name:
            ani = animation.FuncAnimation(
                # self.fig, self.__animate_repeat, interval=1, frames=max(self.repeat_df.step))
                self.fig,
                self.__animate_repeat,
                interval=1,
                frames=(50))

            ani.save(self.save_name, writer=writer)

        else:
            for i in range(10):
                self.fig, self.ax = plt.subplots(
                    figsize=(max(self.df.position), 5))
                normal = pl.Normalize(0, 1)
                self.cax, _ = cbar.make_axes(self.ax)
                self.cb2 = cbar.ColorbarBase(self.cax, cmap=cmap, norm=normal)
                self.__animate_repeat(i)
                plt.show(block=False)
                plt.pause(0.001)
                plt.close()
Пример #14
0
    def plot_regions_states(self):
        fig, ax = plt.subplots()

        states_per_reg = [len(region.states) for region in self.regions]
        states_per_reg_lims = (min(states_per_reg), max(states_per_reg))
        normal = pylab.Normalize(*states_per_reg_lims)

        colors = pylab.cm.BuGn(normal(states_per_reg))

        for region, color in zip(self.regions, colors):
            lengths = region.max_border - region.min_border
            ax.add_patch(
                patches.Rectangle(region.min_border,
                                  *lengths,
                                  fill=True,
                                  edgecolor='k',
                                  facecolor=color))

        cax, _ = cbar.make_axes(ax)
        print("the interest lims are: ", states_per_reg_lims)
        cb2 = cbar.ColorbarBase(cax, cmap=pylab.cm.BuGn, norm=normal)
        ax.set_xlim(self.state_bounds[0][0], self.state_bounds[1][0])
        ax.set_ylim(self.state_bounds[0][1], self.state_bounds[1][1])
Пример #15
0
    def plot_regions_interest(self, ax=None):
        if ax is None:
            __, ax = plt.subplots()

        interests = self.compute_all_interests()
        interest_lims = (min(interests), max(interests))
        normal = pylab.Normalize(*interest_lims)

        colors = pylab.cm.YlOrRd(normal(interests))

        for region, color in zip(self.regions, colors):
            lengths = region.max_border - region.min_border
            ax.add_patch(
                patches.Rectangle(region.min_border,
                                  *lengths,
                                  fill=True,
                                  edgecolor='k',
                                  facecolor=color))

        cax, _ = cbar.make_axes(ax)
        print("the interest lims are: ", interest_lims)
        cb2 = cbar.ColorbarBase(cax, cmap=pylab.cm.YlOrRd, norm=normal)
        ax.set_xlim(self.state_bounds[0][0], self.state_bounds[1][0])
        ax.set_ylim(self.state_bounds[0][1], self.state_bounds[1][1])
Пример #16
0
def plot_discretized_belief_halfcircle(belief_rewards, center_points, env,
                                       observations):

    fig = plt.figure()
    env.plot_behavior(observations,
                      plot_env=True,
                      color=cols_deep[3],
                      linewidth=5)
    res = center_points[1, 0] - center_points[0, 0]
    normal = pl.Normalize(0., 1.)
    colors = pl.cm.gray(normal(belief_rewards))

    for (x, y), c in zip(center_points, colors):
        rec = Rectangle((x, y),
                        res,
                        res,
                        facecolor=c,
                        alpha=0.85,
                        edgecolor='none')
        plt.gca().add_patch(rec)

    cax, _ = cbar.make_axes(plt.gca())
    cb2 = cbar.ColorbarBase(cax, cmap=pl.cm.gray, norm=normal)
    return fig
Пример #17
0
def hello():

    rtimes, rt, rp = np.loadtxt("data/data.txt").T
    rtimes = map(datetime.datetime.fromtimestamp, rtimes)
    rtimes = matplotlib.dates.date2num(rtimes)
    fig = Figure()
    axis = fig.add_subplot(1, 1, 1)
    axis.xaxis_date()
    fig.autofmt_xdate()

    forecast_list = []
    for fname in glob.glob("data/forecast.*.txt"):
        stamp = fname.split(".")[1]
        times, tempa = np.loadtxt(fname).T
        times = map(datetime.datetime.fromtimestamp, times)
        times = matplotlib.dates.date2num(times)

        points = np.array([times, tempa]).T.reshape(-1, 1, 2)
        segments = np.concatenate([points[:-1], points[1:]], axis=1)
        lc = LineCollection(segments,
                            cmap=plt.get_cmap("jet"),
                            norm=plt.Normalize(0, 1))
        lc.set_array(np.linspace(0, 1, len(times)))
        lc.set_linewidth(1)
        axis.add_collection(lc)

        axis.plot_date(times, tempa, "-", linewidth=0)

    axis.plot_date(rtimes, rt, "-", linewidth=1, color="black")

    canvas = FigureCanvas(fig)
    output = StringIO.StringIO()
    canvas.print_png(output)
    response = make_response(output.getvalue())
    response.mimetype = 'image/png'
    return response
Пример #18
0
    def XVsY2DPlot(self,
                   ax,
                   xVal,
                   yVal,
                   zVal,
                   cmap=None,
                   title=None,
                   xlabel=None,
                   xlim=None,
                   ylabel=None,
                   ylim=None,
                   zlabel=None,
                   zMax=None,
                   zMin=None):

        X, Y = pylab.meshgrid(xVal, yVal)
        X = transpose(X)
        Y = transpose(Y)

        C = transpose(zVal)
        ipn = ax.pcolor(X,
                        Y,
                        C,
                        cmap=cmap,
                        edgecolors='None',
                        norm=pylab.Normalize(),
                        vmax=zMax,
                        vmin=zMin)
        ax.set_xlim(xlim)
        ax.set_ylim(ylim)
        ax.set_title(title)
        ax.set_xlabel(xlabel)
        ax.set_ylabel(ylabel)

        cbpn = pylab.colorbar(ipn)
        cbpn.set_label(zlabel)
Пример #19
0
	error[nanLocs]=0

	fluxes = []
	fluxErrors = []
	for aperture in apertures:
		print(aperture_photometry(data,aperture,error=error))
		fluxErrors.append(list(aperture_photometry(data,aperture,error=error)['aperture_sum_err'])[0])
		fluxes.append(list(aperture_photometry(data,aperture,error=error)['aperture_sum'])[0])

	return np.array(fluxes), np.array(fluxErrors),pixelCenter

fluxes,fluxErrors,pixelCenter = calculateFluxes(data,WCS(hdu.header,naxis=2))

######################################################################################

norm = plt.Normalize()
colors = plt.cm.jet(norm(fluxes))
rainbowColorMapValue = plt.get_cmap('rainbow')
colors = rainbowColorMapValue(norm(fluxes))

infile = 'data/HZ7_Collapsed.fits'

hdu = fits.open(infile)
data = hdu[0].data[0][0]
wcs = WCS(hdu[0].header,naxis=2)

# Plotting low-res moment-1 plot
fig = plt.figure()
ax = fig.add_subplot(projection=wcs)
im = ax.imshow(data,cmap='rainbow')
Пример #20
0
           embedding[1],
           s=100 * d**2,
           c=labels,
           cmap=pl.cm.spectral)

# Plot the edges
start_idx, end_idx = np.where(non_zero)
#a sequence of (*line0*, *line1*, *line2*), where::
#            linen = (x0, y0), (x1, y1), ... (xm, ym)
segments = [[embedding[:, start], embedding[:, stop]]
            for start, stop in zip(start_idx, end_idx)]
values = np.abs(partial_correlations[non_zero])
lc = LineCollection(segments,
                    zorder=0,
                    cmap=pl.cm.hot_r,
                    norm=pl.Normalize(0, .7 * values.max()))
lc.set_array(values)
lc.set_linewidths(15 * values)
ax.add_collection(lc)

# Add a label to each node. The challenge here is that we want to
# position the labels to avoid overlap with other labels
for index, (name, label, (x, y)) in enumerate(zip(names, labels, embedding.T)):

    dx = x - embedding[0]
    dx[index] = 1
    dy = y - embedding[1]
    dy[index] = 1
    this_dx = dx[np.argmin(np.abs(dy))]
    this_dy = dy[np.argmin(np.abs(dx))]
    if this_dx > 0:
Пример #21
0
    def __init__(self,
                 data_file,
                 plot_groups=[1],
                 data_type=2,
                 color_map='jet',
                 plot_contours=False,
                 plot_label="",
                 plot_bands=None,
                 time_zone=0,
                 plot_max_freq=30.0,
                 run_quietly=False,
                 save_file='',
                 dpi=150,
                 parent=None):

        self.data_type = data_type
        self.run_quietly = run_quietly
        self.dpi = dpi

        self.df = VOAOutFile(data_file,
                             time_zone=time_zone,
                             data_type=self.data_type,
                             quiet=run_quietly)

        self.image_defs = self.IMG_TYPE_DICT[self.data_type]

        color_map = eval('P.cm.' + color_map)

        if plot_groups[0] == 'a':
            num_grp = self.df.get_number_of_groups()
            plot_groups = range(0, num_grp)

        self.subplots = []
        number_of_subplots = len(plot_groups)

        matplotlib.rcParams['axes.edgecolor'] = 'gray'
        matplotlib.rcParams['axes.facecolor'] = 'white'
        matplotlib.rcParams['axes.grid'] = True
        matplotlib.rcParams['figure.facecolor'] = 'white'
        matplotlib.rcParams['legend.fancybox'] = True
        matplotlib.rcParams['legend.shadow'] = True
        matplotlib.rcParams['figure.subplot.hspace'] = 0.45
        matplotlib.rcParams['figure.subplot.wspace'] = 0.35
        matplotlib.rcParams['figure.subplot.right'] = 0.85
        colorbar_fontsize = 12

        if number_of_subplots <= 1:
            self.num_rows = 1
            self.main_title_fontsize = 24
            matplotlib.rcParams['legend.fontsize'] = 12
            matplotlib.rcParams['axes.labelsize'] = 12
            matplotlib.rcParams['axes.titlesize'] = 8
            matplotlib.rcParams['xtick.labelsize'] = 10
            matplotlib.rcParams['ytick.labelsize'] = 10
            matplotlib.rcParams[
                'figure.subplot.top'] = 0.79  # single figure plots have a larger title so require more space at the top.
            self.x_axes_ticks = P.arange(0, 25, 2)
        elif ((number_of_subplots >= 2) and (number_of_subplots <= 6)):
            self.num_rows = 2
            self.main_title_fontsize = 18
            matplotlib.rcParams['legend.fontsize'] = 10
            matplotlib.rcParams['axes.labelsize'] = 10
            matplotlib.rcParams['axes.titlesize'] = 11
            matplotlib.rcParams['xtick.labelsize'] = 8
            matplotlib.rcParams['ytick.labelsize'] = 8
            self.x_axes_ticks = P.arange(0, 25, 4)
        else:
            self.num_rows = 3
            self.main_title_fontsize = 16
            matplotlib.rcParams['legend.fontsize'] = 8
            matplotlib.rcParams['axes.labelsize'] = 8
            matplotlib.rcParams['axes.titlesize'] = 10
            matplotlib.rcParams['xtick.labelsize'] = 6
            matplotlib.rcParams['ytick.labelsize'] = 6
            self.x_axes_ticks = P.arange(0, 25, 4)

        self.num_cols = int(
            math.ceil(float(number_of_subplots) / float(self.num_rows)))
        self.fig = Figure(figsize=(7, 6.5))
        self.main_title_label = self.fig.suptitle(
            plot_label + unicode(self.image_defs['title'], 'utf-8'),
            fontsize=self.main_title_fontsize)

        for chan_grp in plot_groups:
            (group_name, group_info, fot, muf, hpf,
             image_buffer) = self.df.get_group_data(chan_grp)

            ax = self.fig.add_subplot(self.num_rows, self.num_cols,
                                      plot_groups.index(chan_grp) + 1)

            self.subplots.append(ax)

            if number_of_subplots > 4:
                #save a little space by only labelling the outer edges of the plot
                ax.label_outer()

            _sign = '+' if (time_zone >= 0) else ''
            self.x_label = ax.set_xlabel(
                _('Time (UTC%(sig)s%(tz)s)') % {
                    'sig': _sign,
                    'tz': time_zone
                })
            self.y_label = ax.set_ylabel(_('Frequency (MHz)'))

            ## Autoscale y (frequency axis)
            if (plot_max_freq == self.AUTOSCALE):
                y_max = math.ceil(max(muf) / 5.0) * 5.0
                y_max = min(plot_max_freq, 30.0)
                y_max = max(plot_max_freq, 5.0)
            else:
                y_max = math.ceil(plot_max_freq / 5.0) * 5.0
            #resize the image
            image_buffer = image_buffer[0:y_max - 1, :]

            y_ticks = [2, 5]
            for y_tick_value in P.arange(10, y_max + 1, 5):
                y_ticks.append(y_tick_value)

            ax.plot(range(0, 25), muf, 'r-', range(0, 25), fot, 'g-')
            ax.set_ylim([2, y_max])

            ax.set_xticks(self.x_axes_ticks)
            ax.set_yticks(y_ticks)

            self.add_legend(ax)
            title_str = group_info.strip()
            if number_of_subplots > 1:
                title_str = self.get_small_title(title_str)
            self.subplot_title_label = ax.set_title(title_str,
                                                    multialignment='left',
                                                    **self.mono_font)

            if (self.data_type > 0):
                im = ax.imshow(image_buffer,
                               interpolation='bicubic',
                               extent=(0, 24, 2, y_max),
                               origin='lower',
                               cmap=color_map,
                               alpha=0.95,
                               norm=P.Normalize(clip=False,
                                                vmin=self.image_defs['min'],
                                                vmax=self.image_defs['max']))
                if plot_contours:
                    ax.contour(image_buffer,
                               self.image_defs['y_labels'],
                               extent=(0, 24, 2, y_max),
                               linewidths=1.0,
                               colors='k',
                               alpha=0.6)

            if plot_bands:
                for a, b in plot_bands:
                    ax.axhspan(a, b, alpha=0.5, ec='k', fc='k')

        if (self.data_type > 0):
            self.cb_ax = self.fig.add_axes(self.get_cb_axes())
            self.fig.colorbar(im,
                              cax=self.cb_ax,
                              orientation='vertical',
                              format=P.FuncFormatter(
                                  eval('self.' +
                                       self.image_defs['formatter'])))
            for t in self.cb_ax.get_yticklabels():
                t.set_fontsize(colorbar_fontsize)

        canvas = FigureCanvasGTKAgg(self.fig)
        self.fig.canvas.mpl_connect('draw_event', self.on_draw)
        canvas.show()

        if save_file:
            self.save_plot(canvas, save_file)

        if not self.run_quietly:
            # TODO consider using a scrolled pane here...
            dia = VOAPlotWindow('pythonProp - ' + self.image_defs['title'],
                                canvas,
                                parent,
                                dpi=self.dpi)
        return
Пример #22
0
    def plot_regions_states(self, maze_id=0, report=None):
        fig, ax = plt.subplots()

        states_per_reg = [len(region.states) for region in self.regions]
        states_per_reg_lims = (min(states_per_reg), max(states_per_reg))
        normal = pylab.Normalize(*states_per_reg_lims)

        colors = pylab.cm.BuGn(normal(states_per_reg))

        for region, color in zip(self.regions, colors):
            lengths = region.max_border - region.min_border
            ax.add_patch(
                patches.Rectangle(region.min_border,
                                  *lengths,
                                  fill=True,
                                  edgecolor='k',
                                  facecolor=color))

        cax, _ = cbar.make_axes(ax)
        print("the interest lims are: ", states_per_reg_lims)
        cb2 = cbar.ColorbarBase(cax, cmap=pylab.cm.BuGn, norm=normal)
        ax.set_xlim(self.state_bounds[0][0], self.state_bounds[1][0])
        ax.set_ylim(self.state_bounds[0][1], self.state_bounds[1][1])

        if maze_id == 0:
            ax.add_patch(
                patches.Rectangle((-3, -3),
                                  10,
                                  2,
                                  fill=True,
                                  edgecolor="none",
                                  facecolor='0.4',
                                  alpha=0.3))
            ax.add_patch(
                patches.Rectangle((-3, -1),
                                  2,
                                  6,
                                  fill=True,
                                  edgecolor="none",
                                  facecolor='0.4',
                                  alpha=0.3))
            ax.add_patch(
                patches.Rectangle((-3, 5),
                                  10,
                                  2,
                                  fill=True,
                                  edgecolor="none",
                                  facecolor='0.4',
                                  alpha=0.3))
            ax.add_patch(
                patches.Rectangle((5, -1),
                                  2,
                                  6,
                                  fill=True,
                                  edgecolor="none",
                                  facecolor='0.4',
                                  alpha=0.3))
            ax.add_patch(
                patches.Rectangle((-1, 1),
                                  4,
                                  2,
                                  fill=True,
                                  edgecolor="none",
                                  facecolor='0.4',
                                  alpha=0.3))
        elif maze_id == 11:
            ax.add_patch(
                patches.Rectangle((-7, 5),
                                  14,
                                  2,
                                  fill=True,
                                  edgecolor="none",
                                  facecolor='0.4',
                                  alpha=0.3))
            ax.add_patch(
                patches.Rectangle((5, -5),
                                  2,
                                  10,
                                  fill=True,
                                  edgecolor="none",
                                  facecolor='0.4',
                                  alpha=0.3))
            ax.add_patch(
                patches.Rectangle((-7, -7),
                                  14,
                                  2,
                                  fill=True,
                                  edgecolor="none",
                                  facecolor='0.4',
                                  alpha=0.3))
            ax.add_patch(
                patches.Rectangle((-7, -5),
                                  2,
                                  10,
                                  fill=True,
                                  edgecolor="none",
                                  facecolor='0.4',
                                  alpha=0.3))
            ax.add_patch(
                patches.Rectangle((-1, 1),
                                  6,
                                  2,
                                  fill=True,
                                  edgecolor="none",
                                  facecolor='0.4',
                                  alpha=0.3))
            ax.add_patch(
                patches.Rectangle((-3, -3),
                                  2,
                                  6,
                                  fill=True,
                                  edgecolor="none",
                                  facecolor='0.4',
                                  alpha=0.3))
            ax.add_patch(
                patches.Rectangle((-1, -3),
                                  4,
                                  2,
                                  fill=True,
                                  edgecolor="none",
                                  facecolor='0.4',
                                  alpha=0.3))

        regions_fig = save_image(fig)

        if report is None:
            return regions_fig
        else:
            report.add_image(
                regions_fig,
                'States per region\nTotal number of states: {}'.format(
                    sum([len(region.states) for region in self.regions])))
Пример #23
0
def choroplethNYC(df,
                  column=None,
                  cmap='viridis',
                  ax=None,
                  cb=True,
                  kind='continuous',
                  alpha=1,
                  color=None,
                  edgecolor=None,
                  scheme=None,
                  k=10,
                  spacing=False,
                  lw=1,
                  width=None,
                  side=False):
    '''creates a choroplath from a dataframe column - NYC tuned
    Arguments:
    df : a GeoDataFrame
    column : a column name
    cmap : colorman name (string optional)
    ax : axis in figure object (string, optiona, is None a figure is created)
    cb : put the color bar. Bool, default is True
    kind :
    spacing : the spacing for the colorbar (bool, optional)
    lw : line width (float, optional, default is 1)
    width : with width of the color bar (figure frction, float)
    side : default False is left (west), True switches to right (east). If a float is passed that is the location
    Returns the figure and the axis, for further manipulation
    '''
    if ax == None:
        ax = pl.figure(figsize=(10, 10)).add_subplot(111)
    if column == None:
        if color == None:
            ax = df.plot(cmap=cmap, alpha=alpha, ax=ax, linewidth=lw)
        else:
            ax = df.plot(alpha=alpha,
                         ax=ax,
                         linewidth=lw,
                         color=color,
                         edgecolor=edgecolor)
    elif not scheme == None:
        ax = df.plot(column=column,
                     edgecolor=edgecolor,
                     cmap=cmap,
                     alpha=alpha,
                     ax=ax,
                     linewidth=lw,
                     scheme=scheme,
                     k=k,
                     legend=True)

        pl.legend(loc=2)
        ax.axis('off')
        leg = ax.get_legend()
        #pl.legend(bbox_to_anchor=(2, 2), loc=2, borderaxespad=0)
        leg.set_bbox_to_anchor((0.35, 0.95, 0, 0))

        fig = ax.get_figure()
        return None, ax, leg
    else:
        if kind == 'continuous' and not isinstance(df[column].values[0],
                                                   (int, float)):
            try:
                df[column] = df[column].astype(float)
                df[column].replace(np.inf, np.nan, inplace=True)
            except ValueError:
                kind = 'discrete'

        ax = df.dropna(subset=[column]).plot(column=column,
                                             edgecolor=edgecolor,
                                             cmap=cmap,
                                             alpha=alpha,
                                             ax=ax,
                                             linewidth=lw)

        vmin, vmax = min(df[column].values), max(df[column].values)
    ax.axis('off')
    fig = ax.get_figure()

    if column == None:
        return fig, ax

    #if  discrete variable you want steps cb
    if kind is 'discrete':
        nc = df[column].unique()
        cmap = discrete_cmap(len(nc), base_cmap=cmap)

    # location of colorbar is tuned to the shape of NYC: sits above SI, west of Manhattan
    if cb:
        if not side:
            x0 = 0.2
        elif isinstance(side, float):
            x0 = side
        else:
            x0 = 0.9
        if not width:
            width = 0.03

        cax = fig.add_axes([x0, 0.41, width, 0.44])

        if kind is 'discrete':
            sm = mpl.colorbar.ColorbarBase(
                ax=cax,
                cmap=cmap,
                norm=pl.Normalize(vmin=vmin - .5, vmax=vmax + .5),
                #spacing='uniform',
                orientation='vertical')

        else:
            sm = mpl.colorbar.ColorbarBase(ax=cax,
                                           cmap=cmap,
                                           norm=pl.Normalize(vmin=vmin,
                                                             vmax=vmax),
                                           ticks=range(spacing + 1),
                                           spacing='uniform',
                                           orientation='vertical')

        sm._A = []

        if kind is 'discrete':
            cb = fig.colorbar(sm,
                              cax=cax,
                              ticks=np.linspace(vmin, vmax, len(nc)))
            cb.ax.set_yticklabels(['%s' % (c) for c in np.sort(nc)])
        else:
            cb = fig.colorbar(sm, cax=cax)
    return fig, ax, cb
Пример #24
0
    def plot_regions_interest(self, maze_id=0, report=None):
        fig, ax = plt.subplots()

        interests = self.compute_all_interests()
        interest_lims = (min(interests), max(interests))
        normal = pylab.Normalize(*interest_lims)

        colors = pylab.cm.YlOrRd(normal(interests))

        for region, color in zip(self.regions, colors):
            lengths = region.max_border - region.min_border
            ax.add_patch(
                patches.Rectangle(region.min_border,
                                  *lengths,
                                  fill=True,
                                  edgecolor='k',
                                  facecolor=color))

        cax, _ = cbar.make_axes(ax)
        print("the interest lims are: ", interest_lims)
        cb2 = cbar.ColorbarBase(cax, cmap=pylab.cm.YlOrRd, norm=normal)
        ax.set_xlim(self.state_bounds[0][0], self.state_bounds[1][0])
        ax.set_ylim(self.state_bounds[0][1], self.state_bounds[1][1])

        if maze_id == 0:
            ax.add_patch(
                patches.Rectangle((-3, -3),
                                  10,
                                  2,
                                  fill=True,
                                  edgecolor="none",
                                  facecolor='0.4',
                                  alpha=0.3))
            ax.add_patch(
                patches.Rectangle((-3, -1),
                                  2,
                                  6,
                                  fill=True,
                                  edgecolor="none",
                                  facecolor='0.4',
                                  alpha=0.3))
            ax.add_patch(
                patches.Rectangle((-3, 5),
                                  10,
                                  2,
                                  fill=True,
                                  edgecolor="none",
                                  facecolor='0.4',
                                  alpha=0.3))
            ax.add_patch(
                patches.Rectangle((5, -1),
                                  2,
                                  6,
                                  fill=True,
                                  edgecolor="none",
                                  facecolor='0.4',
                                  alpha=0.3))
            ax.add_patch(
                patches.Rectangle((-1, 1),
                                  4,
                                  2,
                                  fill=True,
                                  edgecolor="none",
                                  facecolor='0.4',
                                  alpha=0.3))
        elif maze_id == 11:
            ax.add_patch(
                patches.Rectangle((-7, 5),
                                  14,
                                  2,
                                  fill=True,
                                  edgecolor="none",
                                  facecolor='0.4',
                                  alpha=0.3))
            ax.add_patch(
                patches.Rectangle((5, -5),
                                  2,
                                  10,
                                  fill=True,
                                  edgecolor="none",
                                  facecolor='0.4',
                                  alpha=0.3))
            ax.add_patch(
                patches.Rectangle((-7, -7),
                                  14,
                                  2,
                                  fill=True,
                                  edgecolor="none",
                                  facecolor='0.4',
                                  alpha=0.3))
            ax.add_patch(
                patches.Rectangle((-7, -5),
                                  2,
                                  10,
                                  fill=True,
                                  edgecolor="none",
                                  facecolor='0.4',
                                  alpha=0.3))
            ax.add_patch(
                patches.Rectangle((-1, 1),
                                  6,
                                  2,
                                  fill=True,
                                  edgecolor="none",
                                  facecolor='0.4',
                                  alpha=0.3))
            ax.add_patch(
                patches.Rectangle((-3, -3),
                                  2,
                                  6,
                                  fill=True,
                                  edgecolor="none",
                                  facecolor='0.4',
                                  alpha=0.3))
            ax.add_patch(
                patches.Rectangle((-1, -3),
                                  4,
                                  2,
                                  fill=True,
                                  edgecolor="none",
                                  facecolor='0.4',
                                  alpha=0.3))

        regions_fig = save_image(fig)

        if report is None:
            return regions_fig
        else:
            report.add_image(
                regions_fig,
                'Interest per region:\nthe number of regions is: {}'.format(
                    len(self.regions)))
Пример #25
0
def plot_W_DBZ_T_WZ(w, dbz, t, pp, xx, yy, height, time, member, \
                    glat=None, glon=None, sfc=False, \
                    out_prefix=None, vector=False, noshow=False, zoom=None):

    filename = "%s_%2.2imin_%2.2dkm" % (out_prefix, int(time),
                                        int(height / 1000.))

    fig, (ax1, ax2, ax3, ax4) = plt.subplots(1,
                                             4,
                                             sharey=True,
                                             figsize=figsize)

    #----

    if (dbz.size > 0):

        clevels = N.arange(_min_dbz, _max_dbz + 2.5, 2.5)
        plot    = ax1.contourf(xx, yy, N.clip(dbz,_min_dbz,_max_dbz), \
              clevels, cmap=_ref_cmap)

        divider = make_axes_locatable(ax1)
        cax = divider.append_axes('right', size='5%', pad=0.05)
        fig.colorbar(plot, cax=cax, orientation='vertical', label='dBZ')

        plot = ax1.contour(xx,
                           yy,
                           dbz,
                           _dbz_clevels[::2],
                           colors='k',
                           linewidths=0.5)
        title = ("Reflectivity")
        ax1.set_aspect('equal', 'datalim')
        ax1.set_title(title, fontsize=10)
        if zoom:
            ax1.set_xlim(1000 * zoom[0], 1000 * zoom[1])
            ax1.set_ylim(1000 * zoom[2], 1000 * zoom[3])

        at = AnchoredText(
            "Max dBZ: %4.1f" % (dbz.max()),
            loc=4,
            prop=dict(size=6),
            frameon=True,
        )
        at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2")
        ax1.add_artist(at)

#----

    scale_w_clevels = min(max(N.int(height / 1000.), 1.0), 6.0)
    clevels = scale_w_clevels * N.arange(-10., 11., 1.)
    wmask = np.ma.masked_array(w, mask=[N.abs(w) <= scale_w_clevels * _min_w])
    if (wmask.size > 0):
        plot = ax2.contourf(xx, yy, wmask, clevels, cmap='bwr')

        divider = make_axes_locatable(ax2)
        cax = divider.append_axes('right', size='5%', pad=0.05)
        fig.colorbar(plot,
                     cax=cax,
                     orientation=_cbar_orien,
                     label=('W %s' % ("$m s^{-1}$")))

        plot = ax2.contour(xx,
                           yy,
                           wmask,
                           clevels[::2],
                           colors='k',
                           linewidths=0.5)

        title = ("Vertical Velocity")
        ax2.set_title(title, fontsize=10)
        if zoom:
            ax2.set_xlim(1000 * zoom[0], 1000 * zoom[1])
            ax2.set_ylim(1000 * zoom[2], 1000 * zoom[3])

        at = AnchoredText("Max W: %4.1f \n Min W: %4.1f" % (w.max(),w.min()), \
                          loc=4, prop=dict(size=6), frameon=True,)
        at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2")
        ax2.add_artist(at)

#--

    clevels = N.arange(-20., 21., 1.)
    if (pp.size > 0):
        plot = ax3.contourf(xx, yy, pp, clevels, cmap='bwr')

        divider = make_axes_locatable(ax3)
        cax = divider.append_axes('right', size='5%', pad=0.05)
        fig.colorbar(plot,
                     cax=cax,
                     orientation=_cbar_orien,
                     label='pertP (mb)')

        plot = ax3.contour(xx,
                           yy,
                           pp,
                           clevels[::2],
                           colors='k',
                           linewidths=0.5)

        title = ("Pert. Pressure in mb)")
        ax3.set_title(title, fontsize=10)

        if zoom:
            ax3.set_xlim(1000 * zoom[0], 1000 * zoom[1])
            ax3.set_ylim(1000 * zoom[2], 1000 * zoom[3])

        at = AnchoredText("Max pertP: %4.1f \n Min pertP: %4.1f" % (pp.max(),pp.min()), \
                          loc=4, prop=dict(size=6), frameon=True,)
        at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2")
        ax3.add_artist(at)

#---

    if (not vector):
        clevels = N.arange(-12., 13., 1.)
        plot = ax4.contourf(xx, yy, t, clevels, cmap='bwr')

        divider = make_axes_locatable(ax4)
        cax = divider.append_axes('right', size='5%', pad=0.05)
        fig.colorbar(plot, cax=cax, orientation=_cbar_orien, label='pertT (K)')

        plot = ax4.contour(xx, yy, t, clevels[::2], colors='k', linewidths=0.5)
        title = ("Pert. Pot. Temperature")
        ax4.set_title(title, fontsize=10)

        if zoom:
            ax4.set_xlim(1000 * zoom[0], 1000 * zoom[1])
            ax4.set_ylim(1000 * zoom[2], 1000 * zoom[3])

        at = AnchoredText(
            "Max pertT: %4.1f \n Min pertT: %4.1f" % (t.max(), t.min()),
            loc=4,
            prop=dict(size=6),
            frameon=True,
        )
        at.patch.set_boxstyle("round,pad=0.,rounding_size=0.2")
        ax4.add_artist(at)

    else:  # Plot wind vectors
        ax4.set_title("Vert Velocity & Horizontal Wind", fontsize=10)
        scale_w_clevels = min(max(N.int(height / 1000.), 1.0), 6.0)
        clevels = scale_w_clevels * N.arange(-10., 11., 1.)
        wmask = np.ma.masked_array(w,
                                   mask=[N.abs(w) <= scale_w_clevels * _min_w])
        #  ax4.contourf(xx, yy, wmask, clevels, cmap='bwr')
        ax4.contour(xx, yy, w, clevels[::2], colors='k', linewidths=1.0)

        spd = np.sqrt(t[0, :, :]**2 + t[1, :, :]**2)

        plot = ax4.quiver(xx[::2,::2], yy[::2,::2], t[0,::2,::2], t[1,::2,::2], spd[::2,::2],
                   pivot='middle', color='black', width=_vec_w, \
                   cmap=plt.get_cmap('YlOrRd'), norm=plt.Normalize(vmin=5.0, vmax=60.), \
                   angles='xy', scale_units='xy', scale=_vector_scale)

        divider = make_axes_locatable(ax4)
        cax = divider.append_axes('right', size='5%', pad=0.05)
        fig.colorbar(plot,
                     cax=cax,
                     orientation=_cbar_orien,
                     label=('W %s' % ("$m s^{-1}$")))

#------- finish

    title = ("\n Time:  %s  min      Height:  %4.2f km" %
             (time, height / 1000.))
    fig.suptitle(title, fontsize=12)

    if output_format != None:
        new_filename = "%s.%s" % (filename, output_format)
        print("\n Saving file %s" % (new_filename))
        fig.savefig(new_filename, format=output_format, dpi=300)

    if interactive and not noshow:
        print(filename)
        os.system("open %s" % new_filename)

    return filename
contour_sets = []
for i in range(h):
    for j in range(l):
        print("i,j", i, j)
        x, y = np.meshgrid(np.arange(0, l1, 1), np.arange(0, l2, 1))
        z = Alpha[(i) * l + j].reshape((l2, l1))
        levels = MaxNLocator(nbins=15).tick_values(z.min(), z.max())
        im = axarr[i, j].contourf(x,
                                  y,
                                  z,
                                  50,
                                  cmap=plt.cm.rainbow,
                                  levels=levels,
                                  vmax=z_max,
                                  vmin=z_min)

f.subplots_adjust(bottom=0.1,
                  top=0.9,
                  left=0.1,
                  right=0.8,
                  wspace=0.3,
                  hspace=0.3)
cb_ax = f.add_axes([0.83, 0.1, 0.02, 0.8])
sm = plt.cm.ScalarMappable(cmap=plt.cm.rainbow,
                           norm=plt.Normalize(vmin=z_min, vmax=z_max))
sm._A = []
plt.colorbar(sm, cax=cb_ax)
plt.suptitle("Modélisation de l'APS pour {} images de tailles {}x{}".format(
    N, l1, l2))

plt.show()
Пример #27
0
            ax.errorbar(row['RA'],
                        row['Dec'],
                        linestyle='none',
                        color=pl.cm.jet((row['Velocity']-50)/20.),
                        marker=marker,
                        xerr=row['eRA'],
                        yerr=row['eDec'],
                        transform=ax.get_transform('fk5'),
                       )

        ax.axis([pmask2.bbox.ixmin-pmask.bbox.ixmin,
                 pmask2.bbox.ixmax-pmask.bbox.ixmin,
                 pmask2.bbox.iymin-pmask.bbox.iymin,
                 pmask2.bbox.iymax-pmask.bbox.iymin])
        ax.set_aspect('equal')
        sm = pl.cm.ScalarMappable(cmap=pl.cm.jet, norm=pl.Normalize(50,70))
        sm._A = []
        cb = fig.colorbar(sm,
                          fig.add_axes([0.90, 0.1, 0.05, 0.8]))
        cb.set_label("Velocity (km/s)")

        fig.savefig("../figures/masers_on_continuum_velocities_epoch{0}_{1}.pdf".format(epoch, line),
                    bbox_inches='tight')


epochs = ['02-Oct-2016', '26-Dec-2016', '30-Dec-2016', '07-Jan-2017']
epochs = [datetime.datetime.strptime(x, '%d-%b-%Y') for x in epochs]

tbl.add_column(Column(name='Date', data=[epochs[row['Epoch']] for row in tbl], dtype='datetime64[s]'))

times = [datetime.datetime.utcfromtimestamp((dt64 - np.datetime64('1970-01-01T00:00:00Z')) / np.timedelta64(1, 's'))
Пример #28
0
def plot_hist(deltas,
              concs,
              pointToRemove=[-1],
              minConc=8,
              maxConc=11,
              binCount=23,
              plotTitle='NIHAO'):
    all_delta_percentages = np.array(deltas)
    all_delta_percentages = all_delta_percentages[np.logical_not(
        np.isnan(all_delta_percentages))]
    n, bins, patches = plt.hist(all_delta_percentages,
                                bins=binCount)  #15 is good, as is 23
    A = np.vstack((np.digitize(all_delta_percentages, bins), concs)).T
    res_lst = np.array([np.mean(A[A[:, 0] == i, 1]) for i in range(len(bins))])
    res_lst[np.isnan(res_lst)] = min(concentrations)
    res_lst = np.array(res_lst)
    maxC = np.average(res_lst)
    minC = np.average(res_lst)
    for i, j in zip(n, res_lst):
        if i < 5:
            continue
        if j < minC:
            minC = j
        if j > maxC:
            maxC = j
    print(maxC)
    maxs.append(maxC)
    print(minC)
    mins.append(minC)
    '''
    if plotTitle == 'Galaxies with AGN':
        minC = 6.3
        maxC = 8.3
    '''
    if minC < 5.5:
        minC = 5.5
    print("n", n)
    print('bins', bins)
    print("A", A)
    print("res_lst", res_lst)
    #minC = 6.5
    #maxC = 12.1
    cmap = plt.get_cmap('plasma')
    #sm = plt.cm.ScalarMappable(cmap='plasma', norm=plt.Normalize(minConc, maxConc))
    sm = plt.cm.ScalarMappable(cmap='plasma', norm=plt.Normalize(minC, maxC))
    #sm = plt.cm.ScalarMappable(cmap='plasma', norm=plt.Normalize(min(res_lst), max(res_lst)))
    sm._A = []

    for i in range(len(patches)):
        if i in pointToRemove:
            patches[i].set_edgecolor('white')
            patches[i].set_facecolor('white')
        else:
            #patches[i].set_facecolor(cmap(norm(res_lst[i],minConc, maxConc) ))
            patches[i].set_facecolor(cmap(norm(res_lst[i], minC, maxC)))
            #patches[i].set_facecolor(cmap(norm(res_lst[i],min(res_lst), max(res_lst) )))
    cbar = plt.colorbar(sm, )
    cbar.set_label('c', rotation=270, fontsize=18)
    plt.ylabel("number of galaxy datapoints", fontsize=18)
    plt.xlabel("$\Delta$ log SFR [M$_\odot$/ year]", fontsize=18)
    plt.xlim(-3, 3)
    plt.yscale('log')
    plt.title(plotTitle)
    #plt.tight_layout()
    plt.savefig(str("plots/10_hist_" + plotTitle.replace(" ", "") + ".png"),
                dpi=300)
    plt.show()
Пример #29
0
sfrEndAtTime = []
sfrEndConc = []

concDict = pickle.load(
    open(fileBaseFalcon + '/2018/pickles/concentrations.pkl', 'rb'))
concentrations = concDict.values()
allConc = []
allMstar = []

cmap = plt.get_cmap('plasma')
#colors = [cmap(i) for i in np.linspace(0, 1, number)]

#hacky code for getting a colorbar
sm = plt.cm.ScalarMappable(cmap='plasma',
                           norm=plt.Normalize(vmin=min(concentrations),
                                              vmax=max(concentrations)))
# fake up the array of the scalar mappable. Urgh...
sm._A = []
#plt.colorbar(sm)

#for a in ['g3.59e12', 'g1.05e13', 'g7.92e12']:
#    galDict.pop(a)
'''
g1 = [g for g in galDict.keys()[0:10]]
g2 = [g for g in galDict.keys()[10:20]]
g3 = [g for g in galDict.keys()[20:30]]
g4 = [g for g in galDict.keys() if g not in g1+g2+g3]
'''

g1 = ['g8.26e11', 'g5.38e11']
g2 = ['g8.26e11', 'g3.21e11']
Пример #30
0
def fission_density_c(sp, case):
    """Generates a csv and png file with results of fission source
    distribution by 1/5 stripes for phase 1a-c of the benchmark
    in the analysis_output folder.

    Parameters
    ----------
    sp: openmc.statepoint.StatePoint
        this statepoint.h5 file is created by running the openmc
        executable on the xml files generated by the build_xml.py
        files and when tallies_on toggle is on True.
    case: str
        case number for naming files
    Returns
    -------
    This function generates a csv file with fission density results
    and visualization of fission source distribution by 1/5 stripe
    for phase 1a-c of the benchmark.
    """

    name = 'analysis_output/' + case + '_c'
    region = ['1', '2', '3', '4', '5']
    fission_rates = []
    num = 1
    for x in range(1, 13):
        mesh_tally = sp.get_tally(name='mesh tally c' + str(x))
        a = mesh_tally.get_pandas_dataframe()
        a = a.drop(columns=['mesh ' + str(x), 'nuclide', 'score'])
        if (x % 2) == 0:
            num = int(x / 2)
            stripe = [str(num) + 'B'] * 5
        else:
            num = int((x + 1) / 2)
            stripe = [str(num) + 'T'] * 5
        a['Region'] = region
        a['Stripe'] = stripe
        if x == 1:
            df = a
        else:
            df = df.append(a)
        b = a['mean'].to_numpy()
        fission_rates.append(b)
    df = df.set_index(['Stripe', 'Region'])
    ave = df['mean'].mean()
    df['Fission Density'] = df['mean'] / ave
    ave_sd = 1 / (len(df['mean'])) * np.sqrt(np.sum(df['std. dev.']**2))
    df['FD std dev'] = df['Fission Density'] * \
        np.sqrt((df['std. dev.'] / df['mean'])**2 + (ave_sd / ave)**2)
    df['Relative unc.'] = df['FD std dev'] / df['Fission Density']
    df.to_csv(name + '.csv')

    xs = []
    ys = []
    ws = np.array([F_len / 5] * 60)
    hs = np.array([F_width] * 60)
    fission_rates /= np.mean(fission_rates)
    vs = fission_rates.flatten()

    for p in range(6):
        for f in range(2):
            x_trans = p * T['A1']['P']['x']
            y_trans = p * T['A1']['P']['y']
            if f == 1:
                x_trans += T['A1']['F']['x']
                y_trans += T['A1']['F']['y']
            for s in range(5):
                if s > 0:
                    x_trans += F_len / 5
                xs.append(V['A1']['F']['L']['x'] + x_trans)
                ys.append(V['A1']['F']['B']['y'] + y_trans)

    normal = pl.Normalize(vs.min(), vs.max())
    colors = pl.cm.YlOrRd(normal(vs))

    fig, ax = plt.subplots()
    for x, y, w, h, c in zip(xs, ys, ws, hs, colors):
        rect = pl.Rectangle((x, y), w, h, color=c)
        ax.add_patch(rect)

    cax, _ = cbar.make_axes(ax)
    cb2 = cbar.ColorbarBase(cax, cmap=pl.cm.YlOrRd, norm=normal)

    ax.set_xlim(-25, 12)
    ax.set_ylim(-25, 0)
    ax.set_xlabel('x [cm]')
    ax.set_ylabel('y [cm]')
    ax.set_title('Case ' + case + ': Normalized Fission Source')
    pl.savefig(name, bbox_inches='tight')
    return