def plot_single_file(opt):
    """ Plots multiple columns into one figure.

     Beware that labels and legends have now changed roles! """
    # preparations
    opt = _check_opt(opt)
    ps.set_style("standard", MANUAL_STYLE)

    if len(opt.files) > 1:
        raise ValueError("Single file plotting mode works only with one file!")

    twiss_data = _get_data(opt.files)

    # plotting
    fig = _create_single_plot(opt.x_cols, opt.y_cols, opt.e_cols, twiss_data,
                              opt.labels, opt.legends, opt.xy,
                              opt.change_marker, opt.no_legend, opt.auto_scale)

    # exports
    if opt.output:
        _export_plots([fig], opt.output)

    if not opt.no_show:
        plt.show()

    return fig
Beispiel #2
0
    def plot_linear_dispersion(self, combined=True):
        """ Plot the Linear Dispersion.

        Available after calc_linear_dispersion!

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

        if combined:
            ax_dx = lin_disp.plot(x='S')
            ax_dx.set_title(title)
            pstyle.set_yaxis_label('dispersion', 'x,y', ax_dx)
            ax_dy = ax_dx
        else:
            ax_dx = lin_disp.plot(x='S', y='DX')
            ax_dx.set_title(title)
            pstyle.set_yaxis_label('dispersion', 'x', ax_dx)

            ax_dy = lin_disp.plot(x='S', y='DY')
            ax_dy.set_title(title)
            pstyle.set_yaxis_label('dispersion', 'y', ax_dy)

        for ax in (ax_dx, ax_dy):
            self._nice_axes(ax)
            ax.legend()
def plot(opt):
    """ Plots data from different twiss-input files into one plot.

    Keyword Args:
        Required
        files (basestring): Twiss files to plot
                            **Flags**: --files
        y_cols (basestring): List of column names to plot (e.g. BETX, BETY)
                             **Flags**: ['-y', '--y_cols']
        Optional
        auto_scale (float): Scales the plot, so that this percentage of
                            points is inside the picture.
                            **Flags**: --autoscale
        change_marker: Changes marker for each line in the plot.
                       **Flags**: --changemarker
                       **Action**: ``store_true``
        e_cols (basestring): List of parameters to get error values from.
                             **Flags**: ['-e', '--e_cols']
        labels (basestring): Y-Lables for the plots, default: y_col.
                             **Flags**: --labels
        legends (basestring): Legends for the plots, default: filenames.
                              **Flags**: --legends
        no_legend: Deactivates the legend.
                   **Flags**: --nolegend
                   **Action**: ``store_true``
        no_show: Suppresses opening plotting windows.
                 **Flags**: --noshow
                 **Action**: ``store_true``
        output (basestring): Base-Name of the output files. _'y_col'.pdf will be attached.
                             **Flags**: --output
        x_cols (basestring): List of column names to use as x-values.
                             **Flags**: ['-x', '--x_cols']
        xy: Plots X and Y for the give parameters into one figure (two axes).
            **Flags**: --xy
            **Action**: ``store_true``
    """
    LOG.debug("Starting plotting of tfs files: {:s}".format(", ".join(
        opt.files)))

    # preparations
    opt = _check_opt(opt)
    ps.set_style("standard", MANUAL_STYLE)

    twiss_data = _get_data(opt.files)

    # plotting
    figs = _create_plots(opt.x_cols, opt.y_cols, opt.e_cols, twiss_data,
                         opt.legends, opt.labels, opt.xy, opt.change_marker,
                         opt.no_legend, opt.auto_scale)

    # exports
    if opt.output:
        _export_plots(figs, opt.output)

    if not opt.no_show:
        plt.show()

    return figs
Beispiel #4
0
def plot(opt):
    """ Plots data from different twiss-input files into one plot.

    Keyword Args:
        Required
        files (str): Twiss files to plot
                     **Flags**: --files
        optics_params (str): List of parameters to plot upon (e.g. BETX, BETY)
                             **Flags**: --optics_params

        Optional
        change_marker: Changes marker for each line in the plot.
                       **Flags**: --changemarker
                       **Action**: ``store_true``
        error_params (str): List of parameters to get error values from.
                            **Flags**: --error_params
        labels (str): Y-Lables for the plots, default: parameters.
                      **Flags**: --labels
        legends (str): Legends for the plots, default: filenames.
                      **Flags**: --legends
        no_legend: Deactivates the legend.
                   **Flags**: --nolegend
                   **Action**: ``store_true``
        no_show: Suppresses opening plotting windows.
                 **Flags**: --noshow
                 **Action**: ``store_true``
        output (str): Base-Name of the output files. _'parameter'.pdf will be attached.
                      **Flags**: --output
        xy: Plots X and Y for the give parameters into one figure (two axes).
            **Flags**: --xy
            **Action**: ``store_true``

    """
    LOG.debug("Starting plotting of tfs files: {:s}".format(", ".join(
        opt.files)))

    # preparations
    opt = _check_opt(opt)
    ps.set_style("standard", MANUAL_STYLE)

    twiss_data = _get_data(opt.files)

    # plotting
    figs = _create_plots(opt.x_cols, opt.y_cols, opt.e_cols, twiss_data,
                         opt.legends, opt.labels, opt.xy, opt.change_marker,
                         opt.no_legend)

    # exports
    if opt.output:
        _export_plots(figs, opt.output)

    if not opt.no_show:
        plt.show()

    return figs
def plot_detuning(x, y, x_err, y_err, labels, x_min=None, x_max=None, y_min=None, y_max=None,
                  odr_plot=linear_odr_plot, output=None, show=True):
    """ Plot amplitude detuning.

    Args:
        x: Action data.
        y: Tune data.
        x_err: Action error.
        y_err: Tune error.
        x_min: Lower action range to plot.
        x_max: Upper action range to plot.
        y_min: Lower tune range to plot.
        y_max: Upper tune range to plot.
        odr_plot: function to add a odr fitting line to axes (e.g. see linear_odr_plot)
        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)

    x_min = 0 if x_min is None else x_min
    x_max = max(x + x_err)*1.01 if x_max is None else x_max

    offset = odr_plot(ax, x, y, x_err, y_err, lim=[x_min, x_max])
    ax.errorbar(x, y-offset, xerr=x_err, yerr=y_err, label=labels.get("line", None))

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

    ax.set_xlim(left=x_min, right=x_max)
    ax.set_ylim(bottom=y_min, top=y_max)

    plt.legend(loc='lower left', bbox_to_anchor=(0.0, 1.01), ncol=2,)
    fig.tight_layout()

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

    if show:
        plt.draw()

    return fig
