예제 #1
0
def test_LogFormatter_sublabel():
    # test label locator
    fig, ax = plt.subplots()
    ax.set_xscale('log')
    ax.xaxis.set_major_locator(mticker.LogLocator(base=10, subs=[]))
    ax.xaxis.set_minor_locator(mticker.LogLocator(base=10,
                                                  subs=np.arange(2, 10)))
    ax.xaxis.set_major_formatter(mticker.LogFormatter(labelOnlyBase=True))
    ax.xaxis.set_minor_formatter(mticker.LogFormatter(labelOnlyBase=False))
    # axis range above 3 decades, only bases are labeled
    ax.set_xlim(1, 1e4)
    fmt = ax.xaxis.get_major_formatter()
    fmt.set_locs(ax.xaxis.get_majorticklocs())
    show_major_labels = [fmt(x) != '' for x in ax.xaxis.get_majorticklocs()]
    assert np.all(show_major_labels)
    _sub_labels(ax.xaxis, subs=[])

    # For the next two, if the numdec threshold in LogFormatter.set_locs
    # were 3, then the label sub would be 3 for 2-3 decades and (2,5)
    # for 1-2 decades.  With a threshold of 1, subs are not labeled.
    # axis range at 2 to 3 decades
    ax.set_xlim(1, 800)
    _sub_labels(ax.xaxis, subs=[])

    # axis range at 1 to 2 decades
    ax.set_xlim(1, 80)
    _sub_labels(ax.xaxis, subs=[])

    # axis range at 0.4 to 1 decades, label subs 2, 3, 4, 6
    ax.set_xlim(1, 8)
    _sub_labels(ax.xaxis, subs=[2, 3, 4, 6])

    # axis range at 0 to 0.4 decades, label all
    ax.set_xlim(0.5, 0.9)
    _sub_labels(ax.xaxis, subs=np.arange(2, 10, dtype=int))
예제 #2
0
def test_LogFormatter_sublabel():
    # test label locator
    fig, ax = plt.subplots()
    ax.set_xscale('log')
    ax.xaxis.set_major_locator(mticker.LogLocator(base=10, subs=[]))
    ax.xaxis.set_minor_locator(
        mticker.LogLocator(base=10, subs=np.arange(2, 10)))
    ax.xaxis.set_major_formatter(mticker.LogFormatter())
    ax.xaxis.set_minor_formatter(mticker.LogFormatter(labelOnlyBase=False))
    # axis range above 3 decades, only bases are labeled
    ax.set_xlim(1, 1e4)
    fmt = ax.xaxis.get_major_formatter()
    fmt.set_locs(ax.xaxis.get_majorticklocs())
    show_major_labels = [fmt(x) != '' for x in ax.xaxis.get_majorticklocs()]
    assert np.all(show_major_labels)
    _sub_labels(ax.xaxis, subs=[])

    # axis range at 2 to 3 decades, label sub 3
    ax.set_xlim(1, 800)
    _sub_labels(ax.xaxis, subs=[3])

    # axis range at 1 to 2 decades, label subs 2 and 5
    ax.set_xlim(1, 80)
    _sub_labels(ax.xaxis, subs=[2, 5])

    # axis range at 0 to 1 decades, label subs 2, 3, 6
    ax.set_xlim(1, 8)
    _sub_labels(ax.xaxis, subs=[2, 3, 6])
예제 #3
0
def set_log_minor(ax=None, which="both", subs=(2, 5)):
    if ax is None: ax = plt.gca()
    if which in ("both", "x"):
        ax.xaxis.set_minor_locator(ticker.LogLocator(subs=subs))
        ax.xaxis.set_minor_formatter(ticker.LogFormatter(labelOnlyBase=False))
    if which in ("both", "y"):
        ax.yaxis.set_minor_locator(ticker.LogLocator(subs=subs))
        ax.yaxis.set_minor_formatter(ticker.LogFormatter(labelOnlyBase=False))
예제 #4
0
def plot_curves(file_name, type_name, show_ylabel=True, show_legend=True):
    json_file = os.path.join(common.result_folder, file_name)
    xlabel = 'num_dexels'
    ylabel = 'time'
    with open(json_file, 'r') as f:
        database = json.load(f)
    # Get list of x entries
    x_array = set()
    for entries in database.values():
        x_array = x_array | set(entry[xlabel] for entry in entries)
    x_array = sorted(x_array)
    # Get list of y entries
    y_arrays = {}
    for i, entries in enumerate(database.values()):
        for entry in entries:
            key = (entry['operation'], entry['radius_relative'])
            if key not in y_arrays:
                y_arrays[key] = numpy.zeros(
                    (len(database.keys()), len(x_array)))
            j = x_array.index(entry[xlabel])
            y_arrays[key][i, j] = entry[ylabel] / 1000
    # Draw plot
    colors = itertools.cycle(('C0', 'C1', 'C2', 'C3'))
    markers = itertools.cycle(('o', '*', 'd', '^'))  # ',', +', '.', 'o', '*')
    linestyles = itertools.cycle(('-', '--', '-.', ':'))
    # plt.figure()
    fig, ax = common.newfig(1)
    show_conv = (type_name == 'loglog')
    for key, y_array in sorted(y_arrays.items()):
        r = key[1]
        c = next(colors)
        e = key[0].title()
        name = '{}, $r = {}$'.format(e, r)
        common.region_plot(x_array, y_array, c, c, name, next(linestyles),
                           next(markers), show_conv)
    if type_name == 'loglog':
        plt.loglog()
        ax.xaxis.set_major_formatter(plticker.LogFormatter(labelOnlyBase=True))
        ax.xaxis.set_minor_formatter(
            plticker.LogFormatter(labelOnlyBase=False,
                                  minor_thresholds=(4, 0.5)))
    plt.xlabel(common.legends[xlabel], fontsize='large')
    if show_ylabel:
        plt.ylabel(common.legends[ylabel], fontsize='large')
    # if show_legend:
    plt.legend(loc='upper left')
    result_plot = os.path.join(
        common.result_folder, ylabel + '_' + os.path.splitext(file_name)[0] +
        '_' + type_name + '.pdf')
    # plt.savefig(result_plot)
    common.savefig(result_plot)
예제 #5
0
def main(config_path):

    src, fs = wav_tools.read_wav('data/src.wav')

    new_brir_path = 'data/test.wav'
    # configs = parse_config_file(config_path)
    # new_config_path = 'config.cfg'
    # new_fig_path = 'test.png'
    # syn_brir(configs, new_config_path, new_brir_path, new_fig_path,
    #      parallel_type=2, n_worker=12)
    new_brir, fs = wav_tools.read_wav(new_brir_path)
    new_record = wav_tools.brir_filter(src, new_brir)
    wav_tools.write_wav(new_record, fs, 'data/new/reverb/15_0387_0.wav')

    brir, fs = wav_tools.read_wav(config_path.replace('cfg', 'wav'))
    record = wav_tools.brir_filter(src, brir)
    wav_tools.write_wav(new_record, fs, 'data/pre/reverb/15_0387_0.wav')

    # brir
    fig, ax = plt.subplots(3, 3, tight_layout=True, figsize=[10, 8])
    ax[0, 0].plot(brir[:, 0])
    ax[0, 0].set_ylabel('brir')
    ax[0, 0].set_title('pre')
    ax[0, 1].plot(new_brir[:, 0])
    ax[0, 1].set_title('new')
    ax[0, 2].plot(brir[:, 0] - new_brir[:, 0])
    ax[0, 2].yaxis.set_major_formatter(ticker.LogFormatter())
    ax[0, 2].set_title('difference')

    ax[1, 0].plot(record[:, 0])
    ax[1, 0].set_ylabel('record')
    ax[1, 1].plot(new_record[:, 0])
    ax[1, 2].plot(record[:, 0] - new_record[:, 0])
    ax[1, 2].yaxis.set_major_formatter(ticker.LogFormatter())

    specgram, freqs, bins, im = ax[2, 0].specgram(record[:, 0],
                                                  Fs=fs,
                                                  NFFT=512,
                                                  noverlap=256,
                                                  cmap='jet')
    new_specgram, freqs, bins, im = ax[2, 1].specgram(new_record[:, 0],
                                                      Fs=fs,
                                                      NFFT=512,
                                                      noverlap=256,
                                                      cmap='jet')
    ax[2, 2].imshow(specgram - new_specgram,
                    aspect='auto',
                    cmap='jet',
                    extent=[bins[0], bins[-1], freqs[0], freqs[-1]])
    fig.savefig('images/validate.png')
