예제 #1
0
def plot_snr_image(img, ivm, levels=(-1.5, 1.5,)):
    img, imgext = parse_ext(img)
    ivm, ivmext = parse_ext(ivm)
    data = fits.getdata(img, ext=imgext)

    np.seterr(all='ignore')

    if 'ivm' in ivm or 'wh' in ivm or 'WHT' == ivmext:
        inv_noise = np.sqrt(fits.getdata(ivm, ext=ivmext))
    elif 'rms' in ivm or 'sig' in ivm or 'ERR' == ivmext:
        inv_noise = 1.0 / fits.getdata(ivm, ext=ivmext)
    else:
        print('Unknown weight map format {}'.format(ivm))
        return

    pp.figure()
    # Use linthresh=1 to go linear when we reach the sky noise
    norm = SymLogNorm(linthresh=1)
    pp.imshow(data * inv_noise, interpolation='nearest',
              origin='lower', norm=norm)
    cbar = pp.colorbar()
    ticks = norm.inverse(np.linspace(0, 1, 10))
    cbar.set_ticks(ticks)
    cbar.set_label('S/N')
    if len(levels) > 0:
        pp.contour(data * inv_noise, levels=levels, colors='black')
    pp.title(img)
    pp.show()
def plot_residual_image(old_res, new_res, mode):
    nres = fits.getdata(new_res)
    ores = fits.getdata(old_res)

    cmap = 'hot'
    cnorm = SymLogNorm(linthresh=30, linscale=0.5)

    #
    # Zoomed out
    #
    fig = plt.figure(figsize=(10, 5))
    ax1 = plt.subplot(121, aspect='equal')
    im = plt.imshow(ores, cmap=cmap, norm=cnorm)
    plt.title('Old ' + mode)
    plt.gca().invert_yaxis()

    plt.subplot(122, sharex=ax1, sharey=ax1, aspect='equal')
    plt.imshow(nres, cmap=cmap, norm=cnorm)
    plt.title('New ' + mode)
    plt.gca().invert_yaxis()

    plt.subplots_adjust(right=0.8)
    cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7])
    fig.colorbar(im, cax=cbar_ax)

    #
    # Zoomed in.
    #
    c_pos = [500, 550]
    c_siz = [200, 200]
    nres_c = Cutout2D(nres, c_pos, c_siz)
    ores_c = Cutout2D(ores, c_pos, c_siz)
    cnorm = SymLogNorm(linthresh=30,
                       linscale=0.5,
                       vmin=nres_c.data.min(),
                       vmax=nres_c.data.max())

    fig2 = plt.figure(figsize=(10, 5))
    ax2 = plt.subplot(121, aspect='equal')
    im = plt.imshow(ores_c.data,
                    extent=np.array(ores_c.bbox_original)[::-1].flatten(),
                    cmap=cmap,
                    norm=cnorm)
    plt.title('Old ' + mode)
    plt.gca().invert_yaxis()

    plt.subplot(122, sharex=ax2, sharey=ax2, aspect='equal')
    plt.imshow(nres_c.data,
               extent=np.array(nres_c.bbox_original)[::-1].flatten(),
               cmap=cmap,
               norm=cnorm)
    plt.title('New ' + mode)
    plt.gca().invert_yaxis()

    plt.subplots_adjust(right=0.8)
    cbar_ax = fig2.add_axes([0.85, 0.15, 0.05, 0.7])
    fig2.colorbar(im, cax=cbar_ax)

    plt.show()
    return
예제 #3
0
def plotFinalResults(entry, img, totalSuccess, profile, c_profiles, pRange,
                     gimgMasked, gColumnTotalFine, contamGimg, wpa,
                     subtractGimg, stageDir):
    '''for use after fully subtracting the contaminants'''
    gdx = gimgMasked.shape[1]
    gdy = gimgMasked.shape[0]
    xmin, xmax, ymin, ymax = max(entry['X_IMAGE']-gdx/2., 0), min(entry['X_IMAGE']+gdx/2., img.shape[1]-1), \
                             max(entry['Y_IMAGE']-gdy/2., 0), min(entry['Y_IMAGE']+gdy/2., img.shape[0]-1)

    f, ((directImagePlot, directImageProfilePlot), (grismPlot, grismProfilePlot), (contamPlot, contamProfilePlot), \
        (subtractedPlot, subtractedProfilePlot)) = plt.subplots(4, 2, sharey=True)

    #plot a grism-sized piece of the direct image
    crop = img[ymin:ymax, xmin:xmax]
    directImagePlot.imshow(crop, norm=SymLogNorm(0.1))
    if totalSuccess:
        directImagePlot.set_title('object %i' % entry['NUMBER'])
    else:
        directImagePlot.set_title('object %i (minimization unsuccessful)' %
                                  entry['NUMBER'])

    directImagePlot.set_ylabel('direct')
    directImagePlot.axis([0, gdx, 0, gdy])
    directImageProfile = profile
    for profNum in c_profiles:
        directImageProfile += c_profiles[profNum]

    directImageProfilePlot.plot(directImageProfile, pRange)
    directImageProfilePlot.set_title('profiles')

    #plot the measured grism and its intensity profile
    vmin = np.ma.min(gimgMasked)
    vmax = np.ma.max(gimgMasked)
    grismPlot.imshow(gimgMasked, norm=SymLogNorm(0.1, vmin=vmin, vmax=vmax))
    grismPlot.set_ylabel('grism')
    grismProfilePlot.plot(gColumnTotalFine, pRange)

    #plot the contamination model and its intensity profile
    contamPlot.imshow(contamGimg, norm=SymLogNorm(0.01))
    contamPlot.set_ylabel('model')
    contamProfilePlot.plot(sum(wpa), pRange)

    #plot the subtracted grism and its intensity profile
    subtractedPlot.imshow(subtractGimg,
                          norm=SymLogNorm(0.1, vmin=vmin, vmax=vmax))
    subtractedPlot.set_ylabel('subtracted')
    subtractedProfile = np.ma.average(subtractGimg, axis=-1)
    subtractedProfilePlot.plot(subtractedProfile, xrange(gdy))

    plt.savefig('%s/stages%i.png' % (stageDir, entry['NUMBER']))
    plt.close(f)
    return
