Exemple #1
0
def plot_percentiles(percentiles, labels):
    fig, ax = plt.subplots(figsize=(20, 12))
    # plot values
    for data in percentiles:
        ax.plot(data['Percentile'], data['Latency'])

    # set axis and legend
    ax.grid()
    ax.set(xlabel='Percentile',
           ylabel='Latency (milliseconds)',
           title='Latency Percentiles')
    ax.set_xscale('logit')
    plt.xticks([0.25, 0.5, 0.9, 0.99, 0.999, 0.9999, 0.99999, 0.999999])
    majors = [
        "25%", "50%", "90%", "99%", "99.9%", "99.99%", "99.999%", "99.9999%"
    ]
    ax.xaxis.set_major_formatter(ticker.FixedFormatter(majors))
    ax.xaxis.set_minor_formatter(ticker.NullFormatter())
    # ax.xaxis.label.set_size(25)
    # ax.yaxis.label.set_size(25)
    for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] +
                 ax.get_xticklabels() + ax.get_yticklabels()):
        item.set_fontsize(20)
    plt.legend(bbox_to_anchor=(0., 1.02, 1., .102),
               loc=3,
               ncol=2,
               borderaxespad=0.,
               labels=labels)

    return fig, ax
Exemple #2
0
    def __init__(self, music_name):
        with wave.open(music_name, "r") as wav:
            (self.nchannels, self.sampwidth, self.framerate, self.nframes,
             self.comptype, self.compname) = wav.getparams()
        self.duration = self.nframes / self.framerate
        _w, _h = 800, 200
        self.k = int(self.nframes / _w / 32)
        self.DPI = 72
        self.peak = 256**self.sampwidth / 2

        data = scipy.io.wavfile.read(music_name)
        samples = data[1]

        plt.figure(1,
                   figsize=(float(_w) / self.DPI, float(_h) / self.DPI),
                   dpi=self.DPI)
        plt.subplots_adjust(wspace=0, hspace=0)

        for n in range(self.nchannels):
            channel = samples[n:]
            channel = channel[0::self.k]
            if self.nchannels == 1:
                channel = channel - self.peak
            axes = plt.subplot(2, 1, n + 1, facecolor="k")
            axes.plot(channel, "g")
            axes.yaxis.set_major_formatter(ticker.FuncFormatter(
                self.format_db))
            plt.grid(True, color="w")
            axes.xaxis.set_major_formatter(ticker.NullFormatter())

        axes.xaxis.set_major_formatter(ticker.FuncFormatter(self.format_time))
        plt.savefig("wave", dpi=self.DPI)
Exemple #3
0
def axis_settings(subax,
                  label=False,
                  arg1=None,
                  arg2=None,
                  arg3=None,
                  arg4=None,
                  arg5=None):
    subax.set_yscale('log')
    subax.set_xlim((0, 35))
    subax.set_ylim((0.01, 100))
    subax.set_xticks([7, 14, 21, 28, 35])
    subax.tick_params(axis='x',
                      which='both',
                      bottom=True,
                      top=True,
                      labelbottom=label,
                      labelsize=8)
    subax.set_yticks([0.01, 0.1, 1, 10, 100])
    subax.tick_params(axis='y',
                      which='both',
                      left=True,
                      right=True,
                      labelleft=label,
                      labelsize=8)
    locmin = mticker.LogLocator(base=10, subs=[1.0])
    subax.yaxis.set_minor_locator(locmin)
    subax.yaxis.set_minor_formatter(mticker.NullFormatter())
    subax.yaxis.get_label().set_backgroundcolor('w')
    for tick in subax.yaxis.get_major_ticks():
        tick.label.set_backgroundcolor('w')
    subax.grid(True, which="both", ls="--", c='gray', lw=0.5)

    return (subax)
Exemple #4
0
def add_dlog_plot(axes, x, y, style, label="", fit_deg=0):
    axes.loglog(x,
                y,
                **style.marker,
                **style.linestyle,
                label=label,
                color=style.color,
                fillstyle="none")

    if fit_deg:
        log_x = np.log(x)
        log_y = np.log(y)
        coeffs = np.polyfit(log_x, log_y, deg=fit_deg)
        poly_1d = np.poly1d(coeffs)
        yfit = lambda x: np.exp(poly_1d(np.log(x)))
        # label = rf"$y = {coeffs[0]:.2f}x {coeffs[1]:+.2f}$"
        label = rf"$n = {coeffs[0]:.2f}$"
        axes.plot(x, yfit(x), color=style.color, marker="", label=label)

    # needed to prevent overlapping labels:
    locs = axes.get_xticklabels(minor=True)
    if len(locs) > 5:
        axes.xaxis.set_minor_formatter(ticker.NullFormatter())
        axes.xaxis.set_major_locator(ticker.MaxNLocator(nbins=5))

    style.next_style()