예제 #6
0
def plot_prices(df, module_type):
    m = df[module_type + '_mean']
    h = df[module_type + '_high']
    l = df[module_type + '_low']
    fig = plt.figure(figsize=(6, 3.5))
    ax = fig.add_subplot(111)
    ax.semilogy(df.index, m, 'b', lw=2)
    ax.fill_between(df.index, l, h, color='blue', alpha=0.2)
    ax.yaxis.set_minor_locator(
        ticker.LogLocator(base=10, subs=np.arange(2, 10, step=1.0)))
    # ax.yaxis.set_major_locator(ticker.LogLocator(base=10, subs='all'))
    # ax.yaxis.set_minor_locator(ticker.MultipleLocator(0.05))
    plt.ylim((0.2, 2.25))
    # ax.yaxis.set_major_formatter(ticker.ScalarFormatter())
    ax.yaxis.set_minor_formatter(
        ticker.LogFormatter(labelOnlyBase=False, minor_thresholds=(100, 0.01)))
    ax.tick_params(axis='both', which='both')
    years = mdates.YearLocator()  # every year
    yearsFmt = mdates.DateFormatter('%Y')
    ax.xaxis.set_major_locator(years)
    ax.xaxis.set_major_formatter(yearsFmt)
    # months = mdates.MonthLocator()  # every month
    # ax.xaxis.set_minor_locator(months)
    plt.grid(True, 'both')
    plt.xlabel('Time')
    plt.ylabel('Price ($/Watt)')
    plt.title('Historical Prices of ' + module_type + ' Modules')
    fig.savefig(module_type + ".pdf", bbox_inches='tight')

    return fig
예제 #7
0
def init(*fargs):
    # Create colorbar as a legend
    cmap = cm.get_cmap('Reds', 4)
    print(vmin, vmax)

    if log:
        norm = cm.colors.LogNorm(vmin=vmin, vmax=vmax)
    else:
        norm = cm.colors.Normalize(vmin=vmin, vmax=vmax)
    sm = cm.ScalarMappable(cmap=cmap, norm=norm)
    # empty array for the data range
    sm._A = []
    # add the colorbar to the figure
    divider = make_axes_locatable(ax)
    size = "5%"
    cax = divider.append_axes("right", size=size, pad=0.1)
    cbar = fig.colorbar(sm, cax=cax, cmap=cmap)
    cbar.ax.tick_params(labelsize=18)
    vals = list(cbar.ax.get_yticks())
    vals.append(vmax)
    print(vals)
    if log:
        cbar.ax.yaxis.set_major_formatter(mtick.LogFormatter())
    else:
        cbar.ax.yaxis.set_major_formatter(mtick.Formatter())

    cbar.ax.set_yticklabels([int(x) for x in vals])
    cbar.ax.set_ylabel(key, fontsize=20)
예제 #8
0
def logscale_plot(ax, xrange, yrange, base=10):

    from matplotlib import ticker

    if xrange is not None:
        ax.xaxis.set_minor_formatter(ticker.LogFormatter())
        ax.xaxis.set_major_formatter(ticker.LogFormatter())
        ax.set_xscale("log", base=base)
        ax.set_xlim([np.min(xrange), np.max(xrange)])
    if yrange is not None:
        ax.yaxis.set_minor_formatter(ticker.LogFormatter())
        ax.yaxis.set_major_formatter(ticker.LogFormatter())
        ax.set_yscale("log", base=base)
        ax.set_ylim([
            yrange.min() - 0.1 * yrange.min(),
            yrange.max() + 0.1 * yrange.min()
        ])
예제 #9
0
def mozenaPlot(data):
    '''
	create the plot from Mark Mozena's thesis with given data
	Sersic vs Reff vs Axis Ratio
	'''
    condition = np.ones_like(data["red"], bool)
    condition &= data["cam"] != 0
    condition &= data["cam"] != 1
    condition &= (data["red"] > 1.4) & (data["red"] < 2.6)
    condition &= (data["mass"] > 10**8.5) & (data["mass"] < 10**11)
    s = 0.5
    ser = data["ser"][condition]
    rad = data["rad"][condition]
    ba = data["ba"][condition]
    serlim = [0, 5.5]
    serticks = [1, 2, 3, 4, 5]

    serVSrad = plt.subplot(221)
    serVSrad.plot(rad, ser, "bs", ms=s)
    serVSrad.set_xscale("log")
    serVSrad.set_ylabel("Sersic (n)", labelpad=15)
    serVSrad.set_ylim(serlim)
    serVSrad.set_yticks(serticks)
    serVSrad.yaxis.set_minor_locator(ticker.AutoMinorLocator(n=2))
    plt.setp(serVSrad.get_xticklabels(), visible=False)

    baVSrad = plt.subplot(223, sharex=serVSrad)
    baVSrad.plot(rad, ba, "bs", ms=s)
    baVSrad.set_xlabel("$R_{eff}$ (kpc)")
    baVSrad.set_xscale("log")
    baVSrad.set_xlim(0.5, 12)
    baVSrad.set_xticks([1.0, 3.0, 10.0])
    baVSrad.xaxis.set_major_formatter(ticker.LogFormatter(labelOnlyBase=False))
    baVSrad.set_ylabel("Axis Ratio (q)")

    baVSser = plt.subplot(224, sharey=baVSrad)
    baVSser.plot(ser, ba, "bs", ms=s)
    baVSser.set_xlim(serlim)
    baVSser.set_xticks(serticks)
    baVSser.xaxis.set_minor_locator(ticker.AutoMinorLocator(n=2))
    baVSser.set_xlabel("Sersic (n)")
    baVSser.set_ylim(0, 1.05)
    baVSser.set_yticks([0.2, 0.4, 0.6, 0.8, 1.0])
    baVSser.yaxis.set_minor_locator(ticker.AutoMinorLocator(n=2))
    plt.setp(baVSser.get_yticklabels(), visible=False)

    # remove extra space between subplots
    plt.tight_layout(w_pad=0, h_pad=0)

    # these are matplotlib.patch.Patch properties
    props = dict(boxstyle='round', facecolor='wheat', alpha=0.5)
    # place a text box in upper left in axes coords
    textstr = "Simulations\nFour Random Cameras\n$z = 1.4 - 2.6$"
    textstr += "\n$log(M_{\odot}) = 8.5 - 11.0$\n$N = %d$" % len(ser)
    plt.figtext(0.6, 0.9, textstr, fontsize=16,
                verticalalignment='top')  #, bbox=props)
    return
예제 #10
0
def scatter_plot(xs, ys, xlabel, ylabel, title, leg=False):
    width = 505.89

    fig, ax = plt.subplots(1, 1, figsize=set_size(width, fraction=0.5))
    plt.tight_layout()
    plt.gcf().subplots_adjust(bottom=0.2, left=0.2)

    ax.scatter(xs, ys, 1.0, alpha=0.5)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)

    ax.set_yscale('log')
    ax.set_xscale('log')

    lims = [
        np.min([0, 0]),  # min of both axes
        np.max([6000, 500]),  # max of both axes
    ]

    # now plot both limits against eachother
    ax.plot(lims, lims, 'k-', alpha=0.6, label='Ping latency')
    ax.plot(xs, [x * 10 for x in xs],
            '#A62447',
            alpha=0.6,
            label='ARAs bound K=3 ')
    ax.set_ylim([1, 6000.0])
    ax.set_xlim([1, 500])

    bins = np.arange(min(xs), max(xs), 2)
    percentilef = lambda v: np.percentile(v, 50, axis=0)
    means = binned_statistic(xs, ys, statistic=percentilef, bins=bins)[0]
    ax.plot(bins[:-1],
            means,
            'go',
            alpha=0.2,
            markersize=4,
            label="50th percentile")
    percentilef = lambda v: np.percentile(v, 95, axis=0)
    means = binned_statistic(xs, ys, statistic=percentilef, bins=bins)[0]
    ax.plot(bins[:-1],
            means,
            'o',
            markerfacecolor="#A62447",
            markersize=4,
            alpha=0.2,
            label="95th percentile")

    if leg:
        ax.legend(loc='lower right', prop={'size': 6})

    ax.xaxis.set_major_locator(ticker.MultipleLocator(2))
    ax.xaxis.set_major_formatter(
        ticker.LogFormatter(base=2.0,
                            labelOnlyBase=True,
                            minor_thresholds=None,
                            linthresh=None))