예제 #4
0
def plot_comp_forloop(data1, data2, varname, tstep, loga, savedir, var_min,
                      var_max, dpi):

    data_var_t1 = data1[varname][tstep]
    data_var_t2 = data2[varname][tstep]
    var_t = data_var_t2 / data_var_t1

    plt.figure()
    if loga == False:
        var_t.plot(vmin=var_min, vmax=var_max)
    if loga == True:
        var_t.plot(vmin=var_min,
                   vmax=var_max,
                   norm=SymLogNorm(vmin=var_min,
                                   vmax=var_max,
                                   linthresh=1e-8,
                                   linscale=1e-8))

    plt.title(r"\textbf{Variable} " + str(varname) + r" \textbf{at }" +
              str(data1.coords['time'][tstep].values).zfill(9) + ' s')
    plt.axes().set_aspect('equal', 'datalim')
    plt.savefig(savedir +
                str(str(varname) + "_" + str(tstep).zfill(9) + ".png"),
                bbox_inches='tight',
                dpi=dpi)
    plt.close('all')

    return None
예제 #5
0
def plot_density(fignum, wave_title, wave):
    """
    Plots density evolution of a wavefunction
    :param fignum: Tracks the figure number so plots may be rendered simultaneously
    :param wave_title: Name of equation used to predict wave; either GPE or Schrodinger
    :param wave: The propagating wavefunction
    :return:
    """
    plt.figure(fignum)
    fignum += 1
    title = wave_title + ' Evolution'
    # plt.title(title)
    plt.imshow(
        np.abs(wave)**2,
        # some plotting parameters
        origin='lower',
        extent=extent_units,
        aspect=aspect,
        norm=SymLogNorm(vmin=1e-8, vmax=1., linthresh=1e-15))
    plt.xlabel('Position ($\mu$m)')
    plt.ylabel('Time (ms)')
    plt.colorbar()
    plt.tight_layout()
    plt.savefig(savespath + method + title + '.pdf')
    return fignum
예제 #6
0
def plot(PESmtx, ax, bar_val=True, label_val=True, color='RdYlBu'):

    cax = ax.imshow(PESmtx,cmap = color, vmin=-1.,vmax=1.,norm=SymLogNorm(10**-4),\
        extent = [-3.14/2.,3.14/2.,-3.14,3.14])

    fsize = 16
    plt.xticks([-1.5, -.75, 0.0, .75, 1.5],
               ['-1.0', '-0.5', '0.0', '0.5', '1.0'],
               fontsize=fsize)
    plt.yticks([-3, -2, -1, 0, 1, 2, 3],
               ['-3', '-2', '-1', '0', '1', '2', '3'],
               fontsize=fsize)
    if label_val:
        xlab = r' $k ( a/ \pi )$'
        ylab = r'Energy / $\tau$'
        plt.xlabel(xlab, fontsize=fsize)
        plt.ylabel(ylab, fontsize=fsize)

    if bar_val:
        tick_labels = ['-0.500', '-0.005', '0.000', '0.005', '0.500']
        tick_locs = [-0.50, -0.005, 0.00, 0.005, 0.50]
        bar = plt.colorbar(cax, ticks=tick_locs, shrink=0.6)
        bar.set_ticklabels(tick_labels)
        bar.update_ticks()
    return cax