Exemple #5
0
    def cleanup(self):
        """
        Cleanup the image by removing textual/formatting elements.
        """
        # Hide this method from the pytest traceback on test failure.
        __tracebackhide__ = True

        if self.remove_title:
            self.ax.set_title("")

        if self.remove_ticks:
            null_formatter = ticker.NullFormatter()
            for axis in ("xaxis", "yaxis", "zaxis"):
                try:
                    axis = getattr(self.ax, axis)
                    axis.set_major_formatter(null_formatter)
                    axis.set_minor_formatter(null_formatter)
                except AttributeError:
                    continue

        if self.remove_labels:
            self.ax.set_xlabel("")
            self.ax.set_ylabel("")

        if self.remove_legend and self.ax.get_legend() is not None:
            self.ax.legend_.remove()
Exemple #6
0
def srgan_loss_comparison():
    """Creates a plot which shows the theoretical loss curves for feature vector distances."""
    sns.set_style('darkgrid')
    figure, axes = plt.subplots(dpi=dpi)
    x_axis = np.arange(-10, 10, 0.01)

    l_g = -(np.log(np.abs(x_axis) + 1))
    l_unlabeled = np.power(x_axis, 2)

    axes.plot(x_axis, (l_g - l_g.min()) / (l_g.max() - l_g.min()),
              color=sns.color_palette()[4],
              label='$L_G$')
    axes.plot(x_axis, (l_unlabeled - l_unlabeled.min()) /
              (l_unlabeled.max() - l_unlabeled.min()),
              color=sns.color_palette()[5],
              label='$L_{fake}$')
    axes.legend().set_visible(True)
    axes.legend(loc='right')
    # axes.get_yaxis().set_ticks([])
    axes.set_ylabel('Loss')
    axes.set_xlabel('Feature difference')
    axes.get_yaxis().set_major_formatter(ticker.NullFormatter())
    axes.get_yaxis().grid(False)
    matplotlib2tikz.save(os.path.join('latex', 'srgan-losses.tex'))
    plt.show()
    plt.close(figure)
Exemple #7
0
def or_plot(fitted, alpha=0.05, intercept=False):
    """
    Odds ratio plot

    Parameters
    ----------
    fitted      A fitted logistic regression model
    alpha       Significance level
    intercept   Include intercept in plot (True or False)
    """
    df = or_conf_int(fitted, alpha=alpha, intercept=intercept,
                     dec=None).iloc[::-1]

    low, high = [100 * alpha / 2, 100 * (1 - (alpha / 2))]
    err = [df["OR"] - df[f"{low}%"], df[f"{high}%"] - df["OR"]]

    fig, ax = plt.subplots()
    ax.axvline(1, ls="dashdot")
    ax.errorbar(x="OR", y="index", data=df, xerr=err, fmt="none")
    ax.scatter(x="OR", y="index", data=df)
    ax.set_xscale("log")
    ax.xaxis.set_minor_formatter(ticker.NullFormatter())
    ax.xaxis.set_major_locator(
        ticker.LogLocator(subs=[0.1, 0.2, 0.5, 1, 2, 5, 10]))
    ax.xaxis.set_major_formatter(ticker.StrMethodFormatter("{x:.1f}"))
    ax.set(xlabel="Odds-ratio")
    return ax
Exemple #8
0
def hyperopt_int_plot(
        hyperopt_results_df,
        hp_name,
        metric,
        filename,
        log_scale_x=False,
        log_scale_y=True
):
    sns.set_style('whitegrid')
    plt.figure()
    seaborn_figure = sns.scatterplot(
        x=hp_name,
        y=metric,
        data=hyperopt_results_df
    )
    if log_scale_x:
        seaborn_figure.set(xscale="log")
    if log_scale_y:
        seaborn_figure.set(yscale="log")
    seaborn_figure.xaxis.set_major_locator(ticker.MaxNLocator(integer=True))
    seaborn_figure.xaxis.set_major_formatter(ticker.ScalarFormatter())
    seaborn_figure.xaxis.set_minor_formatter(ticker.NullFormatter())
    seaborn_figure.figure.tight_layout()
    if filename:
        seaborn_figure.figure.savefig(filename)
    else:
        seaborn_figure.figure.show()