예제 #11
0
 def __init__(
     self,
     ax,
     cmap=None,
     norm=None,
     alpha=None,
     values=None,
     boundaries=None,
     orientation='vertical',
     extend='neither',
     spacing='uniform',  # uniform or proportional
     ticks=None,
     format=None,
     drawedges=False,
     filled=True,
 ):
     self.ax = ax
     self._patch_ax()
     if cmap is None: cmap = cm.get_cmap()
     if norm is None: norm = colors.Normalize()
     self.alpha = alpha
     cm.ScalarMappable.__init__(self, cmap=cmap, norm=norm)
     self.values = values
     self.boundaries = boundaries
     self.extend = extend
     self._inside = self._slice_dict[extend]
     self.spacing = spacing
     self.orientation = orientation
     self.drawedges = drawedges
     self.filled = filled
     self.solids = None
     self.lines = None
     self.outline = None
     self.patch = None
     self.dividers = None
     self.set_label('')
     if cbook.iterable(ticks):
         self.locator = ticker.FixedLocator(ticks, nbins=len(ticks))
     else:
         self.locator = ticks  # Handle default in _ticker()
     if format is None:
         if isinstance(self.norm, colors.LogNorm):
             self.formatter = ticker.LogFormatter()
         else:
             self.formatter = ticker.ScalarFormatter()
     elif cbook.is_string_like(format):
         self.formatter = ticker.FormatStrFormatter(format)
     else:
         self.formatter = format  # Assume it is a Formatter
     # The rest is in a method so we can recalculate when clim changes.
     self.config_axis()
     self.draw_all()
예제 #12
0
def stft_pcolormesh(t,
                    f,
                    Zxx,
                    title="STFT Magnitude",
                    xlabel="Time (s)",
                    ylabel="Frequency (Hz)",
                    ylim=None,
                    yscale="log",
                    figsize=(6, 4),
                    options=["grid"],
                    plot_type="pcolormesh",
                    shading="gouraud",
                    max_mag=None,
                    **kwargs):

    tickers = {
        "yaxis": {
            "major": {
                "locator":
                ticker.AutoLocator(),
                "formatter":
                ticker.LogFormatter(labelOnlyBase=False,
                                    minor_thresholds=(np.inf, np.inf))
            }
        }
    }

    mag = np.abs(Zxx)**2

    return FigData(
        xs=t,
        ys=f,
        zs=mag,
        title=title,
        xlabel=xlabel,
        ylabel=ylabel,
        line_options=[{
            "vmin": 0,
            "vmax": np.max(mag) if max_mag is None else max_mag,
            "shading": shading
        }],
        ylim=ylim,
        yscale=yscale,
        figsize=figsize,
        options=options,
        plot_type=plot_type,
        tickers=tickers if yscale == "log" else None,
        fit_data=False,  # This must be False for a 2D zs array
        **kwargs)
예제 #13
0
def plotShear(r, gt, gx, rerr, gterr, gxerr, marker='o', gs=None, **kwargs):
    """ plotShear(r,gt,gx,rerr,gterr,gxerr,marker='o',gs=None,**kwargs)
    """
    from matplotlib import gridspec
    convert = (u.Mpc**(-2)).to(u.pc**(-2))  # plot in units Msun/pc**2
    #convert=1e-14
    if gs is None:
        gs = gridspec.GridSpec(2, 1, height_ratios=[2, 1])
    plt.subplots_adjust(hspace=0.001)

    # gt
    top_ax = plt.subplot(gs[0])
    #top_ax = plt.subplot(211)
    top_ax.set_yticks([0], minor=True)
    top_ax.yaxis.grid(True, which='minor', ls='--')
    top_ax.errorbar(r, (gt * convert),
                    yerr=(gterr * convert),
                    xerr=rerr,
                    marker=marker,
                    ls='None',
                    **kwargs)
    plt.xscale('log')
    #plt.yscale('log')
    #plt.ylabel(r'$\Delta \Sigma_+\ [h 10^{14} M_\odot \mathrm{Mpc}^{-2}]$')
    plt.ylabel(r'$\Delta \Sigma_+\ [h M_\odot \mathrm{pc}^{-2}]$')
    # gx
    bottom_ax = plt.subplot(gs[1], sharex=top_ax)
    #bottom_ax = plt.subplot(212, sharex=top_ax)
    bottom_ax.set_yticks([0], minor=True)
    bottom_ax.yaxis.grid(True, which='minor', ls='--')
    bottom_ax.errorbar(r, (gx * convert),
                       yerr=(gxerr * convert),
                       xerr=rerr,
                       marker=marker,
                       ls='None',
                       **kwargs)
    plt.ylabel(r'$\Delta\Sigma_\times$')
    plt.setp(top_ax.get_xticklabels(), visible=False)
    plt.xlabel(r'R [Mpc/$h$]')
    bottom_ax.xaxis.set_major_formatter(ticker.LogFormatter())
    nbins = len(top_ax.get_yticklabels())  # added
    bottom_ax.yaxis.set_major_locator(
        ticker.MaxNLocator(nbins=usel.floor_to_odd(nbins / 2.),
                           prune='upper'))  # adde
    plt.xlim([r[0] - np.diff(r)[0], r[-1] + np.diff(r)[-1]])
    #plt.tight_layout()
    #plt.subplots_adjust(hspace=0.001)
    return (top_ax, bottom_ax), gs
예제 #14
0
def n_plot(r, dr, n, dn, **kwargs):

    plt.errorbar(r.value,
                 n.value,
                 yerr=dn.value,
                 xerr=dr.value,
                 marker='s',
                 ls='None',
                 **kwargs)
    plt.xscale('log')
    plt.ylabel(r'$n_g\ [{0}]$'.format(n.unit))
    #plt.setp(plt.gca().get_xticklabels(), visible=False)
    plt.gca().xaxis.set_major_formatter(ticker.LogFormatter())
    plt.xlabel('R [{0}]'.format(r.unit))
    plt.xlim(
        [r.value[0] - np.diff(r.value)[0], r.value[-1] + np.diff(r.value)[-1]])
예제 #15
0
    def build_plot(self,
                   xlabel="", ylabel="Overhead w.r.t. native",
                   legend_loc=None,
                   figsize=(12, 2),
                   text_points=(),
                   vline_position=6,
                   title="",
                   ncol=5,
                   build_names="short",
                   **kwargs):

        # rename builds
        self.df.rename(columns=prepare.BUILD_NAMES[build_names], inplace=True)

        logging.info("Building plot")

        style = self.StyleClass(legend_ncol=ncol, legend_loc=legend_loc)
        plot = self.df.plot(
            kind="bar",
            figsize=figsize,
            linewidth=0.5,
            edgecolor=style.bar_edge_color,
            color=style.colors,
            title=title,
            **kwargs
        )
        plot = style.apply(plot)

        if kwargs.get("logy", False) == True:
            plot.set_yscale('log', basey=2)
            plot.yaxis.set_major_formatter(plticker.LogFormatter(base=2))

        # parametrize labels
        plot.set_ylabel(ylabel, fontsize=10)
        plot.set_xlabel("", fontsize=0)  # remove x label

        # vertical line - usually, a delimiter for mean values
        plot.axvline(vline_position, linewidth=0.9, color='grey', dashes=[3, 3])

        # additional text
        for point in text_points:
            plot.text(point[0], point[1], point[2], fontsize=8)

        # save the resulting plot as an object property
        self.plot = plot
def init():
    # Create colorbar as a legend
    cmap = cm.get_cmap('Reds', 4)
    vmin = 1 if "Deaths" in key else 10
    print(vmin, vmax)
    size = "5%" 
    sm = plt.cm.ScalarMappable(cmap=cmap, norm=cm.colors.LogNorm(vmin=vmin, 
                                vmax =vmax))#round(vmax, len(str(vmax))-1)))
    # empty array for the data range
    sm._A = []
    # add the colorbar to the figure
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size = size, pad = 0.1)
    cbar = fig.colorbar(sm, cax=cax, cmap = cmap)
    cbar.ax.tick_params(labelsize=18)
    vals = list(cbar.ax.get_yticks())
    vals.append(vmax)
    print(vals)
    cbar.ax.yaxis.set_major_formatter(mtick.LogFormatter())
    cbar.ax.set_yticklabels([int(x) for x in vals])
    cbar.ax.set_ylabel(key, fontsize = 20)
예제 #17
0
def plotShearEB(r, gt, gx, gterr, gxerr, ax=None, **kwargs):
    """ plotShearV2(r,gt,gx,,gterr,gxerr,marker='o',gs=None,**kwargs)
    """

    convert = (u.Mpc**(-2)).to(u.pc**(-2))  # plot in units Msun/pc**2
    #convert=1e-14
    if ax is None:
        fig, ax = plt.subplots()
    #top_ax = plt.subplot(211)


