Exemplo n.º 1
0
    def plot_rdts(self, rdt_names=None, apply_fun=np.abs, combined=True):
        """ Plot Resonance Driving Terms """
        LOG.debug("Plotting Resonance Driving Terms")
        rdts = self.get_rdts(rdt_names)
        is_s = rdts.columns.str.match(r'S$', case=False)
        rdts = rdts.dropna()
        rdts.loc[:, ~is_s] = rdts.loc[:, ~is_s].applymap(apply_fun)
        pstyle.set_style(self._plot_options.style, self._plot_options.manual)

        if combined:
            ax = rdts.plot(x='S')
            ax.set_title('Resonance Driving Terms')
            pstyle.small_title(ax)
            pstyle.set_name('Resonance Driving Terms', ax)
            pstyle.set_yaxis_label(apply_fun.__name__, 'F_{{jklm}}', ax)
            self._nice_axes(ax)
        else:
            for rdt in rdts.loc[:, ~is_s]:
                ax = rdts.plot(x='S', y=rdt)
                ax.set_title('Resonance Driving Term ' + rdt)
                pstyle.small_title(ax)
                pstyle.set_name('Resonance Driving Term ' + rdt, ax)
                pstyle.set_yaxis_label(apply_fun.__name__, rdt, ax)
                self._nice_axes(ax)
Exemplo n.º 2
0
    def plot_phase_advance(self, combined=True):
        """ Plots the phase advances between two consecutive elements

        Args:
            combined (bool): If 'True' plots x and y into the same axes.
        """
        raise NotImplementedError('Plotting Phase Advance Shift is not Implemented yet.')
        #TODO: reimplement the phase-advance shift calculations (if needed??)
        LOG.debug("Plotting Phase Advance")
        tw = self.mad_twiss
        pa = self._phase_advance
        dpa = self._dphase_advance
        phase_advx = np.append(pa['X'].iloc[0, -1] + tw.Q1, pa['X'].values.diagonal(offset=-1))
        dphase_advx = np.append(dpa['X'].iloc[0, -1], dpa['X'].values.diagonal(offset=-1))
        phase_advy = np.append(pa['Y'].iloc[0, -1] + tw.Q2, pa['Y'].values.diagonal(offset=-1))
        dphase_advy = np.append(dpa['Y'].iloc[0, -1], dpa['Y'].values.diagonal(offset=-1))
        phase_adv = tw[["S"]].copy()
        phase_adv['MUX'] = np.cumsum(phase_advx + dphase_advx) % 1 - .5
        phase_adv['MUY'] = np.cumsum(phase_advy + dphase_advy) % 1 - .5

        title = 'Phase'
        pstyle.set_style(self._plot_options.style, self._plot_options.manual)

        if combined:
            ax_dx = phase_adv.plot(x='S')
            ax_dx.set_title(title)
            pstyle.small_title(ax_dx)
            pstyle.set_name(title, ax_dx)
            pstyle.set_yaxis_label('phase', 'x,y', ax_dx, delta=False)
            ax_dy = ax_dx
        else:
            ax_dx = phase_adv.plot(x='S', y='MUX')
            ax_dx.set_title(title)
            pstyle.small_title(ax_dx)
            pstyle.set_name(title, ax_dx)
            pstyle.set_yaxis_label('phase', 'x', ax_dx, delta=False)

            ax_dy = phase_adv.plot(x='S', y='MUY')
            ax_dy.set_title(title)
            pstyle.small_title(ax_dy)
            pstyle.set_name(title, ax_dy)
            pstyle.set_yaxis_label('phase', 'y', ax_dy, delta=False)

        for ax in (ax_dx, ax_dy):
            self._nice_axes(ax)
            ax.legend()
Exemplo n.º 3
0
    def plot_chromatic_beating(self, combined=True):
        """ Plot the Chromatic Beating

        Available after calc_chromatic_beating

        Args:
            combined (bool): If 'True' plots x and y into the same axes.
        """
        LOG.debug("Plotting Chromatic Beating")
        chrom_beat = self.get_chromatic_beating().dropna()
        title = 'Chromatic Beating'
        pstyle.set_style(self._plot_options.style, self._plot_options.manual)

        if combined:
            ax_dx = chrom_beat.plot(x='S')
            ax_dx.set_title(title)
            pstyle.small_title(ax_dx)
            pstyle.set_name(title, ax_dx)
            pstyle.set_yaxis_label('dbetabeat', 'x,y', ax_dx)
            ax_dy = ax_dx
        else:
            ax_dx = chrom_beat.plot(x='S', y='DBEATX')
            ax_dx.set_title(title)
            pstyle.small_title(ax_dx)
            pstyle.set_name(title, ax_dx)
            pstyle.set_yaxis_label('dbetabeat', 'x', ax_dx)

            ax_dy = chrom_beat.plot(x='S', y='DBEATY')
            ax_dy.set_title(title)
            pstyle.small_title(ax_dy)
            pstyle.set_name(title, ax_dy)
            pstyle.set_yaxis_label('dbetabeat', 'y', ax_dy)

        for ax in (ax_dx, ax_dy):
            self._nice_axes(ax)
            ax.legend()