Beispiel #6
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()
Beispiel #7
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()
Beispiel #8
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 = regex_in(r'\AS$', rdts.columns)
        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)
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"lines.marker": 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
    ]

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

        with suppress_warnings(UserWarning):  # caused by _nolegend_
            bbq_df.plot(y=COL_BBQ(plane),
                        ax=ax[idx],
                        color=color,
                        alpha=.2,
                        label="_nolegend_")
        bbq_df.loc[mask, :].plot(y=COL_BBQ(plane),
                                 ax=ax[idx],
                                 color=color,
                                 alpha=.4,
                                 label="$Q_{:s}$ filtered".format(
                                     plane.lower()))
        bbq_df.plot(y=COL_MAV(plane),
                    ax=ax[idx],
                    color=color,
                    label="$Q_{:s}$ moving av.".format(plane.lower()))

        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")

        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'))

        # don't show labels on upper plot (if two plots)
        if idx:
            # 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)

    plt.tight_layout()

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

    if show:
        plt.draw()

    return fig
def plot_analysis(opt):
    """ Plots the specified results

    For required opt-structure look in parse_options.
    """
    LOG.debug("Plotting GetLLM analysis.")
    mdl_analysis = opt.subnode in mdl_subnodes

    ps.set_style("standard", MANUAL_STYLE)
    xmin = min(opt.xplot_xmin, opt.yplot_xmin)
    xmax = max(opt.xplot_xmax, opt.yplot_xmax)

    gs = gridspec.GridSpec(2, 1, height_ratios=[1, 1])
    ax_x = plt.subplot(gs[0])
    ax_y = None
    ir_pos = None

    paths = opt.path.split(',')

    if opt.label == 'None':
        if mdl_analysis:
            labels = [
                "mo_" + opt.path.rsplit('/', 1)[-1],
                "me_" + opt.path.rsplit('/', 1)[-1]
            ]
        else:
            labels = paths
    else:
        labels = opt.label.split(',')

    for idx, path in enumerate(paths):
        data_x, data_y = get_data(path, opt.mainnode, opt.subnode)
        plot_data(ax_x, data_x, labels, idx, opt.change_marker)

        if ir_pos is None:
            ir_pos = get_irpos(data_x, opt.accel)

        if data_y is not None:
            if ax_y is None:
                ax_x.axes.get_xaxis().set_visible(False)
                ax_y = plt.subplot(gs[1])
            plot_data(ax_y, data_y, labels, idx, opt.change_marker)

    ax_x.set_xlim(xmin, xmax)
    ax_x.set_ylim(opt.xplot_ymin, opt.xplot_ymax)
    set_yaxis_label(ax_x, 'x', opt.subnode)

    if ax_y is not None:
        ax_y.set_xlim(xmin, xmax)
        ax_y.set_ylim(opt.yplot_ymin, opt.yplot_ymax)
        set_yaxis_label(ax_y, 'y', opt.subnode)
        ps.set_xaxis_label(ax_y)
        if ir_pos:
            ps.show_ir(ir_pos, ax_y, mode='outside')
            ps.show_ir(ir_pos, ax_x, mode='lines')
    else:
        ax_x.axes.get_xaxis().set_visible(True)
        ps.set_xaxis_label(ax_x)
        if ir_pos:
            ps.show_ir(ir_pos, ax_x, mode='outside')

    if int(opt.legendh) > 12:
        show_legend(ax_x, int(opt.legendx), int(opt.legendy))
    return gs