예제 #7
0
파일: _plot.py 프로젝트: silx-kit/pyFAI
def plot2d(result, calibrant=None, label=None, ax=None):
    """Display the caked image in the jupyter notebook

    :param result: instance of Integrate2dResult
    :param calibrant: Calibrant instance to overlay diffraction lines
    :param label: (str) name of the curve

    :param ax: subplot object to display in, if None, a new one is created.
    :return: Matplotlib subplot
    """
    img = result.intensity
    pos_rad = result.radial
    pos_azim = result.azimuthal
    if ax is None:
        _fig, ax = subplots()
    colornorm = SymLogNorm(1,
                           base=10,
                           vmin=numpy.nanmin(img),
                           vmax=numpy.nanmax(img))

    ax.imshow(
        img,
        origin="lower",
        extent=[pos_rad.min(),
                pos_rad.max(),
                pos_azim.min(),
                pos_azim.max()],
        aspect="auto",
        cmap="inferno",
        norm=colornorm)
    if label:
        ax.set_title("2D regrouping")
    else:
        ax.set_title(label)
    ax.set_xlabel(result.unit.label)
    ax.set_ylabel(r"Azimuthal angle $\chi$ ($^{o}$)")
    if calibrant:
        from pyFAI import units
        x_values = None
        twotheta = numpy.array([i for i in calibrant.get_2th()
                                if i])  # in radian
        unit = result.unit
        if unit == units.TTH_DEG:
            x_values = numpy.rad2deg(twotheta)
        elif unit == units.TTH_RAD:
            x_values = twotheta
        elif unit == units.Q_A:
            x_values = (4.e-10 * numpy.pi / calibrant.wavelength) * numpy.sin(
                .5 * twotheta)
        elif unit == units.Q_NM:
            x_values = (4.e-9 * numpy.pi / calibrant.wavelength) * numpy.sin(
                .5 * twotheta)
        if x_values is not None:
            for x in x_values:
                line = lines.Line2D(
                    [x, x], [pos_azim.min(), pos_azim.max()],
                    color='red',
                    linestyle='--')
                ax.add_line(line)
    return ax
예제 #8
0
def main():

    get_file = lambda x: "cru_ts3.23.1901.2014.{0}.100mean.pkl".format(x)

    tair_data = pickle.load(open(FILEPATH + get_file('tmp'), 'rb'))
    rain_data = pickle.load(open(FILEPATH + get_file('pre'), 'rb'))

    sav_patch = pickle.load(open(PATCHPATH, 'rb'))

    fig = plt.figure(figsize=(10, 6), frameon=False)
    fig.add_axes([0, 0, 1.0, 1.0])

    n_plots = 2
    grid = gridspec.GridSpec(n_plots, 1, hspace=0.3)
    subaxs = [plt.subplot(grid[i]) for i in range(n_plots)]

    # Mean Annual Temperature plot
    make_map(subaxs[0], tair_data, sav_patch['clip'], \
             cmap=get_cmap(MAPCOLOR), \
             levels=np.arange(15, 35, 0.5), \
             cticks=np.arange(15, 35, 2.5), \
             title="Global Savanna Bioregion \\\\ Mean Annual Temperature (1901 to 2013)")

    # Mean Annual Rainfall plot
    make_map(subaxs[1], rain_data, sav_patch['clip'], \
             cmap=get_cmap(MAPCOLOR), \
             levels=np.logspace(1, 3, 100), \
             cticks=[10, 50, 100, 200, 500, 1000], \
             norm=SymLogNorm(linthresh=0.3, linscale=0.03), \
             title="Global Savanna Bioregion \\\\ Mean Annual Precipitation (1901 - 2013)")

    plt.savefig(SAVEPATH)
예제 #9
0
def nice_map(wl,
             t,
             d,
             lvls=20,
             linthresh=10,
             linscale=1,
             norm=None,
             linscaley=1,
             cmap='coolwarm',
             **kwargs):
    if norm is None:
        norm = SymLogNorm(linthresh, linscale=linscale)
    con = plt.contourf(wl, t, d, lvls, norm=norm, cmap=cmap, **kwargs)
    cb = plt.colorbar(pad=0.02)
    cb.set_label(sig_label)
    plt.contour(wl,
                t,
                d,
                lvls,
                norm=norm,
                colors='black',
                lw=.5,
                linestyles='solid')

    plt.yscale('symlog',
               linthreshy=1,
               linscaley=linscaley,
               suby=[2, 3, 4, 5, 6, 7, 8, 9])
    plt.ylim(-.5, )
    plt.xlabel(freq_label)
    plt.ylabel(time_label)
    return con
