Ejemplo n.º 1
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_data(opt):
    ps.set_style(opt['plot']['style'], manual=opt['plot']['manual_style'])
    _plot_beta(opt)
    _plot_param('phase', opt)
    _plot_param('phasetot', opt)
    _plot_tune(opt)
    _plot_coupling(opt)
def _plot_and_output(path, data, layout, title, fig=None):
    ps.set_style(PLOT_STYLE, MANUAL_STYLE_NORMAL)
    fig = mpl_wrap.plot_wrapper(data, layout, title, LEGEND_COLS, fig)
    fig.tight_layout()
    with open(path + ".json", "w") as f:
        f.write(json.dumps({'data': data, 'layout': layout}))
    fig.savefig(path + ".png")
    fig.savefig(path + ".pdf")
def _plot_separate_ampdet(cwd, data, current_params, line_names, id=None):
    """ Writing separate plots for Ampdet Terms """
    for ampdet in AMPDET_NAMES:
        title = get_plot_title(current_params)
        output_file = os.path.join(cwd, title.replace(" ", ".") + "." + ampdet)
        if id:
            output_file += "." + id
        if title[0] == "b":
            title = "Beam" + title[1:]
        LOG.info("Writing plot for '{:s}'".format(title))

        lines = []

        ps.set_style(PLOT_STYLE, MANUAL_STYLE_NORMAL)
        fig = plt.figure()
        gs = gridspec.GridSpec(1, 1, height_ratios=[1])
        ax = fig.add_subplot(gs[0])
        current_params.update(dict(ampdet=ampdet))
        if "".join(current_params["error_types"]) == "B5A5B6A6":
            add_measurement_lines(ax, current_params, line_names)

        color_cycle = get_colors()
        for line_name in line_names:
            df = data[line_name]  # assumes all df here have the same indices
            current_color = color_cycle.next()
            lines += [
                go.Scatter(
                    x=list(range(len(df.index))),
                    y=list(df.loc[:, ampdet + "_AVG"] * 1e-4),
                    error_y=dict(
                        array=list(df.loc[:, ampdet + "_STD"] * 1e-4),
                        color=current_color,
                        opacity=.5,
                    ),
                    mode='markers+lines',
                    name=line_name.replace("_", " "),
                    hoverinfo="y+text",
                    hovertext=list(df.index),
                    line=dict(color=current_color),
                )
            ]

        xaxis = dict(
            range=[-0.1, len(df.index) - 0.9],
            # title=title,
            showgrid=True,
            ticks="outer",
            ticktext=list(df.index),
            tickvals=list(range(len(df.index))))

        yaxis = dict(title=YLABEL_MAP[ampdet], )

        hack_axis(xaxis, yaxis, current_params)
        current_params.pop("ampdet")

        layout = plotly_predef.get_layout(xaxis=xaxis, yaxis=yaxis)
        _plot_and_output(output_file, lines, layout, title, fig)