Exemple #9
0
def plot_correction(pre_mat, post_mat, title):
    """ Plot comparison of pre-correction and post-correction matrices """

    #Make figure
    fig, ax = plt.subplots()
    fig.suptitle(title, fontsize=16, weight="bold")

    L = pre_mat.shape[1]
    flank = int(L / 2.0)
    xvals = np.arange(L)  # each position corresponds to i in mat

    #Customize minor tick labels
    xtick_pos = xvals[:-1] + 0.5
    xtick_labels = list(range(-flank, flank))  #-flank - flank without 0
    ax.xaxis.set_major_locator(ticker.FixedLocator(xvals))
    ax.xaxis.set_major_formatter(ticker.FixedFormatter(xtick_labels))
    ax.xaxis.set_minor_locator(ticker.FixedLocator(
        xtick_pos))  #locate minor ticks between major ones (cutsites)
    ax.xaxis.set_minor_formatter(ticker.NullFormatter())

    #PWMs for all mats
    pre_pwm = pre_mat
    post_pwm = post_mat

    #Pre correction
    for nuc in range(4):
        yvals = [pre_pwm[nuc, m] for m in range(L)]
        plt.plot(xvals,
                 yvals,
                 linestyle="--",
                 color=colors[nuc],
                 linewidth=1,
                 alpha=0.5)

    #Post correction
    for nuc in range(4):
        yvals = [post_pwm[nuc, m] for m in range(L)]
        plt.plot(xvals,
                 yvals,
                 color=colors[nuc],
                 linewidth=2,
                 label=names[nuc])

    plt.xlim([0, L - 1])
    plt.xlabel('Position from cutsite')
    plt.ylabel('Nucleotide frequency')

    #Set legend
    plt.plot([0], [0],
             linestyle="--",
             linewidth=1,
             color="black",
             label="pre-correction")
    plt.plot([0], [0], color="black", label="post-correction")
    plt.legend(loc="lower right", prop={'size': 6})

    plt.tight_layout()
    fig.subplots_adjust(top=0.88, hspace=0.4)

    return (fig)
Exemple #10
0
def draw(file_name):
    wav = wave.open(file_name, mode="r")
    global nframes, k, peak, duration
    (nchannels, sampwidth, framerate, nframes, comptype,
     compname) = wav.getparams()

    duration = nframes / framerate
    w, h = 800, 300
    k = nframes / w / 32
    DPI = 72
    peak = 256**sampwidth / 2

    content = wav.readframes(nframes)
    samples = np.fromstring(content, dtype=types[sampwidth])

    plt.figure(1, figsize=(float(w) / DPI, float(h) / DPI), dpi=DPI)
    plt.subplots_adjust(wspace=0, hspace=0)

    for n in range(nchannels):
        channel = samples[n::nchannels]

        channel = channel[0::k]
        if nchannels == 1:
            channel = channel - peak

        axes = plt.subplot(2, 1, n + 1, axisbg="k")
        axes.plot(channel, "g")
        axes.yaxis.set_major_formatter(ticker.FuncFormatter(format_db))
        plt.grid(True, color="w")
        axes.xaxis.set_major_formatter(ticker.NullFormatter())

    axes.xaxis.set_major_formatter(ticker.FuncFormatter(format_time))
    # plt.savefig("wave", dpi=DPI)
    plt.show()
Exemple #11
0
    def set_yaxis(self):
        """
        Custom Y axis with absolute or percentage formatting
        """
        if self.yunits == '%':
            # Set percentage scale
            self.ymax = max(self.ymax, 0.01)  # set a minimum of 1%
            note_ymax = '{:.1%}'.format(np.around(self.ymax, 3)) if self.ymax < 1 else ''
            divider = 4
            majformatter = tkr.PercentFormatter(xmax=1)
            self.log.debug("Plot Y axis set to percentual values")
        else:
            # Set absolute scale
            self.ymax = max(self.ymax, 1)  # set a minimum of 1 unit
            note_ymax = '{:.0f}'.format(np.around(self.ymax, 0))
            divider = 2 if self.ymax > 10 else 1
            majformatter = tkr.ScalarFormatter()
            self.log.debug("Plot Y axis set to absolute values")

        self.ax.set_ylim([0, self.ymax])

        self.ax.yaxis.set_minor_locator(tkr.AutoMinorLocator(divider))
        self.ax.yaxis.set_major_locator(tkr.MaxNLocator())

        self.ax.yaxis.set_minor_formatter(tkr.NullFormatter())
        self.ax.yaxis.set_major_formatter(majformatter)

        # Add axes labels
        self.ax.set_ylabel(self.ylab)
        # Add max value as annotation
        self.add_annotation(note_ymax, (0.00, 1.03), align='center')
Exemple #12
0
def logtick(ax, axis='x', grid=True, color="k", subs=[1., 2., 5.]):
    if matplotlibversion < "1.2":
        print "ERROR : logtick doesn't work with maptplotlib < 1.2"
        return

    def myfuncformatter(tick, tickposition=None):
        s = "%.6f" % tick
        if "." in s: s = s.rstrip('0').rstrip('.')
        return s

    major_locator = ticker.LogLocator(base=10., subs=subs)
    major_formatter = ticker.FuncFormatter(myfuncformatter)

    minor_locator = ticker.LogLocator(base=10., subs=[3., 4., 6., 7., 8., 9.])
    minor_formatter = ticker.NullFormatter()

    if 'x' in axis.lower():
        ax.xaxis.set_major_locator(major_locator)
        ax.xaxis.set_major_formatter(major_formatter)
        ax.xaxis.set_minor_locator(minor_locator)
        ax.xaxis.set_minor_formatter(minor_formatter)
    if 'y' in axis.lower():
        ax.yaxis.set_major_locator(major_locator)
        ax.yaxis.set_major_formatter(major_formatter)
        ax.yaxis.set_minor_locator(minor_locator)
        ax.yaxis.set_minor_formatter(minor_formatter)

    if grid:
        ax.grid(True, which="major", color=color, linestyle=":")
        ax.grid(True, which="minor", color=color, linestyle=":")