예제 #10
0
def dependencies(deps: DependencyResult, model_output: int = None,
                 *, cmap="RdBu_r", fontcolor_thresh: float = None,
                 text_len: int = None, omit_leading_zero: bool = None, trailing_zeros: bool = None,
                 grid: bool = None, angle_left: bool = None, cbar: bool = None,
                 cbar_label: str = None,
                 ax: plt.Axes = None, figsize: Tuple[float, float] = None, cellsize: float = None, title: str = None):
    if model_output is None and deps.data.ndim != 2:
        n_model_outputs = deps.data.shape[2]
        if n_model_outputs != 1:
            raise ValueError("When plotting dependencies, the model_output argument can only be omitted when "
                             "there is only one model output in the DependencyResult. However, this Dependency "
                             f"stores {n_model_outputs} model outputs. So, please supply model_output.")
        else:
            model_output = 0

    plot_kwargs = {
        "cmap": cmap, "fontcolor_thresh": fontcolor_thresh,
        "text_len": text_len, "omit_leading_zero": omit_leading_zero, "trailing_zeros": trailing_zeros,
        "grid": grid, "angle_left": angle_left, "cbar": cbar, "cbar_label": cbar_label,
        "ax": ax, "figsize": figsize, "cellsize": cellsize, "title": title}
    plot_kwargs = {k: v for k, v in plot_kwargs.items() if v is not None}

    if model_output is None:
        values = deps.data
    else:
        values = deps.data[:, :, model_output]

    labels = [f"{type(om).__name__[0]}~{frag}" for om, frag in deps.reverse_index]
    extremum = max(1, nan_op(np.ma.max, np.abs(values)))
    plot_matrix(values, row_labels=labels, col_labels=labels,
                norm=SymLogNorm(linthresh=0.1, linscale=0.2, vmin=-extremum, vmax=extremum),
                **plot_kwargs)
예제 #11
0
    def norm(self, norm):
        vmin, vmax = self.pixels.norm.vmin, self.pixels.norm.vmax

        if norm == "lin":
            self.pixels.norm = Normalize()
        elif norm == "log":
            vmin = 0.1 if vmin < 0 else vmin
            vmax = 0.2 if vmax < 0 else vmax
            self.pixels.norm = LogNorm(vmin=vmin, vmax=vmax)
            self.pixels.autoscale()  # this is to handle matplotlib bug #5424
        elif norm == "symlog":
            self.pixels.norm = SymLogNorm(linthresh=1.0,
                                          base=10,
                                          vmin=vmin,
                                          vmax=vmax)
            self.pixels.autoscale()
        elif isinstance(norm, Normalize):
            self.pixels.norm = norm
        else:
            raise ValueError(
                "Unsupported norm: '{}', options are 'lin',"
                "'log','symlog', or a matplotlib Normalize object".format(
                    norm))

        self.update()
        self.pixels.autoscale()
예제 #12
0
    def plot_heatmap_corridor(plotdata,
                              c,
                              unit,
                              figsize=(15, 12),
                              cmap='Blues',
                              vmin=None,
                              vmax=None):
        if unit == 'mln':
            plotdata = plotdata / 1e6
            c = c.replace('(', '(mln ')
        elif unit == '1000':
            plotdata = plotdata / 1e3
            c = c.replace('(', '(x1000 ')
        if plotdata.abs().max().max() > 100:
            format = '.0f'
        else:
            format = '.1f'

        f, ax = plt.subplots(figsize=figsize)
        sns.heatmap(plotdata.T,
                    cmap=cmap,
                    annot=True,
                    fmt=format,
                    ax=ax,
                    norm=SymLogNorm(1),
                    cbar=False,
                    vmin=vmin,
                    vmax=vmax)
        plt.xlabel('Herkomst')
        plt.ylabel('Bestemming')
        plt.title(f'{c} - {scenarios.Qref}')
예제 #13
0
 def get_norm(self):
     """
     This will create a matplotlib.colors.Normalize from selected idx, limits and powerscale
     """
     idx = self.norm.currentIndex()
     if self.autoscale.isChecked():
         cmin = cmax = None
     else:
         cmin = self.cmin_value
         cmax = self.cmax_value
     if NORM_OPTS[idx] == 'Power':
         if self.powerscale.hasAcceptableInput():
             self.powerscale_value = float(self.powerscale.text())
         return PowerNorm(gamma=self.powerscale_value, vmin=cmin, vmax=cmax)
     elif NORM_OPTS[idx] == "SymmetricLog10":
         return SymLogNorm(
             1e-8 if cmin is None else max(1e-8,
                                           abs(cmin) * 1e-3),
             vmin=cmin,
             vmax=cmax)
     elif NORM_OPTS[idx] == "Log":
         cmin = MIN_LOG_VALUE if cmin is not None and cmin <= 0 else cmin
         return LogNorm(vmin=cmin, vmax=cmax)
     else:
         return Normalize(vmin=cmin, vmax=cmax)
예제 #14
0
def plot_mosaic(mosaic, outfile, node_ranks, coarsen):
    """ Given a mosaic, plot it to outfile. """

    cmap = cm.plasma_r
    cmap.set_under(color="white")
    if not isinstance(mosaic, np.ndarray):
        M = mosaic_to_mat(mosaic, SHIFT)
    else:
        M = mosaic
    if (np.amin(M) < 0):
        plt.matshow(M, cmap="RdBu_r", norm=SymLogNorm(linthresh=SHIFT))
    else:
        plt.matshow(M, cmap=cmap, norm=LogNorm(vmin=vmin(M, 10 * SHIFT)))

    plt.colorbar()
    plt.xlabel("Destination")
    plt.ylabel("Source")

    if not coarsen:
        ax = plt.gca()
        ax.xaxis.set_major_locator(MultipleLocator(node_ranks))
        ax.yaxis.set_major_locator(MultipleLocator(node_ranks))
        plt.grid(True, color="black")

    plt.savefig(outfile)