Exemplo n.º 4
0
def plot_detuning(x,
                  y,
                  xerr,
                  yerr,
                  labels,
                  xmin=None,
                  xmax=None,
                  ymin=None,
                  ymax=None,
                  odr_fit=None,
                  odr_plot=plot_linear_odr,
                  output=None,
                  show=True):
    """ Plot amplitude detuning.

    Args:
        x: Action data.
        y: Tune data.
        xerr: Action error.
        yerr: Tune error.
        xmin: Lower action range to plot.
        xmax: Upper action range to plot.
        ymin: Lower tune range to plot.
        ymax: Upper tune range to plot.
        odr_fit: results of the odr-fit (e.g. see do_linear_odr)
        odr_plot: function to plot odr_fit (e.g. see plot_linear_odr)
        labels: Dict of labels to use for the data ("line"), the x-axis ("x") and the y-axis ("y")
        output: Output file of the plot.
        show: Show the plot in window.

    Returns:
        Plotted Figure
    """
    ps.set_style(
        "standard", {
            u"lines.marker": u"o",
            u"lines.linestyle": u"",
            u'figure.figsize': [9.5, 4],
        })

    fig = plt.figure()
    ax = fig.add_subplot(111)

    xmin = 0 if xmin is None else xmin
    xmax = max(x + xerr) * 1.05 if xmax is None else xmax

    offset = 0
    if odr_fit:
        odr_plot(ax, odr_fit, lim=[xmin, xmax])
        offset = odr_fit.beta[0]

    ax.errorbar(x,
                y - offset,
                xerr=xerr,
                yerr=yerr,
                label=labels.get("line", None))

    # labels
    default_labels = const.get_paired_lables("", "")
    ax.set_xlabel(labels.get("x", default_labels[0]))
    ax.set_ylabel(labels.get("y", default_labels[1]))

    # limits
    ax.set_xlim(left=xmin, right=xmax)
    ax.set_ylim(bottom=ymin, top=ymax)

    # lagends
    ax.legend(
        loc='lower right',
        bbox_to_anchor=(1.0, 1.01),
        ncol=2,
    )
    ax.ticklabel_format(style="sci", useMathText=True, scilimits=(-3, 3))
    fig.tight_layout()
    fig.tight_layout()  # needs two calls for some reason to look great

    if output:
        fig.savefig(output)
        ps.set_name(os.path.basename(output))

    if show:
        plt.draw()

    return fig