Exemple #13
0
def common_ytick_labels(fig, axes=None):
    """ Simplify common ytick labels.
    
    Keep ytick labels only at the leftmost axes and center the common ylabel.

    Parameters
    ----------
    fig: matplotlib figure
        The figure containing the axes.
    axes: None or sequence of matplotlib axes
        Axes whose yticks should be combined.
        If None take all axes of the figure.
    """
    if axes is None:
        axes = fig.get_axes()
    coords = np.array([ax.get_position().get_points().ravel() for ax in axes])
    minx = np.min(coords[:, 0])
    miny = np.min(coords[:, 1])
    maxy = np.max(coords[:, 3])
    yl = 0.5 * (miny + maxy)
    done = False
    for ax in axes:
        if ax.get_position().p0[0] > minx + 1e-6:
            ax.set_ylabel('')
            ax.yaxis.set_major_formatter(ticker.NullFormatter())
        elif done:
            ax.set_ylabel('')
        else:
            x, y = ax.yaxis.get_label().get_position()
            y = ax.transAxes.inverted().transform(
                fig.transFigure.transform((0, yl)))[1]
            ax.yaxis.get_label().set_position((x, y))
            done = True
Exemple #14
0
def plot_all(incl, save=None):
    global models

    rows = 2
    cols = 2

    fig, axes = plt.subplots(nrows=rows,
                             ncols=cols,
                             sharex=True,
                             sharey=True,
                             figsize=(19.20, 10.80))
    fig.subplots_adjust(wspace=0., hspace=0.)

    for i, model in enumerate(models):
        ax = axes.flatten()[i]
        star = Star(model, incl)

        wave_obs, sed_obs = np.loadtxt(
            '/home/rieutord/Ester/postprocessing/SED/SED', unpack=True)
        wave_mod, sed_mod = star.SED()
        ax.loglog(wave_mod * 1e4, sed_mod * 1e-4)
        ax.loglog(wave_obs, sed_obs, 'o')
        ax.yaxis.set_minor_locator(plt.LogLocator(base=10, numticks=15))
        ax.yaxis.set_minor_formatter(ticker.NullFormatter())
        ax.tick_params(labelsize=16,
                       direction='inout',
                       which='both',
                       length=5,
                       width=1)

        if ax.colNum != 0:
            ax.tick_params(left=False)
        else:
            ax.set_ylabel(
                'F$_\lambda$ (erg$\cdot$s$^{-1}\cdot$cm$^{-2}\cdot\mu$m$^{-1}$)',
                fontsize=20)

        if ax.rowNum != 1:
            ax.tick_params(bottom=False)
        else:
            ax.set_xlabel('$\lambda$ ($\mu$m)', fontsize=20)

        text = (
            'M  = {star.mod.M/Star.Msun:.2f} M$\odot$\nZ  = {star.mod.Z[0, 0]:.3f}\n'
            'Xc = {star.mod.Xc:.3f}')
        props = dict(boxstyle='round', facecolor='white', alpha=0.7)
        # place a text box in lower left in axes coords
        ax.text(0.75,
                0.90,
                text,
                transform=ax.transAxes,
                verticalalignment='top',
                bbox=props,
                fontdict=dict(fontsize=14))

    if save:
        fig.savefig(fname='/home/rieutord/Ester/postprocessing/SED/' + save,
                    bbox_inches='tight')
    fig.show()
    return
Exemple #15
0
def plotFourierData(freq, mag, axis=None, color='b', alpha=1.0):
    ax = axis

    if axis is None:
        fig = plt.figure(1337)
        fig.clf()
        fig.canvas.set_window_title("Non-Intrusive Load Monitoring - Frequency Spectrum - Felix Maass")

        ax = fig.add_subplot(111)

    ax.plot(freq, mag, color=color, alpha=alpha)

    ax.set_title("Frequency Spectrum")

    ax.set_xlabel('Frequency [Hz]')
    ax.get_xaxis().set_major_formatter(ticker.EngFormatter())
    ax.get_xaxis().set_minor_formatter(ticker.NullFormatter())

    ax.set_ylabel('Magnitude (log10)')
    ax.set_yscale('log')

    #######

    if axis is None:
        fig.tight_layout()
        plt.show()