예제 #15
0
def plotHeatmapInLogarithmicScaleFromFigAxAndData(fig, ax, np_data,
                                                  colorbar_limit_min,
                                                  colorbar_limit_max,
                                                  linthresh, colormap):
    # Logarithmic scale
    heatmap = ax.pcolor(np_data,
                        cmap=colormap,
                        norm=SymLogNorm(vmin=colorbar_limit_min,
                                        vmax=colorbar_limit_max,
                                        linthresh=linthresh))
    # heatmap = ax.pcolor(np_data,  norm=SymLogNorm(vmin=colorbar_limit_min, vmax=colorbar_limit_max,linthresh=linthresh))
    # The ticks of the colorbar are all powers of 10 and also the min and the max of the heatmap
    colorbar_ticks = list(
        set(
            exponentialRangeFromMinAndMax(colorbar_limit_min,
                                          colorbar_limit_max) +
            [colorbar_limit_min, colorbar_limit_max])
    )  # list(set(...)) so the duplicates are eliminated
    cbar = fig.colorbar(
        heatmap,
        ticks=colorbar_ticks,
        format=matplotlib.ticker.FuncFormatter(
            lambda x, p: logTickerToString(x, p))
    )  # I create a lambda instead of just putting the function name so it's more explicit that it's a function and that it receives x and p
    # Change font size in color bar
    cbar.ax.tick_params(labelsize=10)
예제 #16
0
    def test_that_masked_data_in_symmetric_log_mode_will_cause_a_switch_back_to_linear_normalisation(
            self):
        image = plt.imshow(self.data,
                           cmap="plasma",
                           norm=SymLogNorm(1e-8, vmin=0.01, vmax=1.0))
        masked_image = plt.imshow(self.masked_data,
                                  cmap="plasma",
                                  norm=SymLogNorm(1e-8, vmin=0.01, vmax=1.0))

        self.widget.set_mappable(image)
        self.widget.norm.setCurrentIndex(NORM_OPTS.index("SymmetricLog10"))
        self.widget.set_mappable(masked_image)

        self.assertEqual(self.widget.norm.currentIndex(),
                         NORM_OPTS.index("Linear"))
        self.assertTrue(isinstance(masked_image.norm, Normalize))
예제 #17
0
def plot_snapshots(Hs, flowparams, delta, g):
    fig = plt.figure(1, (10., 5.))
    grid = AxesGrid(
        fig,
        111,  # similar to subplot(111)
        nrows_ncols=(2, int(Hs.shape[0] / 2)),  # creates grid of axes
        axes_pad=0.25,  # pad between axes in inch.
        label_mode='L',  # put labels on left, bottom
        cbar_mode=
        'single',  # one color bar (default: right of last image in grid)
        cbar_pad=0.20,  # insert space between plots and color bar
        cbar_size='10%'  # size of colorbar relative to last image
    )

    # create individual snapshots - figures are still addressed by single index,
    # despite multi-row grid
    Hmin = -0.5 * g
    Hmax = 10 * delta
    for s in range(Hs.shape[0]):
        img = grid[s].imshow(
            Hs[s],
            cmap=plt.get_cmap('RdBu_r'),  # choose color map
            interpolation='nearest',
            norm=SymLogNorm(linthresh=1e-10, vmin=Hmin,
                            vmax=Hmax),  # normalize 
            vmin=Hmin,  # min/max values for data
            vmax=Hmax)

        # tune plots: switch off tick marks, ensure that plots retain aspect ratio
        grid[s].set_title('$s=%s$' % flowparams[s])
        grid[s].tick_params(bottom='off', top='off', left='off', right='off')

        grid[s].set_xticks([0, 1, 2, 3, 4, 5])
        grid[s].set_yticks([0, 1, 2, 3, 4, 5])
        grid[s].set_xticklabels(['$0$', '$1$', '$2$', '$3$', '$4$', '$5$'])
        grid[s].set_yticklabels(['$0$', '$1$', '$2$', '$3$', '$4$', '$5$'])

    cbar = grid.cbar_axes[0]
    plt.colorbar(img,
                 cax=cbar,
                 ticks=[
                     -1.0e-1, -1.0e-3, -1.0e-5, -1.0e-7, -1.09e-9, 0., 1.0e-9,
                     1.0e-7, 1.0e-5, 1.0e-3, 0.1, 10.0
                 ])

    cbar.axes.set_yticklabels([
        '$-10^{-1}$', '$-10^{-3}$', '$-10^{-5}$', '$-10^{-7}$', '$-10^{-9}$',
        '$0.0$', '$10^{-9}$', '$10^{-7}$', '$10^{-5}$', '$10^{-3}$',
        '$10^{-1}$', '$10$'
    ])
    cbar.set_ylabel('$\mathrm{[a. u.]}$')

    plt.savefig("srg_pairing_delta%2.1f_g%2.1f.pdf" % (delta, g),
                bbox_inches="tight",
                pad_inches=0.05)
    plt.show()

    return