#    ax.set_yticks([0], minor=True)
#    ax.yaxis.grid(True, which='minor', ls='--')
    ax.errorbar(r, (gt * convert),
                yerr=(gterr * convert),
                marker='o',
                color='k',
                ls='None',
                label='E',
                **kwargs)
    plt.xscale('log')
    #plt.yscale('log')
    #plt.ylabel(r'$\Delta \Sigma_+\ [h 10^{14} M_\odot \mathrm{Mpc}^{-2}]$')
    plt.ylabel(r'$\Delta \Sigma [h M_\odot \mathrm{pc}^{-2}]$')
    # gx
    ax.plot(r * 10**0.01, (gx * convert),
            marker='x',
            color='r',
            ls='None',
            label='B',
            **kwargs)
    plt.xlabel(r'R [Mpc/$h$]')
    ax.xaxis.set_major_formatter(ticker.LogFormatter())
    plt.xlim([r[0] - np.diff(r)[0], r[-1] + np.diff(r)[-1]])
    plt.axhline(y=0, ls=':', c='k')
    #plt.tight_layout()
    #plt.subplots_adjust(hspace=0.001)
    plt.legend()
    return ax
예제 #18
0
    def setTicks(self, fig, ax):
        if self.handlerId == "lineChart" and self.getBooleanOption(
                "logy", False):
            start, end = ax.get_ylim()
            ax.yaxis.set_minor_locator(
                ticker.MultipleLocator((end - start) / 4))
            ax.yaxis.set_minor_formatter(
                ticker.LogFormatter(labelOnlyBase=False))
            ax.grid(True, which='both')

        labels = [s.get_text() for s in ax.get_xticklabels()]
        totalWidth = sum(len(s) for s in labels) * 5
        if totalWidth > self.getPreferredOutputWidth():
            self.needsStretching = self.canStretch()
            if self.isStretchingOn():
                #resize image width
                fig.set_size_inches(
                    min(totalWidth / self.getDPI(), 32768 / self.getDPI()),
                    fig.get_figheight())
            else:
                self.addMessage(
                    "Some labels are not displayed because of a lack of space. Click on Stretch image to see them all"
                )
                #filter down the list to max 20
                max = int(len(labels) / 20)
                if max < 20:
                    xl = [(i, a[:10] + ".." if len(a) > 10 else a)
                          for i, a in enumerate(labels)]
                else:
                    xl = [(i, a) for i, a in enumerate(labels)
                          if (i % max == 0)]
                ax.set_xticks([x[0] for x in xl])
                ax.set_xticklabels([x[1] for x in xl])
                plt.xticks(rotation=30)
        else:
            plt.xticks(rotation=0)
예제 #19
0
 def test_LogFormatter_call(self, val):
     # test _num_to_string method used in __call__
     temp_lf = mticker.LogFormatter()
     temp_lf.axis = FakeAxis()
     assert temp_lf(val) == str(val)
예제 #20
0
 def test_pprint(self, value, domain, expected):
     fmt = mticker.LogFormatter()
     label = fmt._pprint_val(value, domain)
     assert label == expected
예제 #21
0
    def __init__(self, ax, cmap=None,
                           norm=None,
                           alpha=1.0,
                           values=None,
                           boundaries=None,
                           orientation='vertical',
                           extend='neither',
                           spacing='uniform',  # uniform or proportional
                           ticks=None,
                           format=None,
                           drawedges=False,
                           filled=True,
                           ):
        self.ax = ax

        if cmap is None: cmap = cm.get_cmap()
        if norm is None: norm = colors.Normalize()
        self.alpha = alpha
        cm.ScalarMappable.__init__(self, cmap=cmap, norm=norm)
        self.values = values
        self.boundaries = boundaries
        self.extend = extend
        self.spacing = spacing
        self.orientation = orientation
        self.drawedges = drawedges
        self.filled = filled

        # artists
        self.solids = None
        self.lines = None
        self.dividers = None
        self.extension_patch1 = None
        self.extension_patch2 = None

        if orientation == "vertical":
            self.cbar_axis = self.ax.yaxis
        else:
            self.cbar_axis = self.ax.xaxis


        if format is None:
            if isinstance(self.norm, colors.LogNorm):
                # change both axis for proper aspect
                self.ax.xaxis.set_scale("log")
                self.ax.yaxis.set_scale("log")
                self.ax._update_transScale()
                self.cbar_axis.set_minor_locator(ticker.NullLocator())
                formatter = ticker.LogFormatter()
            else:
                formatter = None
        elif cbook.is_string_like(format):
            formatter = ticker.FormatStrFormatter(format)
        else:
            formatter = format  # Assume it is a Formatter

        if formatter is None:
            formatter = self.cbar_axis.get_major_formatter()
        else:
            self.cbar_axis.set_major_formatter(formatter)

        if cbook.iterable(ticks):
            self.cbar_axis.set_ticks(ticks)
        elif ticks is not None:
            self.cbar_axis.set_major_locator(ticks)
        else:
            self._select_locator(formatter)


        self._config_axes()

        self.update_artists()

        self.set_label_text('')
예제 #22
0
def _pprint_helper(value, domain, expected):
    fmt = mticker.LogFormatter()
    label = fmt.pprint_val(value, domain)
    nose.tools.assert_equal(label, expected)
예제 #23
0
    def _set_ticker(self, a):
        try:
            if not isiterable(self.ticks):
                if self.scale == 'linear':
                    a.set_major_locator(mticker.AutoLocator())
                elif self.scale == 'log':
                    a.set_major_locator(mticker.LogLocator(self.base))
                elif self.scale == 'symlog':
                    from matplotlib.scale import SymmetricalLogScale
                    if isMPL33:
                        scale = SymmetricalLogScale(
                            a,
                            base=self.base,
                            linthresh=self.symloglin,
                            linscale=self.symloglinscale)
                    else:
                        scale = SymmetricalLogScale(
                            a,
                            basex=self.base,
                            linthreshx=self.symloglin,
                            linscalex=self.symloglinscale)
                    a.set_major_locator(
                        mticker.SymmetricalLogLocator(scale.get_transform()))


#                    scale.set_default_locators_and_formatters(a)

                else:
                    a.set_major_locator(mticker.AutoLocator())
                #a.get_axes().locator_params(self.name[0], nbins = 10)
                if self.ticks is not None:
                    value = self.ticks
                else:
                    #figpage = a.get_axes().figobj.get_figpage()
                    figpage = a.axes.figobj.get_figpage()
                    if self.name[0] == 'x':
                        value = figpage.getp('nticks')[0]
                    elif self.name[0] == 'y':
                        value = figpage.getp('nticks')[1]
                    elif self.name[0] == 'z':
                        value = figpage.getp('nticks')[2]
                    else:
                        pass
                try:
                    # this works onlyfor MaxNLocator
                    #a.get_axes().locator_params(self.name[0], nbins = value)
                    a.axes.locator_params(self.name[0], nbins=value)
                except BaseException:
                    # for Symlog and LogLocator
                    a.get_major_locator().numticks = value
            else:
                a.set_ticks(self.ticks)

            if self.format == 'default':
                if self.scale == 'linear':
                    a.set_major_formatter(mticker.ScalarFormatter())
                elif self.scale == 'log':
                    a.set_major_formatter(
                        mticker.LogFormatterMathtext(self.base))
                elif self.scale == 'symlog':
                    a.set_major_formatter(
                        mticker.LogFormatterMathtext(self.base))
                else:
                    a.set_major_formatter(mticker.ScalarFormatter())
            elif self.format == 'scalar':
                a.set_major_formatter(mticker.ScalarFormatter())
            elif self.format == 'scalar(mathtext)':
                a.set_major_formatter(
                    mticker.ScalarFormatter(useOffset=True, useMathText=True))
                a.get_major_formatter().get_offset()
            elif self.format == 'log':
                a.set_major_formatter(mticker.LogFormatter(self.base))
            elif self.format == 'log(mathtext)':
                a.set_major_formatter(mticker.LogFormatterMathtext(self.base))
            elif self.format == 'log(exp)':
                a.set_major_formatter(mticker.LogFormatterExponent(self.base))
            elif self.format == 'none':
                a.set_major_formatter(mticker.NullFormatter())
            else:
                a.set_major_formatter(mticker.FormatStrFormatter(self.format))
        except BaseException:
            import traceback
            traceback.print_exc()