Exemple #16
0
 def set_default_locators_and_formatters(self, axis):
     axis.set_major_locator(GPSAutoLocator(unit=self.unit,
                                           epoch=self.epoch))
     axis.set_major_formatter(GPSFormatter(unit=self.unit,
                                           epoch=self.epoch))
     axis.set_minor_locator(GPSAutoMinorLocator(epoch=self.epoch))
     axis.set_minor_formatter(ticker.NullFormatter())
Exemple #17
0
def plotPowerCurve(chunk, axis=None):
    ax = axis

    if axis is None:
        fig = plt.figure(271)
        fig.clf()
        fig.canvas.set_window_title("Non-Intrusive Load Monitoring - Power Characteristics - Felix Maass")

        ax = fig.add_subplot(111)


    ax.set_title("Power")
    ax.set_xlabel('Time [ms]')
    ax.set_ylabel('Power [VA / W / VAr]')

    ax.get_xaxis().set_major_formatter(ticker.EngFormatter())
    ax.get_xaxis().set_minor_formatter(ticker.NullFormatter())

    apparentPower   = chunk['u'] * chunk['i']

    phaseShift      = calculatePhaseShift(chunk)
    realPower       = apparentPower * cos(phaseShift)
    reactivePower   = apparentPower * sin(phaseShift)

    ax.plot(chunk['t'], apparentPower, color='r', label='Apparent')
    ax.plot(chunk['t'], realPower, color='g', label='Real')
    ax.plot(chunk['t'], reactivePower, color='b', label='Reactive')

    ax.legend()

    #######

    if axis is None:
        fig.tight_layout()
        plt.show()
Exemple #18
0
def plotIVCurve(chunk, axis=None):
    ax = axis

    if axis is None:
        fig = plt.figure(314)
        fig.clf()
        fig.canvas.set_window_title("Non-Intrusive Load Monitoring - Current-Voltage Characteristics - Felix Maass")

        ax = fig.add_subplot(111)

    ax.set_title("IV-Curve")
    ax.set_xlabel('Voltage [V]')
    ax.set_ylabel('Amperage [A]')

    ax.get_xaxis().set_major_formatter(ticker.EngFormatter())
    ax.get_xaxis().set_minor_formatter(ticker.NullFormatter())

    if np.max(np.abs(chunk['i'])) < 0.3:
        ax.set_ylim([-500,500])
        ax.set_autoscaley_on(False)
    else:
        ax.set_autoscaley_on(True)

    ax.plot(chunk['u'], chunk['i'], color='b')


    #######

    if axis is None:
        fig.tight_layout()
        plt.show()
Exemple #19
0
def plot_emacs(model, run_name, model_name, noise_type):
    emac = 0
    noise = 0
    emacs = []
    denominator = 0
    for name, param in model.named_parameters():
        if "noise" in name:
            mod = model
            for subname in name.split('.')[:-1]:
                mod = getattr(mod, subname)

            e = torch.exp(param)
            if mod.quantize_energy:
                e = RoundSTE.apply(e)

            if noise_type == "shot":
                noise += 1. / torch.sqrt(e).mean() * mod.total_macs
            elif noise_type == "thermal":
                noise += 1. / torch.sqrt(e).mean() * mod.total_macs / 100.
            if noise_type == "weight":
                noise += 1. / torch.sqrt(e).mean() * mod.total_macs

            emac += e.mean() * mod.total_macs
            emacs.append(e.mean().item())
            denominator += mod.total_macs
    avg_emac = (emac / denominator).item()
    avg_noise = (noise / denominator).item()

    plt.figure(figsize=(5, 3.5))
    plot = sns.lineplot(x=range(len(emacs)), y=np.array(emacs) * 0.128)
    if model_name == "bert":
        title = f"BERT Energy/MAC by Matrix Multiplication"
        xlabel = "Matrix Multiplication"
    else:
        title = f"{model_name}".capitalize() + f" Energy/MAC by Layer"
        xlabel = "Layer"

    sns.set_color_codes()
    plot.set_title(title)
    plot.set(yscale="log")
    plot.set(xlabel=xlabel, ylabel=f"Energy/MAC (aJ)")

    plot.yaxis.set_major_formatter(ticker.ScalarFormatter())
    y_minor = ticker.LogLocator(base=10.0,
                                subs=np.arange(1.0, 10.0) * 0.1,
                                numticks=10)
    plot.get_yaxis().set_minor_locator(y_minor)
    plot.grid(b=True,
              which='minor',
              color='lightgray',
              axis='y',
              linewidth=0.5)
    plot.yaxis.set_minor_locator(y_minor)
    plot.yaxis.set_minor_formatter(ticker.NullFormatter())

    plt.savefig(f"{run_name}/emac_by_layer.pdf", bbox_inches="tight")
    plt.close()

    return avg_emac, avg_noise