예제 #18
0
파일: colors.py 프로젝트: zkbt/illumination
def cmap_norm_ticks(a,
                    whatpercentiles=[1, 99],
                    howmanysigmaarelinear=1.5,
                    whatfractionislinear=0.15,
                    vmax=None,
                    vmin=None,
                    cmap=None):
    '''
    Return a probably pretty-OK colormap, a color normalization,
    and suggested tick marks for a colorbar, based on an input array.

    Parameters
    ----------

    a : array
            The cmap and norm will be set on the basis of values in this array.
    '''

    if vmin is None:
        gonegative = (a <= 0).any()
    else:
        gonegative = vmin < 0

    # figure out a decent color scale
    if gonegative:
        # go diverging, if this is a difference that crosses zero
        if vmax is not None:
            vmin = -vmax
        else:
            vmin, vmax = np.nanpercentile(a, whatpercentiles)
            scale = np.maximum(np.abs(vmin), np.abs(vmax))
            vmin, vmax = -scale, scale
        span = np.log10(vmax)
        sigma = mad(a)

        norm = SymLogNorm(howmanysigmaarelinear * sigma,
                          linscale=span * whatfractionislinear,
                          vmin=vmin,
                          vmax=vmax)
        if cmap is None:
            cmap = 'RdBu'
        ticks = [
            vmin, -howmanysigmaarelinear * sigma, 0,
            howmanysigmaarelinear * sigma, vmax
        ]
    else:
        if vmax is None:
            vmax = np.nanpercentile(a, whatpercentiles[1])
        if vmin is None:
            vmin = np.nanpercentile(a, whatpercentiles[0])

        # go simple logarithmic, if this is all positive
        norm = LogNorm(vmin=vmin, vmax=vmax)
        if cmap is None:
            cmap = 'Blues'
        ticks = [vmin, vmin * np.sqrt(vmax / vmin), vmax]

    return cmap, norm, ticks
예제 #19
0
def plot_detector_image(input_workspace: EventWorkspace, fig, ax):
    plot = ax.imshow(input_workspace,
                     aspect='auto',
                     cmap='viridis',
                     distribution=True,
                     origin='lower',
                     norm=SymLogNorm(1e-6))
    fig.colorbar(plot, ax=ax)
    ax.set_title("Detector image")
예제 #20
0
def plotpolarimg(data, cmap, INVERT):
    if INVERT == True:
        plt.figure()
        plt.imshow(data,
                   cmap=cmap,
                   extent=[0, 20000, 60, 0],
                   aspect='auto',
                   norm=SymLogNorm(linthresh=3e-02, vmin=-1, vmax=1))
        plt.gca().invert_yaxis()
    elif INVERT == False:
        plt.figure()
        plt.imshow(data,
                   cmap=cmap,
                   extent=[0, 20000, 60, 0],
                   aspect='auto',
                   norm=SymLogNorm(linthresh=3e-02, vmin=-1, vmax=1))
    plt.ylabel('angle theta')
    plt.xlabel('radius from transducer')
예제 #21
0
def test_vmin_vmax_api(test_data_dir, temp_figure_and_axis):
    ds = GasDataSet(1,
                    directory=test_data_dir / "idefix_rwi",
                    geometry="polar")
    fig, ax = temp_figure_and_axis
    p = ds["VX1"].vertical_at_midplane().map("R", "phi")

    # check that no warning is emitted from matplotlib
    im1 = p.plot(fig,
                 ax,
                 vmin=-1,
                 vmax=1,
                 norm=SymLogNorm(linthresh=0.1, base=10))
    im2 = p.plot(fig,
                 ax,
                 norm=SymLogNorm(linthresh=0.1, base=10, vmin=-1, vmax=1))

    npt.assert_array_equal(im1.get_array(), im2.get_array())
def plot_embedding(spec, path):
    spec = spec.transpose(1, 0) # (seq_len, feature_dim) -> (feature_dim, seq_len)
    plt.gcf().clear()
    plt.figure(figsize=(12, 3))
    plt.pcolormesh(spec, norm=SymLogNorm(linthresh=1e-3))
    plt.colorbar()
    plt.tight_layout()
    plt.savefig(path, dpi=300, format="png")
    plt.close()
예제 #23
0
def test_log_symlognorm_cbar():
    # test the undesired minor ticks do not appear if minor
    # ticks visibility is set to True for a pcolormesh with
    # a SymLogNorm
    data = [[0.0001, 0.005], [0.01, 1]]
    plt.rcParams['xtick.minor.visible'] = True
    plt.rcParams['ytick.minor.visible'] = True
    plt.pcolormesh(data, norm=SymLogNorm(0.01))
    plt.colorbar()