Exemplo n.º 5
0
def plot_bbq_data(bbq_df,
                  interval=None, xmin=None, xmax=None, ymin=None, ymax=None,
                  output=None, show=True, two_plots=False):
    """ Plot BBQ data.

    Args:
        bbq_df: BBQ Dataframe with moving average columns
        interval: start and end time of used interval, will be marked with red bars
        xmin: Lower x limit (time)
        xmax: Upper x limit (time)
        ymin: Lower y limit (tune)
        ymax: Upper y limit (tune)
        output: Path to the output file
        show: Shows plot if `True`
        two_plots: Plots each tune in it's own axes if `True`

    Returns:
        Plotted figure

    """
    LOG.debug("Plotting BBQ data.")

    ps.set_style("standard", {
        u'figure.figsize': [12.24, 7.68],
        u"lines.marker": u"",
        u"lines.linestyle": u""}
        )

    fig = plt.figure()

    if two_plots:
        gs = gridspec.GridSpec(2, 1, height_ratios=[1, 1])
        ax = [fig.add_subplot(gs[1]), fig.add_subplot(gs[0])]
    else:
        gs = gridspec.GridSpec(1, 1, height_ratios=[1])
        ax = fig.add_subplot(gs[0])
        ax = [ax, ax]

    bbq_df.index = [datetime.datetime.fromtimestamp(time, tz=TIMEZONE) for time in bbq_df.index]

    handles = [None] * (3 * len(PLANES))
    for idx, plane in enumerate(PLANES):
        color = ps.get_mpl_color(idx)
        mask = bbq_df[COL_IN_MAV(plane)]

        # plot and save handles for nicer legend
        handles[idx] = ax[idx].plot(bbq_df.index, bbq_df[COL_BBQ(plane)],
                                    color=ps.change_color_brightness(color, .4),
                                    marker="o", markerfacecolor="None",
                                    label="$Q_{:s}$".format(plane.lower(),)
                                    )[0]
        filtered_data = bbq_df.loc[mask, COL_BBQ(plane)].dropna()
        handles[len(PLANES)+idx] = ax[idx].plot(filtered_data.index, filtered_data.values,
                                                color=ps.change_color_brightness(color, .7),
                                                marker=".",
                                                label="filtered".format(plane.lower())
                                                )[0]
        handles[2*len(PLANES)+idx] = ax[idx].plot(bbq_df.index, bbq_df[COL_MAV(plane)],
                                                  color=color,
                                                  linestyle="-",
                                                  label="moving av.".format(plane.lower())
                                                  )[0]

        if ymin is None and two_plots:
            ax[idx].set_ylim(bottom=min(bbq_df.loc[mask, COL_BBQ(plane)]))

        if ymax is None and two_plots:
            ax[idx].set_ylim(top=max(bbq_df.loc[mask, COL_BBQ(plane)]))

    # things to add/do only once if there is only one plot
    for idx in range(1+two_plots):
        if interval:
            ax[idx].axvline(x=interval[0], color="red")
            ax[idx].axvline(x=interval[1], color="red")

        if two_plots:
            ax[idx].set_ylabel("$Q_{:s}$".format(PLANES[idx]))
        else:
            ax[idx].set_ylabel('Tune')

        ax[idx].set_ylim(bottom=ymin, top=ymax)
        ax[idx].yaxis.set_major_formatter(FormatStrFormatter('%.5f'))

        ax[idx].set_xlim(left=xmin, right=xmax)
        ax[idx].set_xlabel('Time')
        ax[idx].xaxis.set_major_formatter(mdates.DateFormatter('%H:%M:%S'))

        if idx:
            # don't show labels on upper plot (if two plots)
            # use the visibility to allow cursor x-position to be shown
            ax[idx].tick_params(labelbottom=False)
            ax[idx].xaxis.get_label().set_visible(False)

        if not two_plots or idx:
            # reorder legend
            ax[idx].legend(handles, [h.get_label() for h in handles],
                           loc='lower right', bbox_to_anchor=(1.0, 1.01), ncol=3,)

    fig.tight_layout()
    fig.tight_layout()

    if output:
        fig.savefig(output)
        ps.set_name(os.path.basename(output))

    if show:
        plt.draw()

    return fig
Exemplo n.º 6
0
def plot_detuning(x, y, xerr, yerr, labels, xmin=None, xmax=None, ymin=None, ymax=None,
                  odr_fit=None, odr_plot=plot_linear_odr, output=None, show=True):
    """ Plot amplitude detuning.

    Args:
        x: Action data.
        y: Tune data.
        xerr: Action error.
        yerr: Tune error.
        xmin: Lower action range to plot.
        xmax: Upper action range to plot.
        ymin: Lower tune range to plot.
        ymax: Upper tune range to plot.
        odr_fit: results of the odr-fit (e.g. see do_linear_odr)
        odr_plot: function to plot odr_fit (e.g. see plot_linear_odr)
        labels: Dict of labels to use for the data ("line"), the x-axis ("x") and the y-axis ("y")
        output: Output file of the plot.
        show: Show the plot in window.

    Returns:
        Plotted Figure
    """
    ps.set_style("standard",
                 {u"lines.marker": u"o",
                  u"lines.linestyle": u"",
                  u'figure.figsize': [9.5, 4],
                  }
                 )

    fig = plt.figure()
    ax = fig.add_subplot(111)

    xmin = 0 if xmin is None else xmin
    xmax = max(x + xerr) * 1.05 if xmax is None else xmax

    offset = 0
    if odr_fit:
        odr_plot(ax, odr_fit, lim=[xmin, xmax])
        offset = odr_fit.beta[0]

    ax.errorbar(x, y - offset, xerr=xerr, yerr=yerr, label=labels.get("line", None))

    # labels
    default_labels = const.get_paired_lables("", "")
    ax.set_xlabel(labels.get("x", default_labels[0]))
    ax.set_ylabel(labels.get("y", default_labels[1]))

    # limits
    ax.set_xlim(left=xmin, right=xmax)
    ax.set_ylim(bottom=ymin, top=ymax)

    # lagends
    ax.legend(loc='lower right', bbox_to_anchor=(1.0, 1.01), ncol=2,)
    ax.ticklabel_format(style="sci", useMathText=True, scilimits=(-3, 3))
    fig.tight_layout()
    fig.tight_layout()  # needs two calls for some reason to look great

    if output:
        fig.savefig(output)
        ps.set_name(os.path.basename(output))

    if show:
        plt.draw()

    return fig