def plot_formatter(ax, title='Title', fname='fname.png'):
    ax.set_title(title)
    ax.set_xlabel('$u - g$ [mag]')
    ax.set_ylabel('$g - r$ [mag]')
    ax.legend()
    ax2 = ax.twinx()
    ax2.set_ylabel('Blue $\\longrightarrow$ Red')
    ax2.plot([1], [1], markersize=0)
    ax3 = ax.twiny()
    ax3.set_xlabel('Blue $\\longrightarrow$ Red')
    ax3.plot([1], [1], markersize=0)
    ax2.yaxis.set_minor_formatter(ticker.NullFormatter())
    ax3.xaxis.set_minor_formatter(ticker.NullFormatter())
    ax2.yaxis.set_major_formatter(ticker.NullFormatter())
    ax3.xaxis.set_major_formatter(ticker.NullFormatter())
    plt.savefig(fname, dpi=300)
    plt.close()
Exemple #21
0
 def __init__(self, *args, **kwargs):
     # Pass a dummy axis to the superclass
     axis = type('Axis', (object, ), {'axis_name': 'x'})()
     super().__init__(axis, *args, **kwargs)
     self._default_major_locator = mticker.AutoLocator()
     self._default_minor_locator = mticker.AutoMinorLocator()
     self._default_major_formatter = pticker.AutoFormatter()
     self._default_minor_formatter = mticker.NullFormatter()
Exemple #22
0
def plot_one_for_all(incl, save=None, res=False, error=0.1):

    global models

    fig, ax = plt.subplots(figsize=(10.80, 10.80))

    wave_obs, sed_obs = np.loadtxt(
        '/home/rieutord/Ester/postprocessing/SED/SED', unpack=True)

    ax.loglog(wave_obs, sed_obs, 'o')

    ax.set_xlabel('$\lambda$ ($\mu$m)', fontsize=20)

    ax.set_ylabel(
        'F$_\lambda$ (erg$\cdot$s$^{-1}\cdot$cm$^{-2}\cdot\mu$m$^{-1}$)',
        fontsize=20)
    ax.yaxis.set_minor_locator(plt.LogLocator(base=10, numticks=15))
    ax.yaxis.set_minor_formatter(ticker.NullFormatter())
    ax.tick_params(labelsize=16,
                   direction='inout',
                   which='both',
                   length=5,
                   width=1)

    linestyles = itertools.cycle([(0, (5, 5)), 'dashdot',
                                  (0, (3, 5, 1, 5, 1, 5)), 'dotted', '-'])

    # Print reduced Chi2 of fit with arbitrary uncertainty on observed data
    if res:
        print('Reduced chi2 ({error*100}% artificial error on data):\n')

    for i, model in enumerate(models):
        star = Star(mod=model, incl=incl)

        wave_mod, sed_mod = star.SED()
        ax.loglog(
            wave_mod * 1e4,
            sed_mod * 1e-4,
            ls=next(linestyles),
            label=
            ('M = {star.mod.M/Star.Msun:.2f} M$\odot$, Z = {star.mod.Z[0, 0]:.3f}, '
             'Xc = {star.mod.Xc:.2f}, $\overline{{\mathrm{{T}}}} = '
             '{int(star.Teff_mean())} $K'),
            zorder=0)

        if res:
            wave_mod_chi2, sed_mod_chi2 = star.SED(wavelength=wave_obs * 1e-4)
            sum_squared_res = sum(
                ((sed_mod_chi2 * 1e-4 - sed_obs) / (error * sed_obs))**2)
            chi2_red = sum_squared_res / len(sed_mod_chi2)
            print('model {star.mod.M/Star.Msun:.2f}: {chi2_red}')

    ax.legend(fontsize=16, loc='lower left')

    if save:
        fig.savefig(fname='./' + save, bbox_inches='tight')
    fig.show()
    return
def test_colorbars_no_overlapH():
    fig = plt.figure(figsize=(4, 2), layout="constrained")
    fig.suptitle("foo")
    axs = fig.subplots(1, 2, sharex=True, sharey=True)
    for ax in axs:
        ax.yaxis.set_major_formatter(ticker.NullFormatter())
        ax.tick_params(axis='both', direction='in')
        im = ax.imshow([[1, 2], [3, 4]])
        fig.colorbar(im, ax=ax, orientation="horizontal")