예제 #24
0
def plot_bg_full(b, gx, gy):
    fig = plt.figure(figsize=[20,20])
    ax = fig.gca()
    lt = 5
    mm = apply_geom_ij_yx( (gy,gx), ~b.bl.mask )
    bb = apply_geom_ij_yx( (gy,gx), b.bl)
    bb = np.ma.masked_array(bb, ~mm)
    ax.matshow(bb, vmin=-0.15*64, norm=SymLogNorm(0.15*64,lt, base=10))
    ax.set_xticks([])
    ax.set_yticks([])
예제 #25
0
 def log_changed(self, value):
     p = self._cur_plot
     if p is not None and p.ax.images:
         old = p.ax.images[0].norm
         kw = dict(vmin=old.vmin, vmax=old.vmax, clip=old.clip)
         if value:
             n = SymLogNorm(1e-9, **kw)
         else:
             n = Normalize(**kw)
         p.ax.images[-1].norm = n
         p.update()
예제 #26
0
def xm_ploting(var_t,
               ticks,
               var_max,
               var_min,
               varname,
               var_time,
               var_tstp,
               save=False,
               savefile=False,
               loga=False,
               title=True):

    plt.figure()

    if loga == False:
        fig = var_t.plot(vmin=var_min, vmax=var_max)
    elif loga == True:
        fig = var_t.plot(norm=SymLogNorm(vmin=var_min,
                                         vmax=var_max,
                                         linthresh=1e-9,
                                         linscale=1e-9),
                         cbar_kwargs={
                             'ticks': ticks,
                             'format': ticker.FuncFormatter(fmt)
                         })

    if title == True:
        if var_time == 0.0 and var_tstp != 0:
            plt.title(r"\textbf{Variable} " + str(varname) + r" \textbf{at }" +
                      str(var_tstp).zfill(9) + ' timesteps')
        else:
            plt.title(r"\textbf{Variable} " + str(varname) + r" \textbf{at }" +
                      str(var_time).zfill(6) + ' s')
    else:
        plt.title(' ')

    plt.axes().set_aspect('equal', 'datalim')

    plt.xlabel(r'x [m]')
    plt.ylabel(r'y [m]')

    if save == True:
        if savefile == False:
            plt.savefig(
                str(str(varname) + "_" + str(var_tstp).zfill(9) + ".png"),
                bbox_inches='tight',
                dpi=300)  # saving figure
        else:
            plt.savefig(savefile, bbox_inches='tight',
                        dpi=300)  # saving figure
    elif save == False:
        plt.show()

    return None
예제 #27
0
def convolve_im(im: np.array, fft_kernel: np.array, verbose=True):
    """ Convolves the image (im) with the frequency kernel (fft_kernel),
        and returns the resulting image.

        "verbose" can be used for turning on/off visualization
        convolution

    Args:
        im: np.array of shape [H, W]
        fft_kernel: np.array of shape [H, W]
        verbose: bool
    Returns:
        im: np.array of shape [H, W]
    """
    # START YOUR CODE HERE ### (You can change anything inside this block)
    fft = np.fft.fft2(im)
    prod = fft * fft_kernel
    conv_result = np.abs(np.fft.ifft2(prod))
    if verbose:
        # Use plt.subplot to place two or more images beside eachother
        plt.figure(figsize=(20, 4))
        # plt.subplot(num_rows, num_cols, position (1-indexed))
        plt.subplot(2, 3, 1)
        plt.imshow(im, cmap="gray")
        plt.subplot(2, 3, 2)
        plt.imshow(np.abs(np.fft.fftshift(fft)),
                   cmap="gray",
                   norm=SymLogNorm(1))
        plt.subplot(2, 3, 4)
        plt.imshow(np.abs(np.fft.fftshift(fft_kernel)),
                   cmap="gray",
                   norm=SymLogNorm(1))
        plt.subplot(2, 3, 5)
        plt.imshow(np.abs(np.fft.fftshift(prod)),
                   cmap="gray",
                   norm=SymLogNorm(1e-3))
        plt.subplot(2, 3, 6)
        plt.imshow(conv_result, cmap="gray")

    ### END YOUR CODE HERE ###
    return conv_result