def make_histogram_plots(opt):
    alpha_mean = .2
    alpha_hist = .6
    title = ""
    ps.set_style('standard')
    opt = tripcor.check_opt(opt)
    cwd = get_data_output_folder(opt.cwd)
    output_folder = get_plot_output_folder(opt.cwd)
    for beam, xing, error_types, error_loc, optic_type in hist_loop(opt):
        fig, axs = plt.subplots(len(AMPDET_NAMES), 1)
        for idx_data, output_id in _ordered_output_ids(opt.machine, beam,
                                                       opt.unused_stages):
            title, filename = get_seed_data_title_and_filename(
                beam, xing, error_types, error_loc, optic_type, output_id)
            seed_df = tfs.read_tfs(os.path.join(cwd, filename), index="SEED")
            y_max = len(seed_df.index)
            for idx_ax, term in enumerate(AMPDET_NAMES):
                ax = axs[idx_ax]
                data = seed_df[term]
                x_pos = data.mean()

                # plot mean
                stem_cont = ax.stem([x_pos], [y_max],
                                    markerfmt="",
                                    basefmt="",
                                    label="_nolegend_")
                plt.setp(stem_cont[1],
                         color=ps.get_mpl_color(idx_data),
                         alpha=alpha_mean)

                # plot std
                # error = data.std()
                # ebar_cont = ax.errorbar(x_pos, y_max, xerr=error, color=ps.get_mpl_color(idx_data),
                #                     label="_nolegend_", marker="")
                # ps.change_ebar_alpha_for_line(ebar_cont, alpha_mean)

                # plot histogram
                data.hist(ax=ax,
                          alpha=alpha_hist,
                          color=ps.get_mpl_color(idx_data),
                          label=output_id)

        for idx_ax, term in enumerate(AMPDET_NAMES):
            axs[idx_ax].set_xlabel(term)
            axs[idx_ax].set_ylabel("Seeds")

        legend = axs[0].legend()
        _reorder_legend(
            legend, _get_all_output_ids(opt.machine, beam, opt.unused_stages))
        ps.sync2d(axs)
        title = " ".join(title.split(" ")[:-1])
        figfilename = "{:s}.{:s}".format(title.replace(' ', '.'), "histogram")
        fig.canvas.set_window_title(title)
        make_bottom_text(axs[-1], title)
        fig.savefig(os.path.join(output_folder, figfilename + ".pdf"))
        fig.savefig(os.path.join(output_folder, figfilename + ".png"))
Ejemplo n.º 6
0
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(',')
    labels = _get_labels(opt.label, paths, mdl_analysis)

    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 * (1 + mdl_analysis),
                  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 * (1 + mdl_analysis),
                      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:
        ps.make_top_legend(ax_x, ps.get_legend_ncols(labels))
    return gs
Ejemplo n.º 7
0
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(',')
    labels = _get_labels(opt.label, paths, mdl_analysis)

    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 * (1 + mdl_analysis), 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 * (1 + mdl_analysis), 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:
        ps.make_top_legend(ax_x, ps.get_legend_ncols(labels))
    return gs
Ejemplo n.º 8
0
def plot_spectrum25D(spectrum, harpy_input, plane):
    nbins = 20

    freqs, amps, amp_range = _get_sorted_amp_and_freq(spectrum)
    df = np.min(freqs[1:] - freqs[:-1]) / 2

    blocks = []
    values = []
    av = np.empty(len(freqs))
    print "  |- Calculating histograms"
    for i, f in enumerate(freqs):
        # get histogram values
        amp_range_in_f = [np.min(amps[i]), np.max(amps[i])]
        a = np.histogram(amps[i], bins=nbins, range=amp_range_in_f)
        av[i] = np.average(amps[i])

        # define xy-values of blocks (counter clockwise, start=bottom left)
        y = np.append(amp_range[0], a[1])  # add empty bottom block
        yp = np.c_[y[:-1], y[:-1], y[1:], y[1:]]
        xp = np.repeat([[f - df, f + df, f + df, f - df]], nbins + 1, axis=0)

        # add to list of blocks and values
        blocks.append(np.dstack((xp, yp)))
        values.append(np.append(0, a[0]))

    blocks = np.concatenate(blocks, 0)
    values = np.concatenate(values, 0)
    pc = mc.PolyCollection(blocks, cmap='jet', edgecolors=None)
    pc.set_array(values)

    print "  |- Actual plotting"
    ps.set_style('presentation',
                 manual={
                     'lines.marker': '',
                     'grid.alpha': 0.2
                 })
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.set_xlim([freqs[0], freqs[-1]])
    ax.set_ylim(amp_range)
    ax.set_ylabel('Relative Amplitude dB')
    ax.set_xlabel('Frequency Hz')
    ax.set_title('Spectrum of plane ' + plane.upper())

    _add_tunes_to_ax(ax, harpy_input, plane)
    ax.add_collection(pc)

    ax.plot(freqs, av, label='average', color='black', linestyle='--')

    plt.colorbar(mappable=pc)
    plt.draw()
    plt.show()
    pass