Exemple #24
0
    def colorbar(self,
                 fig=None,
                 anchor=(0.35, 0.24),
                 size=(0.3, 0.02),
                 fmt="{f:.0f}",
                 label=True):
        """カラーバーを描く

        Parameters:
        ----------
        fig: matplotlib Figure
            プロット領域を作成した際の戻り値
        anchor: tuple(float, float)
            カラーバーの位置
        size: tuple(float, float)
            カラーバーの大きさ
        fmt: str
            カラーバーの目盛り線ラベルの書式
        label: bool
            カラーバーの目盛り線ラベルを描くかどうか
        ----------
        """
        if fig is None:
            raise Exception('fig is needed')
        ax = fig.add_axes(anchor + size)
        gradient = np.linspace(0, 1, self.cm.N)
        gradient_array = np.vstack((gradient, gradient))
        ticks = list()
        labels = list()
        ll = np.arange(self.tmin, self.tmax, self.tstep)
        for t in ll:
            ticks.append((t - self.tmin) / (self.tmax - self.tmin) * self.cm.N)
            if label:
                labels.append(fmt.format(f=t))
        # カラーバーを描く
        ax.imshow(gradient_array, aspect='auto', cmap=self.cm)
        ax.yaxis.set_major_locator(mticker.NullLocator())
        ax.yaxis.set_minor_locator(mticker.NullLocator())
        ax.set_xticks(ticks)
        if label:
            ax.set_xticklabels(labels)
        else:
            ax.xaxis.set_major_formatter(mticker.NullFormatter())
            ax.xaxis.set_minor_formatter(mticker.NullFormatter())
def plot_history(env, h):

    grid = np.ones(env.state_space) * 255
    xs = []
    ys = []
    us = []
    vs = []
    for t in range(1, len(h) - 1):
        state = h[t][0]
        next_state = h[t + 1][0]

        x = state[1]
        y = state[0]
        u = next_state[1] - state[1]
        v = -(next_state[0] - state[0])

        xs.append(x)
        ys.append(y)
        us.append(u)
        vs.append(v)

        grid[y, x] = 200

    fig, ax = plt.subplots(1, figsize=(20, 15))
    plt.imshow(grid, cmap='gray', vmin=0, vmax=255)

    ax.grid(linestyle='-', linewidth=1)

    ax.set_xticks(np.arange(-.5, 10, 1))
    ax.set_yticks(np.arange(-.5, 10, 1))
    ax.set_xticklabels([])
    ax.set_yticklabels([])
    ax.set_xlabel('Wind (number of steps pushed North)', fontsize=30)

    ax.text(env.initial_state[1],
            env.initial_state[0],
            'Start',
            ha="center",
            va="center",
            fontsize=30)
    ax.text(env.terminate_state[1],
            env.terminate_state[0],
            'End',
            ha="center",
            va="center",
            fontsize=30)

    ax.xaxis.set_major_formatter(ticker.NullFormatter())
    ax.xaxis.set_minor_locator(ticker.FixedLocator(np.arange(0, 10, 1)))
    ax.xaxis.set_minor_formatter(ticker.FixedFormatter(np.abs(env.north_wind)))
    ax.tick_params(which='minor', labelsize=20)

    plt.arrow(5.5, 6, 0, -4, width=2, head_width=5, head_length=2, alpha=0.4)
    plt.quiver(xs, ys, us, vs)

    plt.title('Policy', fontsize=35)
Exemple #26
0
def plot_num_triplet_with_nonzero_integer_ambiguity(fname, display=False, font_size=12, fig_size=[9,3]):
    """Plot the histogram for the number of triplets with non-zero integer ambiguity

    Fig. 3d-e in Yunjun et al. (2019, CAGEO).
    """

    # read data
    data, atr = readfile.read(fname)
    vmax = int(np.nanmax(data))

    # plot
    fig, axs = plt.subplots(nrows=1, ncols=2, figsize=fig_size)

    # subplot 1 - map
    ax = axs[0]
    im = ax.imshow(data, cmap='RdBu_r', interpolation='nearest')

    # reference point
    if all(key in atr.keys() for key in ['REF_Y','REF_X']):
        ax.plot(int(atr['REF_X']), int(atr['REF_Y']), 's', color='white', ms=3)

    # format
    pp.auto_flip_direction(atr, ax=ax, print_msg=False)
    fig.colorbar(im, ax=ax)
    ax.set_title(r'$T_{int}$', fontsize=font_size)

    # subplot 2 - histogram
    ax = axs[1]
    ax.hist(data[~np.isnan(data)].flatten(), range=(0, vmax), log=True, bins=vmax)

    # axis format
    ax.set_xlabel(r'# of triplets w non-zero int ambiguity $T_{int}$', fontsize=font_size)
    ax.set_ylabel('# of pixels', fontsize=font_size)
    ax.xaxis.set_minor_locator(ticker.AutoMinorLocator())
    ax.yaxis.set_major_locator(ticker.LogLocator(base=10.0, numticks=15))
    ax.yaxis.set_minor_locator(ticker.LogLocator(base=10.0, numticks=15,
                                                 subs=(0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9)))
    ax.yaxis.set_minor_formatter(ticker.NullFormatter())

    for ax in axs:
        ax.tick_params(which='both', direction='in', labelsize=font_size,
                       bottom=True, top=True, left=True, right=True)

    fig.tight_layout()

    # output
    out_fig = '{}.png'.format(os.path.splitext(fname)[0])
    print('plot and save figure to file', out_fig)
    fig.savefig(out_fig, bbox_inches='tight', transparent=True, dpi=300)

    if display:
        plt.show()
    else:
        plt.close(fig)

    return