def ctamap( obs , emin , emax , \
    coordsys , ra , dec , rad , \
    caldb , irf , name , plotfile ) :
    skymap = ctools.ctskymap() 
    skymap[ 'inobs' ] = obs
    skymap[ 'emin' ] = emin
    skymap[ 'emax' ] = emax
    skymap[ 'nxpix' ] = 100
    skymap[ 'nypix' ] = 100
    skymap[ 'binsz' ] = 0.02
    skymap[ 'proj' ] = 'CAR'
    skymap[ 'coordsys' ] = coordsys
    skymap[ 'xref' ] = ra
    skymap[ 'yref' ] = dec
    skymap[ 'bkgsubtract' ] = 'IRF'
    skymap[ 'caldb' ] = caldb
    skymap[ 'irf' ] = irf
    skymap[ 'outmap' ] = name

    skymap.execute()

    skymap.skymap().smooth( 'GAUSSIAN', 0.02 )

    ax = plt.subplot()
    plt.imshow( skymap.skymap().array() , \
        origin='lower' , \
        extent=[ ra + rad , \
            ra - rad , \
            dec - rad , \
            dec + rad ] , \
        norm=SymLogNorm( 1 , base=10 ) )
    xlabel = '' ; ylabel = '' ;
    if coordsys == 'GAL' :
        xlabel = 'Longitude (deg)'
        ylabel = 'Latitude (deg)'
    elif coordsys == 'CEL' :
        xlabel = 'R.A. (deg)'
        ylabel = 'DEC (deg)'
    else :
        print( 'Unknown coordinate System. \
            I will assume Celestial Coordinate System' )
        xlabel = 'R.A. (deg)'
        ylabel = 'DEC (deg)'
    ax.set_xlabel( xlabel )
    ax.set_ylabel( ylabel )
    cbar = plt.colorbar()
    cbar.set_label( 'Counts' )

    if len( plotfile ) > 0 :
        plt.savefig( plotfile )
    else :
        plt.show()
    plt.close()
예제 #29
0
    def plot_matrix(self) -> plt.Figure:

        fig, ax = plt.subplots()

        idx_mc = 0
        idx_eb = 0

        # Some times the lower edges may be zero, so we skip them

        if self._mc_energies[0] == 0:
            idx_mc = 1

        if self._ebounds[0] == 0:
            idx_eb = 1

        # ax.imshow(image[idx_eb:, idx_mc:], extent=(self._ebounds[idx_eb],
        #                                            self._ebounds[-1],
        #                                            self._mc_energies[idx_mc],
        #                                            self._mc_energies[-1]),
        #           aspect='equal',
        #           cmap=cm.BrBG_r,
        #           origin='lower',
        #           norm=SymLogNorm(1.0, 1.0, vmin=self._matrix.min(), vmax=self._matrix.max()))

        # Find minimum non-zero element
        vmin = self._matrix[self._matrix > 0].min()

        cmap = copy.deepcopy(
            cm.get_cmap(threeML_config.plugins.ogip.response_cmap.value))

        cmap.set_under(threeML_config.plugins.ogip.response_zero_color)

        mappable = ax.pcolormesh(
            self._mc_energies[idx_mc:],
            self._ebounds[idx_eb:],
            self._matrix,
            cmap=cmap,
            norm=SymLogNorm(1.0, 1.0, vmin=vmin, vmax=self._matrix.max()),
        )

        ax.set_xscale("log")
        ax.set_yscale("log")

        fig.colorbar(mappable, label="cm$^{2}$")

        # if show_energy is not None:
        #    ener_val = Quantity(show_energy).to(self.reco_energy.unit).value
        #    ax.hlines(ener_val, 0, 200200, linestyles='dashed')

        ax.set_xlabel("True energy (keV)")
        ax.set_ylabel("Reco energy (keV)")

        return fig
예제 #30
0
def grheat(X, gridbounds, xlabel=None, ylabel=None, zlabel=None):
    """Simple interface to a heatmap (uses matplotlib's `imshow`).

    Parameters
    ----------
    X : numpy.array
        a matrix-like object 
    gridbounds : float or tuple
        the bounds of the grid. If a float, -/+ this value is taken as the bounds
    xlabel : str (optional)
    ylabel : str (optional)
    zlabel : str (optional)
    """

    fig, ax = plt.subplots()

    if isinstance(gridbounds, tuple):
        if isinstance(gridbounds[0], tuple):
            extent = [
                *gridbounds[0],
                *gridbounds[1],
            ]
        else:
            extent = [
                -gridbounds[0],
                gridbounds[0],
                -gridbounds[1],
                gridbounds[1],
            ]
    else:
        extent = [
            -gridbounds,
            gridbounds,
            -gridbounds,
            gridbounds,
        ]

    plt.imshow(X,
               cmap="hot",
               extent=extent,
               vmin=np.nanmin(X),
               vmax=np.nanmax(X),
               norm=SymLogNorm(1, linscale=1))

    clb = plt.colorbar()

    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.grid(False)
    clb.set_label(zlabel)

    plt.tight_layout()
def plotimg(data, cmap, z, zact, INVERT):
    if INVERT == True:
        plt.figure()
        plt.imshow(data,
                   cmap=cmap,
                   extent=[zact - z, zact, z / np.sqrt(3), -z / np.sqrt(3)],
                   aspect='auto',
                   norm=SymLogNorm(linthresh=0.01,
                                   vmin=np.amin(data),
                                   vmax=np.amax(data)))
        plt.gca().invert_yaxis()
    elif INVERT == False:
        plt.figure()
        plt.imshow(data,
                   cmap=cmap,
                   extent=[zact - z, zact, -z / np.sqrt(3), z / np.sqrt(3)],
                   aspect='auto',
                   norm=SymLogNorm(linthresh=0.01,
                                   vmin=np.amin(data),
                                   vmax=np.amax(data)))
    plt.xlabel('mm in z-direction')
    plt.ylabel('mm in x-direction')