예제 #24
0
def test_minlocator_type():
    fig, ax = plt.subplots()
    with pytest.raises(TypeError):
        ax.xaxis.set_minor_locator(mticker.LogFormatter())
예제 #25
0
    def show_image(self):
        self.fig.clf()
        stat_temp = self.get_activated_num()
        stat_temp = OrderedDict(
            sorted(six.iteritems(stat_temp), key=lambda x: x[0]))

        # Check if positions data is available. Positions data may be unavailable
        # (not recorded in HDF5 file) if experiment is has not been completed.
        # While the data from the completed part of experiment may still be used,
        # plotting vs. x-y or scatter plot may not be displayed.
        positions_data_available = False
        if 'positions' in self.data_dict.keys():
            positions_data_available = True

        # Create local copies of self.pixel_or_pos, self.scatter_show and self.grid_interpolate
        pixel_or_pos_local = self.pixel_or_pos
        scatter_show_local = self.scatter_show
        grid_interpolate_local = self.grid_interpolate

        # Disable plotting vs x-y coordinates if 'positions' data is not available
        if not positions_data_available:
            if pixel_or_pos_local:
                pixel_or_pos_local = 0  # Switch to plotting vs. pixel number
                logger.error(
                    "'Positions' data is not available. Plotting vs. x-y coordinates is disabled"
                )
            if scatter_show_local:
                scatter_show_local = False  # Switch to plotting vs. pixel number
                logger.error(
                    "'Positions' data is not available. Scatter plot is disabled."
                )
            if grid_interpolate_local:
                grid_interpolate_local = False  # Switch to plotting vs. pixel number
                logger.error(
                    "'Positions' data is not available. Interpolation is disabled."
                )

        low_lim = 1e-4  # define the low limit for log image
        plot_interp = 'Nearest'

        if self.scaler_data is not None:
            if np.count_nonzero(self.scaler_data) == 0:
                logger.warning('scaler is zero - scaling was not applied')
            elif len(self.scaler_data[self.scaler_data == 0]) > 0:
                logger.warning('scaler data has zero values')

        grey_use = self.color_opt

        ncol = int(np.ceil(np.sqrt(len(stat_temp))))
        try:
            nrow = int(np.ceil(len(stat_temp) / float(ncol)))
        except ZeroDivisionError:
            ncol = 1
            nrow = 1

        a_pad_v = 0.8
        a_pad_h = 0.5

        grid = ImageGrid(self.fig,
                         111,
                         nrows_ncols=(nrow, ncol),
                         axes_pad=(a_pad_v, a_pad_h),
                         cbar_location='right',
                         cbar_mode='each',
                         cbar_size='7%',
                         cbar_pad='2%',
                         share_all=True)

        def _compute_equal_axes_ranges(x_min, x_max, y_min, y_max):
            """
            Compute ranges for x- and y- axes of the plot. Make sure that the ranges for x- and y-axes are
            always equal and fit the maximum of the ranges for x and y values:
                  max(abs(x_max-x_min), abs(y_max-y_min))
            The ranges are set so that the data is always centered in the middle of the ranges

            Parameters
            ----------

            x_min, x_max, y_min, y_max : float
                lower and upper boundaries of the x and y values

            Returns
            -------

            x_axis_min, x_axis_max, y_axis_min, y_axis_max : float
                lower and upper boundaries of the x- and y-axes ranges
            """

            x_axis_min, x_axis_max, y_axis_min, y_axis_max = x_min, x_max, y_min, y_max
            x_range, y_range = abs(x_max - x_min), abs(y_max - y_min)
            if x_range > y_range:
                y_center = (y_max + y_min) / 2
                y_axis_max = y_center + x_range / 2
                y_axis_min = y_center - x_range / 2
            else:
                x_center = (x_max + x_min) / 2
                x_axis_max = x_center + y_range / 2
                x_axis_min = x_center - y_range / 2

            return x_axis_min, x_axis_max, y_axis_min, y_axis_max

        def _adjust_data_range_using_min_ratio(c_min,
                                               c_max,
                                               c_axis_range,
                                               *,
                                               min_ratio=0.01):
            """
            Adjust the range for plotted data along one axis (x or y). The adjusted range is
            applied to the 'extend' attribute of imshow(). The adjusted range is always greater
            than 'axis_range * min_ratio'. Such transformation has no physical meaning
            and performed for aesthetic reasons: stretching the image presentation of
            a scan with only a few lines (1-3) greatly improves visibility of data.

            Parameters
            ----------

            c_min, c_max : float
                boundaries of the data range (along x or y axis)
            c_axis_range : float
                range presented along the same axis

            Returns
            -------

            cmin, c_max : float
                adjusted boundaries of the data range
            """
            c_range = c_max - c_min
            if c_range < c_axis_range * min_ratio:
                c_center = (c_max + c_min) / 2
                c_new_range = c_axis_range * min_ratio
                c_min = c_center - c_new_range / 2
                c_max = c_center + c_new_range / 2
            return c_min, c_max

        for i, (k, v) in enumerate(six.iteritems(stat_temp)):

            quant_norm_applied = False
            if self.quantitative_normalization:
                # Quantitative normalization
                data_dict, quant_norm_applied = self.param_quant_analysis.apply_quantitative_normalization(
                    data_in=self.dict_to_plot[k],
                    scaler_dict=self.scaler_norm_dict,
                    scaler_name_default=self.get_selected_scaler_name(),
                    data_name=k,
                    name_not_scalable=self.name_not_scalable)
            else:
                # Normalize by the selected scaler in a regular way
                data_dict = normalize_data_by_scaler(
                    data_in=self.dict_to_plot[k],
                    scaler=self.scaler_data,
                    data_name=k,
                    name_not_scalable=self.name_not_scalable)

            if pixel_or_pos_local or scatter_show_local:

                # xd_min, xd_max, yd_min, yd_max = min(self.x_pos), max(self.x_pos),
                #     min(self.y_pos), max(self.y_pos)
                x_pos_2D = self.data_dict['positions']['x_pos']
                y_pos_2D = self.data_dict['positions']['y_pos']
                xd_min, xd_max, yd_min, yd_max = x_pos_2D.min(), x_pos_2D.max(
                ), y_pos_2D.min(), y_pos_2D.max()
                xd_axis_min, xd_axis_max, yd_axis_min, yd_axis_max = \
                    _compute_equal_axes_ranges(xd_min, xd_max, yd_min, yd_max)

                xd_min, xd_max = _adjust_data_range_using_min_ratio(
                    xd_min, xd_max, xd_axis_max - xd_axis_min)
                yd_min, yd_max = _adjust_data_range_using_min_ratio(
                    yd_min, yd_max, yd_axis_max - yd_axis_min)

                # Adjust the direction of each axis depending on the direction in which encoder values changed
                #   during the experiment. Data is plotted starting from the upper-right corner of the plot
                if x_pos_2D[0, 0] > x_pos_2D[0, -1]:
                    xd_min, xd_max, xd_axis_min, xd_axis_max = xd_max, xd_min, xd_axis_max, xd_axis_min
                if y_pos_2D[0, 0] > y_pos_2D[-1, 0]:
                    yd_min, yd_max, yd_axis_min, yd_axis_max = yd_max, yd_min, yd_axis_max, yd_axis_min

            else:

                yd, xd = data_dict.shape

                xd_min, xd_max, yd_min, yd_max = 0, xd, 0, yd
                if (yd <= math.floor(xd / 100)) and (xd >= 200):
                    yd_min, yd_max = -math.floor(xd / 200), math.ceil(xd / 200)
                if (xd <= math.floor(yd / 100)) and (yd >= 200):
                    xd_min, xd_max = -math.floor(yd / 200), math.ceil(yd / 200)

                xd_axis_min, xd_axis_max, yd_axis_min, yd_axis_max = \
                    _compute_equal_axes_ranges(xd_min, xd_max, yd_min, yd_max)

            if self.scale_opt == 'Linear':

                low_ratio = self.limit_dict[k]['low'] / 100.0
                high_ratio = self.limit_dict[k]['high'] / 100.0
                if (self.scaler_data is None) and (not quant_norm_applied):
                    minv = self.range_dict[k]['low']
                    maxv = self.range_dict[k]['high']
                else:
                    # Unfortunately, the new normalization procedure requires to recalculate min and max values
                    minv = np.min(data_dict)
                    maxv = np.max(data_dict)
                low_limit = (maxv - minv) * low_ratio + minv
                high_limit = (maxv - minv) * high_ratio + minv

                # Set some minimum range for the colorbar (otherwise it will have white fill)
                if math.isclose(low_limit, high_limit, abs_tol=2e-20):
                    if abs(low_limit) < 1e-20:  # The value is zero
                        dv = 1e-20
                    else:
                        dv = math.fabs(low_limit * 0.01)
                    high_limit += dv
                    low_limit -= dv

                if not scatter_show_local:
                    if grid_interpolate_local:
                        data_dict, _, _ = grid_interpolate(
                            data_dict, self.data_dict['positions']['x_pos'],
                            self.data_dict['positions']['y_pos'])
                    im = grid[i].imshow(data_dict,
                                        cmap=grey_use,
                                        interpolation=plot_interp,
                                        extent=(xd_min, xd_max, yd_max,
                                                yd_min),
                                        origin='upper',
                                        clim=(low_limit, high_limit))
                    grid[i].set_ylim(yd_axis_max, yd_axis_min)
                else:
                    xx = self.data_dict['positions']['x_pos']
                    yy = self.data_dict['positions']['y_pos']

                    # The following condition prevents crash if different file is loaded while
                    #    the scatter plot is open (PyXRF specific issue)
                    if data_dict.shape == xx.shape and data_dict.shape == yy.shape:
                        im = grid[i].scatter(
                            xx,
                            yy,
                            c=data_dict,
                            marker='s',
                            s=500,
                            alpha=1.0,  # Originally: alpha=0.8
                            cmap=grey_use,
                            vmin=low_limit,
                            vmax=high_limit,
                            linewidths=1,
                            linewidth=0)
                        grid[i].set_ylim(yd_axis_max, yd_axis_min)

                grid[i].set_xlim(xd_axis_min, xd_axis_max)

                grid_title = k
                if quant_norm_applied:
                    grid_title += " - Q"  # Mark the plots that represent quantitative information
                grid[i].text(0,
                             1.01,
                             grid_title,
                             ha='left',
                             va='bottom',
                             transform=grid[i].axes.transAxes)

                grid.cbar_axes[i].colorbar(im)
                im.colorbar.formatter = im.colorbar.cbar_axis.get_major_formatter(
                )
                # im.colorbar.ax.get_xaxis().set_ticks([])
                # im.colorbar.ax.get_xaxis().set_ticks([], minor=True)
                grid.cbar_axes[i].ticklabel_format(style='sci',
                                                   scilimits=(-3, 4),
                                                   axis='both')

                #  Do not remove this code, may be useful in the future (Dmitri G.) !!!
                #  Print label for colorbar
                # cax = grid.cbar_axes[i]
                # axis = cax.axis[cax.orientation]
                # axis.label.set_text("$[a.u.]$")

            else:

                maxz = np.max(data_dict)
                # Set some reasonable minimum range for the colorbar
                #   Zeros or negative numbers will be shown in white
                if maxz <= 1e-30:
                    maxz = 1

                if not scatter_show_local:
                    if grid_interpolate_local:
                        data_dict, _, _ = grid_interpolate(
                            data_dict, self.data_dict['positions']['x_pos'],
                            self.data_dict['positions']['y_pos'])
                    im = grid[i].imshow(data_dict,
                                        norm=LogNorm(vmin=low_lim * maxz,
                                                     vmax=maxz,
                                                     clip=True),
                                        cmap=grey_use,
                                        interpolation=plot_interp,
                                        extent=(xd_min, xd_max, yd_max,
                                                yd_min),
                                        origin='upper',
                                        clim=(low_lim * maxz, maxz))
                    grid[i].set_ylim(yd_axis_max, yd_axis_min)
                else:
                    im = grid[i].scatter(
                        self.data_dict['positions']['x_pos'],
                        self.data_dict['positions']['y_pos'],
                        norm=LogNorm(vmin=low_lim * maxz, vmax=maxz,
                                     clip=True),
                        c=data_dict,
                        marker='s',
                        s=500,
                        alpha=1.0,  # Originally: alpha=0.8
                        cmap=grey_use,
                        linewidths=1,
                        linewidth=0)
                    grid[i].set_ylim(yd_axis_min, yd_axis_max)

                grid[i].set_xlim(xd_axis_min, xd_axis_max)

                grid_title = k
                if quant_norm_applied:
                    grid_title += " - Q"  # Mark the plots that represent quantitative information
                grid[i].text(0,
                             1.01,
                             grid_title,
                             ha='left',
                             va='bottom',
                             transform=grid[i].axes.transAxes)

                grid.cbar_axes[i].colorbar(im)
                im.colorbar.formatter = im.colorbar.cbar_axis.get_major_formatter(
                )
                im.colorbar.ax.get_xaxis().set_ticks([])
                im.colorbar.ax.get_xaxis().set_ticks([], minor=True)
                im.colorbar.cbar_axis.set_minor_formatter(
                    mticker.LogFormatter())

            grid[i].get_xaxis().set_major_locator(
                mticker.MaxNLocator(nbins="auto"))
            grid[i].get_yaxis().set_major_locator(
                mticker.MaxNLocator(nbins="auto"))

            grid[i].get_xaxis().get_major_formatter().set_useOffset(False)
            grid[i].get_yaxis().get_major_formatter().set_useOffset(False)

        self.fig.suptitle(self.img_title, fontsize=20)
        self.fig.canvas.draw_idle()