Exemple #27
0
def mirror_xticks(my_axes, xlim, xmajor, xminor=None):
    my_axes.xaxis.set_ticks(xmajor)
    if xminor is not None:
        my_axes.xaxis.set_ticks(xminor, minor=True)
        my_axes.xaxis.set_minor_formatter(ticker.NullFormatter())
    my_axes.set_xlim(xlim)

    tx = my_axes.twiny()
    tx.set_xscale(my_axes.get_xscale())
    tx.xaxis.tick_top()
    tx.xaxis.set_tick_params(direction='in', which='both')
    tx.xaxis.set_ticks(xmajor)
    if xminor is not None:
        tx.xaxis.set_ticks(xminor, minor=True)
        tx.xaxis.set_minor_formatter(ticker.NullFormatter())
    tx.set_xlim(xlim)
    for ticklabel in tx.xaxis.get_majorticklabels():
        ticklabel.set_visible(False)
    return tx
Exemple #28
0
def mirror_yticks(my_axes, ylim, ymajor, yminor=None):
    my_axes.yaxis.set_ticks(ymajor)
    if yminor is not None:
        my_axes.yaxis.set_ticks(yminor, minor=True)
        my_axes.yaxis.set_minor_formatter(ticker.NullFormatter())
    my_axes.set_ylim(ylim)

    ty = my_axes.twinx()
    ty.set_yscale(my_axes.get_yscale())
    ty.yaxis.tick_right()
    ty.yaxis.set_tick_params(direction='in', which='both')
    ty.yaxis.set_ticks(ymajor)
    if yminor is not None:
        ty.yaxis.set_ticks(yminor, minor=True)
        ty.yaxis.set_minor_formatter(ticker.NullFormatter())
    ty.set_ylim(ylim)
    for ticklabel in ty.yaxis.get_majorticklabels():
        ticklabel.set_visible(False)
    return ty
Exemple #29
0
def createplotforoperation(op, data, inter):
    plt.cla()
    plt.clf()
    plt.rcParams.update({'font.size': 12})
    plt.figure(figsize=(7.5, 5))
    plt.yscale('log')  #Vi skal lige vælge om det er log eller ej
    plt.xscale('log')
    plt.gca().yaxis.set_major_formatter(mtick.StrMethodFormatter('{x:,.0f}'))
    plt.gca().yaxis.set_minor_formatter(mtick.NullFormatter())
    df = pd.DataFrame(data[data["Op"] == op])
    df = df.astype({'OpCount': 'int64'})
    df['Avg(micros)'] = (df['Time(s)'] / df['OpCount']) * 1000 * 1000
    print(df)
    texts = []
    i = 0
    for name in sorted(list(pd.unique(df['DS']))):
        dfn = df[df['DS'] == name]
        x = list(dfn['Size'])
        y = list(dfn['Avg(micros)'])
        p = plt.plot(x, y, label=name, marker=markers[i])
        i += 1
        texts.append(
            plt.annotate(f'{name}', (x[-1], y[-1]), color=p[0].get_color()))
    plt.xlabel('Initial elements')
    plt.ylabel('Average time (µs)')
    plt.grid(True, which="both", linestyle='--')
    size = texts[0].get_fontsize()
    overlapping = True
    while overlapping:
        overlap = set()
        overlapping = False
        for a in texts:
            for b in texts:
                if a == b: continue
                if a._get_position_xy(plt)[1] < b._get_position_xy(
                        plt)[1] and a._get_position_xy(
                            plt)[1] + size > b._get_position_xy(plt)[1]:
                    overlap.add(a)
                    overlap.add(b)
                    overlapping = True
        if len(overlap) == 0: break
        mi = min(overlap, key=lambda a: a.xy[1])
        ma = max(overlap, key=lambda a: a.xy[1])
        mi.set_y(mi.xy[1] - mi.xy[1] / 100)
        ma.set_y(ma.xy[1] + ma.xy[1] / 100)
        mi.xy = (mi._x, mi._y)
        ma.xy = (ma._x, ma._y)
    plt.legend(loc="upper left")
    plt.margins(x=0)
    plt.title(f'Average runtime for N "{op}" operations in {l}')
    plt.tight_layout()

    pathlib.Path(f'../results/graphs_{inter}').mkdir(parents=True,
                                                     exist_ok=True)
    plt.savefig(f'../results/graphs_{inter}/{op}.png', bbox_inches='tight')
Exemple #30
0
def decorate_data_late(ax, t, ym, yM):
    '''
    input:
        ax, axis handle
         
    sets limits,writes x_label
    '''
    from matplotlib import ticker
    ax.set_xlim(t[0], t.max())
    ax.set_ylim(ym, yM)
    ax.yaxis.set_major_formatter(ticker.NullFormatter())  #