Ejemplo n.º 9
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()
Ejemplo n.º 10
0
def plot_locations(locations, order, qx_lim, qy_lim, outpath=None, show=False):
    """ Plot given locations into tune diagram.

    Args:
        locations: list of triplets of Qx, Qy and label
        order: max order of resonance lines to plot
        qx_lim: limits for qx
        qy_lim: limits for qy
        outpath: save data as tfs

    Returns:
        figure
    """
    ps.set_style("standard", {
        u"figure.figsize": FIGURE_SIZE,
        u"grid.alpha": GRID_ALPHA
    })
    fig, ax = plt.subplots(1, 1)

    # do resonances
    resonances = get_resonance_lines(order)
    for r in resonances:
        r.plot(ax)

    # do locations
    _plot_locations(ax, locations, qx_lim)

    # adjust axis
    ax.set_xlim(qx_lim)
    ax.set_ylim(qy_lim)
    ax.set_xlabel("$Q_x$")
    ax.set_ylabel("$Q_y$")
    _make_lines_legend(ax, order)

    if outpath:
        fig.savefig(outpath)

    if show:
        plt.show()
    return fig
Ejemplo n.º 11
0
def plot_spectrum2D(spectrum, harpy_input, plane):
    freqs, amps, amp_range = _get_sorted_amp_and_freq(spectrum)
    print "  |- Calculating averages"
    for i in range(len(freqs)):
        print "    freq {:d} of {:d}".format(i, len(freqs))
        amps[i] = np.average(amps[i])

    print "  |- Actual plotting"
    ps.set_style('presentation')
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.set_xlim([freqs[0], freqs[-1]])
    ax.set_ylim(amp_range)
    ax.set_ylabel('Relative Amplitude dB')
    ax.set_xlabel('Frequency Hz')
    ax.set_title('Averaged Spectrum of plane ' + plane.upper())

    ax.plot(freqs, amps, label='average')
    _add_tunes_to_ax(ax, harpy_input, plane)

    plt.draw()
    plt.show()
Ejemplo n.º 12
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)
Ejemplo n.º 13
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()
Ejemplo n.º 14
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
Ejemplo n.º 15
0
def _create_plots(x_cols, y_cols, e_cols, datas, file_labels, column_labels, y_labels,
                  xy, change_marker, no_legend, auto_scale, figure_per_file=False):
    # create layout
    ps.set_style("standard", MANUAL_STYLE)
    ir_positions, x_is_position = _get_ir_positions(datas, x_cols)

    y_lims = None
    the_loop = _LoopGenerator(x_cols, y_cols, e_cols, datas,
                              file_labels, column_labels, y_labels,
                              xy, figure_per_file)

    for ax, idx_plot, idx, data, x_col, y_col, e_col, legend, y_label, last_line in the_loop():
        # plot data
        y_label_from_col, y_plane, y_col, e_col, chromatic = _get_names_and_columns(idx_plot, xy,
                                                                                     y_col, e_col)

        x_val, y_val, e_val = _get_column_data(data, x_col, y_col, e_col)

        ebar = ax.errorbar(x_val, y_val, yerr=e_val,
                           ls=rcParams[u"lines.linestyle"], fmt=get_marker(idx, change_marker),
                           label=legend)

        _change_ebar_alpha(ebar)

        if auto_scale:
            current_y_lims = _get_auto_scale(y_val, auto_scale)
            if y_lims is None:
                y_lims = current_y_lims
            else:
                y_lims = [min(y_lims[0], current_y_lims[0]),
                          max(y_lims[1], current_y_lims[1])]
            if last_line:
                ax.set_ylim(*y_lims)

        # things to do only once
        if last_line:
            # setting the y_label
            if y_label is None:
                _set_ylabel(ax, y_col, y_label_from_col, y_plane, chromatic)
            else:
                y_label_from_label = ""
                if y_label:
                    y_label_from_label, y_plane, _, _, chromatic = _get_names_and_columns(
                        idx_plot, xy, y_label, "")
                if xy:
                    y_label = "{:s} {:s}".format(y_label, y_plane)
                _set_ylabel(ax, y_label, y_label_from_label, y_plane, chromatic)

            # setting x limits
            if x_is_position:
                try:
                    ps.set_xLimits(data.SEQUENCE, ax)
                except (AttributeError, ps.ArgumentError):
                    pass

            # setting visibility, ir-markers and label
            if xy and idx_plot == 0:
                ax.axes.get_xaxis().set_visible(False)
                if x_is_position and ir_positions:
                    ps.show_ir(ir_positions, ax, mode='lines')
            else:
                if x_is_position:
                    ps.set_xaxis_label(ax)
                    if ir_positions:
                        ps.show_ir(ir_positions, ax, mode='outside')

            if not no_legend and idx_plot == 0:
                ps.make_top_legend(ax, the_loop.get_ncols())

    return the_loop.get_figs()