예제 #26
0
def plot_energy_landscape(x,
                          y,
                          values,
                          log_legend=False,
                          title=None,
                          dir_path=None,
                          legend_title=None,
                          legend_min=0,
                          legend_max=None):
    # Clearing the canvas, so we always draw on the empty canvas. Just in case.
    plt.clf()
    x, y = preprocess(x, y)
    fig, ax = plt.subplots()
    XX, YY = np.meshgrid(x, y)
    z = values.reshape(len(x) - 1, len(y) - 1).T
    # ax.grid(True, which='minor', axis='both', linestyle='-', color='k')
    # ax.set_xticks(x, minor=True)
    # ax.set_yticks(y, minor=True)

    ## This is for having ticks in the plot as multiples of pi
    ax.xaxis.set_major_formatter(
        tck.FuncFormatter(lambda val, pos: '{:.2f}$\pi$'.format(val / np.pi)
                          if val != 0 else '0'))
    ax.xaxis.set_major_locator(tck.MultipleLocator(base=np.pi / 4))

    ax.yaxis.set_major_formatter(
        tck.FuncFormatter(lambda val, pos: '{:.2f}$\pi$'.format(val / np.pi)
                          if val != 0 else '0'))
    ax.yaxis.set_major_locator(tck.MultipleLocator(base=np.pi / 4))

    if log_legend:
        mesh_plot = ax.pcolormesh(XX,
                                  YY,
                                  z,
                                  cmap='RdBu',
                                  vmax=legend_max,
                                  norm=LogNorm())
    else:
        mesh_plot = ax.pcolormesh(XX,
                                  YY,
                                  z,
                                  cmap='RdBu',
                                  vmin=legend_min,
                                  vmax=legend_max)

    ax.set_xlabel("beta")
    ax.set_ylabel("gamma")
    if title is None:
        title = "QAOA energy landscape"
    ax.set_title(title)

    # set the limits of the plot to the limits of the data
    ax.axis([x.min(), x.max(), y.min(), y.max()])
    if log_legend:
        cbar_formatter = tck.LogFormatter(10, labelOnlyBase=False)
        cbar = fig.colorbar(mesh_plot, ax=ax, format=cbar_formatter)
    else:
        cbar = fig.colorbar(mesh_plot, ax=ax)

    if legend_title is None:
        legend_title = "energy"
    cbar.set_label(legend_title)

    file_path = title
    if dir_path != None:
        file_path = os.path.join(dir_path, file_path)
    plt.savefig(file_path)
    plt.close()
    return ax
예제 #27
0
def gt_profile(x,
               y,
               g1,
               g2,
               sig_g,
               xc,
               yc,
               zl=None,
               minr=0.1,
               maxr=20,
               nbinr=10,
               cosmo=None,
               a=0.365,
               marker='o',
               correctResponsivity=False,
               **kwargs):
    """ gt_profile(x,y,g1,g1,gw, xc, yc, zl, minr, maxr, nbinr=10, cosmo=None, a=0.365)
    plot tangential shear profile
    """
    gt, gx, r = gT(x, y, g1, g2, xc, yc)
    unit = str(minr.unit)
    if ('pc' in "{0.unit:FITS}".format(minr)):
        r = ((r.to(u.arcmin)) * cosmo.kpc_comoving_per_arcmin(zl)).to(
            getattr(u, unit))
        #d_co = cd.comoving_distance(zl, **cosmo)
        #r = ( r.to(u.rad) * d_co*u.Mpc/u.rad ).to(getattr(u,unit))
    else:
        r = r.to(getattr(u, unit))
    wg = 1 / (sig_g**2 + a**2)
    #sig_g = sig_g/np.sqrt(2) # for each component??
    if correctResponsivity:  ## for regauss
        R = 1. - a**2
    else:  ## no need for KSB
        R = 1  #??
    # binning over radial axis
    gtw, gterr, gterr2, x1, xmin, xmax, Nbin, STD, wbin = usel.Wbinning(
        r,
        gt,
        sig_g,
        wg,
        minr=minr / minr.unit,
        maxr=maxr / minr.unit,
        nbinr=nbinr)
    gxw, gxerr, gxerr2, _, _, _, _, _, _ = usel.Wbinning(r,
                                                         gx,
                                                         sig_g,
                                                         wg,
                                                         minr=minr / minr.unit,
                                                         maxr=maxr / minr.unit,
                                                         nbinr=nbinr)
    xerr = (xmax - xmin) / 2
    gtw, gterr, gterr2, gxw, gxerr, gxerr2 = gtw / (2 * R), gterr / (
        2 * R), gterr2 / (2 * R), gxw / (2 * R), gxerr / (2 * R), gxerr2 / (
            2 * R)  # correct for resopnsivity

    # plot gt,gx
    plt.subplots_adjust(hspace=0.001)
    top_ax = plt.subplot(211)
    top_ax.set_yticks([0], minor=True)
    top_ax.yaxis.grid(True, which='minor', ls='--')
    top_ax.errorbar(x1,
                    gtw,
                    yerr=gterr2,
                    xerr=xerr,
                    marker=marker,
                    ls='None',
                    **kwargs)
    plt.xscale('log')
    plt.ylabel(r'$g_+$')
    bottom_ax = plt.subplot(212, sharex=top_ax)
    bottom_ax.errorbar(x1,
                       gxw,
                       yerr=gxerr2,
                       xerr=xerr,
                       marker=marker,
                       ls='None',
                       **kwargs)
    bottom_ax.set_yticks([0], minor=True)
    bottom_ax.yaxis.grid(True, which='minor', ls='--')
    plt.ylabel(r'$g_\times$')
    plt.setp(top_ax.get_xticklabels(), visible=False)
    plt.xlabel('R [{0}]'.format(unit))
    bottom_ax.xaxis.set_major_formatter(ticker.LogFormatter())
    nbins = len(top_ax.get_yticklabels())  # added
    bottom_ax.yaxis.set_major_locator(
        ticker.MaxNLocator(nbins=nbins, prune='upper'))  # adde
    plt.xlim([x1[0] - np.diff(x1)[0], x1[-1] + np.diff(x1)[-1]])

    return t.Table([x1, xerr, gtw, gterr, gterr2, gxw, gxerr, gxerr2],
                   names=('R [{0}]'.format(unit), 'dR [{0}]'.format(unit),
                          'gt', 'gterr (KSB+)', 'gterr (regauss)', 'gx',
                          'gxerr (KSB+)', 'gxerr (regauss)'))
예제 #28
0
def comp_props(dolines,
               dotypes=['med_8u'],
               clouds=None,
               markers=None,
               indir=None,
               leaves=False,
               cmap_name='gist_rainbow',
               mec='gray',
               xplot=['rad_pc'],
               yplot=['vrms_k'],
               xlims=[[-1, 1.5]],
               ylims=[[-2, 1.5]],
               pltname=['rdv'],
               slope=[0.5],
               pad=[0.03]):

    global axes
    params = {'mathtext.default': 'regular'}
    plt.rcParams.update(params)
    cmap = plt.get_cmap(cmap_name)

    # Table of cloud-averaged properties
    cldtab = Table(names=('cld', 'med_8u', 'med_co', 'avg_st', 'med_24'),
                   dtype=('S6', 'f4', 'f4', 'f4', 'f4'))
    cldtab.add_row(('30Dor', 36.8732, 2.0518, 0.8101, 386.8365))
    cldtab.add_row(('N59C', 8.1936, 3.0875, 0.3671, 12.8014))
    cldtab.add_row(('A439', 2.6004, 3.2009, 0.6587, 1.2010))
    cldtab.add_row(('GMC104', 1.5529, 4.4368, 1.7162, 0.6574))
    cldtab.add_row(('GMC1', 1.1792, 2.0274, 0.3059, 0.5231))
    cldtab.add_row(('PCC', 0.7974, 1.4606, 0.5502, 0.1617))
    # Convert stellar surf density to Msol/pc^2
    cldtab['avg_st'] = cldtab['avg_st'] * 62.5

    # Generate plots
    for i in range(len(xplot)):
        for line in dolines:
            for type in dotypes:
                fig, axes = plt.subplots()
                for j, reg in enumerate(clouds):
                    dir = indir.replace('CLOUD', reg)
                    if os.path.isfile(dir + reg + '_' + line +
                                      '_physprop_add.txt'):
                        infile = dir + reg + '_' + line + '_physprop_add.txt'
                    else:
                        infile = dir + reg + '_' + line + '_physprop.txt'
                    if type in ['8um_avg', 'siglum']:
                        if type == 'siglum' and line == '12':
                            norm = LogNorm(vmin=10, vmax=1000)
                        else:
                            norm = LogNorm(vmin=1, vmax=100)
                        plot_ecsv(infile,
                                  xplot[i],
                                  yplot[i],
                                  zaxis=type,
                                  cmap=cmap,
                                  mark=markers[j],
                                  mec=mec,
                                  msize=8,
                                  zorder=i,
                                  label=reg,
                                  leaves=leaves,
                                  norm=norm)
                    else:
                        if type == 'med_co':
                            norm = Normalize(vmin=min(cldtab[type]),
                                             vmax=max(cldtab[type]))
                        else:
                            norm = LogNorm(vmin=min(cldtab[type]),
                                           vmax=max(cldtab[type]))
                        colr = np.array(cmap(norm(cldtab[type][j])))
                        plot_ecsv(infile,
                                  xplot[i],
                                  yplot[i],
                                  col=colr,
                                  mark=markers[j],
                                  mec=mec,
                                  msize=8,
                                  zorder=i,
                                  label=reg,
                                  leaves=leaves)
                axes.set_xlim(10**xlims[i][0], 10**xlims[i][1])
                axes.set_ylim(10**ylims[i][0], 10**ylims[i][1])
                logfmt = ticker.LogFormatterExponent(base=10.0,
                                                     labelOnlyBase=True)
                axes.xaxis.set_major_formatter(logfmt)
                axes.yaxis.set_major_formatter(logfmt)
                axes.minorticks_off()
                # Reference slopes
                xmod = np.logspace(xlims[i][0], xlims[i][1], 100)
                ymod = xmod**slope[i]
                if xplot[i] == 'rad_pc' and yplot[i] == 'vrms_k':
                    ymod = ymod * 0.72
                    axes.plot(xmod,
                              ymod,
                              linestyle='-',
                              color='r',
                              lw=4,
                              alpha=0.5,
                              zorder=-1)
                    axes.text(10**(xlims[i][1] - 0.05),
                              10**(ylims[i][1] - 0.8),
                              'S87',
                              horizontalalignment='right',
                              color='r',
                              rotation=30)
                else:
                    # Plot nominal R(12/13) of 8
                    if xplot[i] == 'flux12' and yplot[i] == 'flux13':
                        ymod = ymod / 8
                    # Plot nominal Sigma_mol of 100 Msol/pc^2
                    if xplot[i].startswith('area') and yplot[i].startswith(
                            'm'):
                        ymod = ymod * 100
                    axes.plot(xmod, ymod, '--', marker=None, color='k')
                # Lines of constant external pressure
                if xplot[i].startswith('sig') and yplot[i] == 'sigvir':
                    ymod = xmod + (20 / (3 * np.pi * 21.1)) * 1.e4 / xmod
                    axes.plot(xmod, ymod, linestyle='-', color='g', lw=1)
                    axes.text(10**-0.97,
                              10**3.5,
                              '$P_{ext}$ = $10^4$ cm$^{-3}$ K',
                              color='g',
                              rotation=-45)
                    ymod2 = xmod + (20 / (3 * np.pi * 21.1)) * 1.e2 / xmod
                    axes.plot(xmod, ymod2, linestyle='-', color='m', lw=1)
                    axes.text(10**-0.97,
                              10**2.1,
                              '$P_{ext}$ = $10^2$ cm$^{-3}$ K',
                              color='m',
                              rotation=-45)
                    axes.text(10**-0.95,
                              10**-0.25,
                              'Virial Eq',
                              color='k',
                              rotation=45)
                # Legend and colorbar
                plt.legend(loc='lower right',
                           fontsize='small',
                           numpoints=1,
                           markerscale=2)
                cax = fig.add_axes([pad[i] + 0.7, 0.11, 0.02, 0.77])
                formatter = ticker.LogFormatter(10,
                                                labelOnlyBase=False,
                                                minor_thresholds=(4, 3))
                if type == 'med_co':
                    cbar = mpl.colorbar.ColorbarBase(cax, cmap=cmap, norm=norm)
                else:
                    cbar = mpl.colorbar.ColorbarBase(
                        cax,
                        cmap=cmap,
                        norm=norm,
                        format=formatter,
                        ticks=[1, 2, 5, 10, 20, 50, 100, 200, 500, 1000])
                cbar.ax.tick_params(labelsize=9)
                if type == 'med_8u':
                    cbar.set_label('cloud median 8$\mu$m intensity [MJy/sr]',
                                   rotation=90)
                elif type == 'med_co':
                    cbar.set_label('cloud median CO intensity [K km/s]',
                                   rotation=90)
                elif type == 'avg_st':
                    cbar.set_label(
                        'cloud mean $\Sigma_{*}$ [$M_\odot$ $pc^{-2}$]',
                        rotation=90)
                elif type == 'med_24':
                    cbar.set_label('cloud mean 24$\mu$m intensity [MJy/sr]',
                                   rotation=90)
                elif type == '8um_avg':
                    cbar.set_label('local mean 8$\mu$m intensity [MJy/sr]',
                                   rotation=90)
                elif type == 'siglum':
                    cbar.set_label(
                        'local mean $\Sigma_{mol}$ [$M_\odot$ $pc^{-2}$]',
                        rotation=90)
                plt.savefig('comp_' + line + '_' + pltname[i] + '_' + type +
                            '.pdf',
                            bbox_inches='tight')
                plt.close()
    return