def make_cta_histogram(opt):
    alpha_mean = 1
    alpha_hist = .4
    mod_one = lambda x: np.mod(x, 1)
    ps.set_style('standard', MANUAL_STYLE_CTA)
    opt = tripcor.check_opt(opt)
    cwd = get_data_output_folder(opt.cwd)
    output_folder = get_cta_plot_output_folder(opt.cwd)
    for beam, error_types, error_loc, optic_type in cta_loop(opt):
        fig, ax = plt.subplots(1, 1)
        color_cycle = get_colors()
        for xing in opt.xing:
            color = color_cycle.next()
            _, filename = get_cta_seed_data_title_and_filename(
                beam, xing, error_types, error_loc, optic_type)

            xing_label = tripcor.get_nameparts_from_parameters(xing=xing)[0]
            try:
                xing_label = legend_map[xing_label]
            except KeyError:
                pass

            seed_df = tfs.read_tfs(os.path.join(cwd, filename),
                                   index="SEED").apply(mod_one)
            diff = np.abs(seed_df.QX - seed_df.QY) * 1e4

            y_max = len(seed_df.index) / 3

            # plot mean
            x_pos = diff.mean()
            stem_cont = ax.stem([x_pos], [y_max],
                                markerfmt="",
                                basefmt="",
                                label="_nolegend_")
            plt.setp(stem_cont[1], color=color, alpha=alpha_mean, ls="--")

            # plot std
            # error = data.std()
            # ebar_cont = ax.errorbar(x_pos, y_max, xerr=error, color=ps.get_mpl_color(idx_data),
            #                     label="_nolegend_", marker="")
            # ps.change_ebar_alpha_for_line(ebar_cont, alpha_mean)

            # plot histogram
            if diff.std() > 0:
                diff.hist(ax=ax,
                          alpha=alpha_hist,
                          color=color,
                          label="_nolegend_")
                diff.hist(ax=ax,
                          histtype="step",
                          color=color,
                          label=xing_label)

        ax.set_xlabel("|C$^{-}$| [$10^{-4}$]")
        ax.set_ylabel("Count")
        legend = ps.make_top_legend(ax, 2)
        legend.remove()

        figtitle, figfilename = get_cta_plot_title_and_filename(
            beam, error_types, error_loc, optic_type)
        fig.canvas.set_window_title(figtitle)
        fig.tight_layout()
        fig.savefig(os.path.join(output_folder, figfilename + ".hist.pdf"))
        fig.savefig(os.path.join(output_folder, figfilename + ".hist.png"))
Ejemplo n.º 17
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
Ejemplo n.º 18
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