예제 #29
0
def main():
    parser = argparse.ArgumentParser(description='plotter')
    parser.add_argument('--fig_length',
                        type=int,
                        default=6,
                        help='matplotlib figure length (default: 6)')
    parser.add_argument('--fig_width',
                        type=int,
                        default=6,
                        help='matplotlib figure width (default: 6)')
    parser.add_argument('--style',
                        default='seaborn',
                        help='matplotlib figure style (default: seaborn)')
    parser.add_argument('--title',
                        default=None,
                        help='matplotlib figure title (default: None)')
    parser.add_argument('--xlabel',
                        default=None,
                        help='matplotlib figure xlabel')
    parser.add_argument('--xkey',
                        default='l',
                        help='x-axis key in csv file (default: l)')
    parser.add_argument('--ykey',
                        default='r',
                        help='y-axis key in csv file (default: r)')
    parser.add_argument('--ylabel',
                        default=None,
                        help='matplotlib figure ylabel')
    parser.add_argument('--smooth',
                        type=int,
                        default=10,
                        help='smooth radius of y axis (default: 10)')
    parser.add_argument(
        '--resample',
        type=int,
        default=512,
        help=
        'if not zero, size of the uniform grid in x direction to resample onto. Resampling is performed via symmetric EMA smoothing (see the docstring for symmetric_ema). Default is zero (no resampling). Note that if average_group is True, resampling is necessary; in that case, default value is 512. (default: 512)'
    )
    parser.add_argument(
        '--smooth_step',
        type=float,
        default=1.0,
        help=
        'when resampling (i.e. when resample > 0 or average_group is True), use this EMA decay parameter (in units of the new grid step). See docstrings for decay_steps in symmetric_ema or one_sided_ema functions.'
    )
    parser.add_argument(
        '--avg_group',
        action='store_true',
        help='average the curves in the same group and plot the mean.')
    parser.add_argument(
        '--shaded_std',
        action='store_true',
        help='shaded region corresponding to standard deviation of the group')
    parser.add_argument(
        '--shaded_err',
        action='store_true',
        help='shaded region corresponding to error in mean estimate')
    parser.add_argument('--legend_loc',
                        type=int,
                        default=0,
                        help='location of legend')
    parser.add_argument('--legend_outside',
                        action='store_true',
                        help='place the legend outside of the figure')
    parser.add_argument('--no_legend_group_num',
                        action='store_true',
                        help="don't show num of group in legend")

    parser.add_argument(
        '--time',
        action='store_true',
        help=
        'enable this will set x_key to t, and activate parameters about time')
    parser.add_argument(
        '--time_unit',
        default='h',
        help='parameters about time, x axis time unit (default: h)')
    parser.add_argument(
        '--time_interval',
        type=float,
        default=1,
        help='parameters about time, x axis time interval (default: 1)')

    parser.add_argument('--xformat', default='eng', help='x-axis format')
    parser.add_argument('--xlim',
                        type=int,
                        default=None,
                        help='x-axis limitation (default: None)')

    parser.add_argument('--log_dir',
                        default='./',
                        help='log dir (default: ./)')
    parser.add_argument('--filename', default='monitor', help='csv filename')
    parser.add_argument('--show', action='store_true', help='show figure')
    parser.add_argument('--save', action='store_true', help='save figure')
    parser.add_argument('--dpi',
                        type=int,
                        default=400,
                        help='figure dpi (default: 400)')
    args = parser.parse_args()

    xscale = 1
    if args.time:
        if args.xlabel is None:
            args.xlabel = 'Training time'
        args.xkey = 't'
        if args.time_unit == 'h':
            xscale = 60 * 60
            args.time_interval = 2
        elif args.time_unit == 'min':
            xscale = 60
            args.time_interval = 20
    else:
        if args.xlabel is None:
            args.xlabel = 'Timesteps'

    if args.ylabel is None:
        args.ylabel = 'Episode Reward'

    if args.filename == 'evaluator':
        args.xkey = 'total_steps'
        args.ykey = 'mean_score'

    allresults = pu.load_results(args.log_dir, filename=args.filename)
    pu.plot_results(allresults,
                    fig_length=args.fig_length,
                    fig_width=args.fig_width,
                    style=args.style,
                    title=args.title,
                    xlabel=args.xlabel,
                    ylabel=args.ylabel,
                    xkey=args.xkey,
                    ykey=args.ykey,
                    xscale=xscale,
                    smooth_radius=args.smooth,
                    resample=args.resample,
                    smooth_step=args.smooth_step,
                    average_group=args.avg_group,
                    shaded_std=args.shaded_std,
                    shaded_err=args.shaded_err,
                    legend_outside=args.legend_outside,
                    legend_loc=args.legend_loc,
                    legend_group_num=not args.no_legend_group_num,
                    filename=args.filename)

    ax = plt.gca()  # get current axis
    if args.time:
        if args.time_unit == 'h' or args.time_unit == 'min':
            ax.xaxis.set_major_locator(
                mticker.MultipleLocator(args.time_interval))
        ax.xaxis.set_major_formatter(
            mticker.FormatStrFormatter("%d" + args.time_unit))
    else:
        if args.xformat == 'eng':
            ax.xaxis.set_major_formatter(mticker.EngFormatter())
        elif args.xformat == 'log':
            ax.xaxis.set_major_formatter(mticker.LogFormatter())
        elif args.xformat == 'sci':
            ax.xaxis.set_major_formatter(mticker.LogFormatterSciNotation())

    if args.xlim is not None:
        plt.xlim((0, args.xlim))

    if args.save:
        plt.savefig(args.log_dir + 'figure', dpi=args.dpi, bbox_inches='tight')
    if args.show:
        plt.show()
예제 #30
0
        "vmax": Zxx_max,
        "shading": 'gouraud'
    }],
    "options": ["grid"],
    "plot_type": "pcolormesh",
    "xlabel": "Time (s)",
    "ylabel": "Frequency (Hz)",
    "ylim": ylim,
    "yscale": "log",
    "tickers": {
        "yaxis": {
            "major": {
                "locator":
                ticker.AutoLocator(),
                "formatter":
                ticker.LogFormatter(labelOnlyBase=False,
                                    minor_thresholds=(np.inf, np.inf))
            }
        }
    },
    "fit_data": False
}

signal_fig = FigData(
    xs=nst.samp_nums,
    ys=nst.data,
    title=f"'Contaminated' {scale_name} minor chord (Pure sine waves)\n"
    f"Sampling Rate = {samp_rate}Hz",
    plot_type="plot",
    xlabel="Time (s)",
    ylabel="Amplitude")