Exemplo n.º 1
0
def subplot_setter(ax: plt.Axes, vis_settings: VisualizerSettings,
                   subplot_settings: SubplotSettings) -> None:
    tick_params = {
        "labelleft": subplot_settings.labelleft,
        "left": subplot_settings.left,
        "labelbottom": subplot_settings.labelbottom,
        "bottom": subplot_settings.bottom
    }

    ax.tick_params(**tick_params)

    if subplot_settings.xlabel is not None:
        ax.set_xlabel(subplot_settings.xlabel)
    if subplot_settings.ylabel is not None:
        ax.set_ylabel(subplot_settings.ylabel)
    if subplot_settings.xlim is not None:
        ax.set_xlim(subplot_settings.xlim)
    if subplot_settings.ylim is not None:
        ax.set_ylim(subplot_settings.ylim)
    if subplot_settings.legend:
        ax.legend()
    if vis_settings.grid:
        ax.grid()
    if subplot_settings.log_scale:
        ax.set_yscale("log")
Exemplo n.º 2
0
def _plot_monthly_averages(ax: pl.Axes, data: pd.DataFrame) -> None:
    # Calculate cumulative snow totals per month in each year
    data["Cumulative Snow"] = (data["SNOW"].groupby(
        [data.index.year, data.index.month]).cumsum())

    # Average these things by month over all years
    avg_per_month = data.groupby(
        data.index.month).mean()[["Cumulative Snow", "TAVG", "TMAX", "TMIN"]]

    # This is to cycle the whole DF so July is at the start
    dummy_sort_key = "dummy"
    avg_per_month[dummy_sort_key] = np.roll(avg_per_month.index, 6)
    avg_per_month.sort_values(dummy_sort_key, inplace=True)
    avg_per_month.drop(dummy_sort_key, axis=1, inplace=True)

    # Replace index month numbers with month names
    avg_per_month.set_index(
        pd.to_datetime(avg_per_month.index, format="%m").strftime("%b"),
        inplace=True,
    )

    # Plot
    avg_per_month.plot.bar(
        ax=ax,
        secondary_y=[
            col for col in avg_per_month.columns if col != "Cumulative Snow"
        ],
    )

    ax.grid(True)
    ax.right_ax.grid(False)
    ax.set_xlabel("Month")
    ax.set_ylabel("Snowfall (Inches)")
    ax.right_ax.set_ylabel("Temperature (F)")
Exemplo n.º 3
0
def animate_pendulum(ax: plt.Axes, t: np.array, sol: np.array, l=1):
    ''' animate pendulum model
    :param t: (N) time value
    :param sol: (N, 2) odeint solution
        sol[:, 0] is the angular position, sol[:, 1] is the angular rate
    :return: list of plot elements
    '''

    plt.rcParams['font.size'] = 15
    lns = []
    for i in range(len(sol)):
        ln, = ax.plot([0, l * np.sin(sol[i, 0] + np.pi)],
                      [0, -l * np.cos(sol[i, 0] + np.pi)],
                      color='k',
                      lw=2)
        pt = ax.scatter([l * np.sin(sol[i, 0] + np.pi)],
                        [-l * np.cos(sol[i, 0] + np.pi)],
                        s=100,
                        c='k')
        tm = ax.text(-l, 0.9 * l, 'time = %.1fs' % t[i])
        lns.append([ln, pt, tm])
    margin = np.abs(l) * 0.05
    ax.set_xlim(-l - margin, l + margin)
    ax.set_ylim(-l - margin, l + margin)
    ax.grid()
    return lns
Exemplo n.º 4
0
def format_axes(
    ax: plt.Axes,
    ticklabels,
    patch_size,
    total_size,
    block_size,
):
    robust_models = [1, 2]
    ax_mm_ticks = np.arange(0, total_size, block_size)
    ax.set_xticks(ax_mm_ticks - 0.5)
    ax.set_yticks(ax_mm_ticks - 0.5)
    ax.set_xticklabels(ax_mm_ticks)
    ax.set_yticklabels(ax_mm_ticks)
    ax.grid(which='major', axis='both', lw=1, color='k', alpha=0.5, ls='-')
    ax.set_xticks(ax_mm_ticks + block_size / 2, minor=True)
    ax.set_yticks(ax_mm_ticks + block_size / 2, minor=True)
    ax.set_xticklabels([])
    ax.set_yticklabels([])
    ax.set_xticklabels(ticklabels, minor=True, fontsize=12, weight='light')
    ax.set_yticklabels(ticklabels, minor=True, fontsize=12, weight='light')
    plt.setp(ax.get_yticklabels(minor=True),
             rotation=90,
             ha="center",
             va="bottom",
             rotation_mode="anchor")
    # ax.set_title(f'Patch Size {patch_size}', fontsize=1, pad=10)
    ax.set_xlabel('Models', fontsize=14)
    ax.set_ylabel('Models', fontsize=14)
    ax.xaxis.labelpad = 7
    ax.yaxis.labelpad = 7
Exemplo n.º 5
0
def group_plot(axis: plt.Axes, title: str, names: List[str],
               ratios: List[Dict[AgentType, List[float]]]):
    """Generate a joint plot for a benchmark result group on `axis`"""
    axis.set_title(title)
    axis.set_xlabel("Time")
    axis.set_ylabel("Safe agents (%)")
    axis.set_yticks(range(0, 101, 10))
    axis.grid(True)
    legend: Tuple[List[plt.Line2D], List[str]] = ([], [])
    dark = get_cmap("Dark2")
    for i, rs in enumerate(ratios):
        line_name = names[i].split("_")[-1]
        for (j, typ) in enumerate(rs):
            data = list(map(lambda x: x * 100, rs[typ]))
            xdata = data[:data.index(100) + 1]
            axis.plot(xdata,
                      color=dark(i),
                      linestyle=AGENT_STYLES[typ.name],
                      linewidth=2)
            if j == 0:
                legend_line = plt.Line2D(xdata,
                                         range(0, len(xdata)),
                                         color=dark(i),
                                         linestyle="solid")
                legend[0].append(legend_line)
                legend[1].append(line_name)
    axis.legend(*legend, loc=4, fontsize="large")
def common_plotting_settings(plot: plt.Axes, plot_def: PlotDef,
                             xaxis_title: str,
                             yaxis_title: str) -> Optional[mpl.legend.Legend]:
    """Common settings for plots.

    Args:
        plot: a pyplot plot object
        plot_def: a `PlotDef` that defines properties of the plot
        xaxis_title: label for x-axis
        yaxis_title: label for y-axis
    """
    plot.set_xlabel(xaxis_title)
    plot.set_ylabel(yaxis_title)
    if plot_def.title:
        plot.set_title(plot_def.title)
    plot.grid(True)

    # get handles and labels for the legend
    handles, labels = plot.get_legend_handles_labels()
    # remove the errorbars from the legend if they are there
    handles = [(h[0] if isinstance(h, tuple) else h) for h in handles]

    if plot_def.legend_pos == "inside":
        return plot.legend(handles, labels)
    if plot_def.legend_pos == "outside":
        return plot.legend(handles,
                           labels,
                           loc="upper left",
                           bbox_to_anchor=(1, plot_def.legend_yanchor))
    return None
Exemplo n.º 7
0
def plot_ghi_curves(
    clearsky_ghi: np.ndarray,
    station_ghi: np.ndarray,
    pred_ghi: typing.Optional[np.ndarray],
    window_start: datetime.datetime,
    window_end: datetime.datetime,
    sample_step: datetime.timedelta,
    horiz_offset: datetime.timedelta,
    ax: plt.Axes,
    station_name: typing.Optional[typing.AnyStr] = None,
    station_color: typing.Optional[typing.AnyStr] = None,
    current_time: typing.Optional[datetime.datetime] = None,
) -> plt.Axes:
    """Plots a set of GHI curves and returns the associated matplotlib axes object.

    This function is used in ``draw_daily_ghi`` and ``preplot_live_ghi_curves`` to create simple
    graphs of GHI curves (clearsky, measured, predicted).
    """
    assert clearsky_ghi.ndim == 1 and station_ghi.ndim == 1 and clearsky_ghi.size == station_ghi.size
    assert pred_ghi is None or (pred_ghi.ndim == 1
                                and clearsky_ghi.size == pred_ghi.size)
    hour_tick_locator = matplotlib.dates.HourLocator(interval=4)
    minute_tick_locator = matplotlib.dates.HourLocator(interval=1)
    datetime_fmt = matplotlib.dates.DateFormatter("%H:%M")
    datetime_range = pd.date_range(window_start, window_end, freq=sample_step)
    xrange_real = matplotlib.dates.date2num(
        [d.to_pydatetime() for d in datetime_range])
    if current_time is not None:
        ax.axvline(x=matplotlib.dates.date2num(current_time),
                   color="r",
                   label="current")
    station_name = f"measured ({station_name})" if station_name else "measured"
    ax.plot(xrange_real, clearsky_ghi, ":", label="clearsky")
    if station_color is not None:
        ax.plot(xrange_real,
                station_ghi,
                linestyle="solid",
                color=station_color,
                label=station_name)
    else:
        ax.plot(xrange_real,
                station_ghi,
                linestyle="solid",
                label=station_name)
    datetime_range = pd.date_range(window_start + horiz_offset,
                                   window_end + horiz_offset,
                                   freq=sample_step)
    xrange_offset = matplotlib.dates.date2num(
        [d.to_pydatetime() for d in datetime_range])
    if pred_ghi is not None:
        ax.plot(xrange_offset, pred_ghi, ".-", label="predicted")
    ax.xaxis.set_major_locator(hour_tick_locator)
    ax.xaxis.set_major_formatter(datetime_fmt)
    ax.xaxis.set_minor_locator(minute_tick_locator)
    hour_offset = datetime.timedelta(hours=1) // sample_step
    ax.set_xlim(xrange_real[hour_offset - 1], xrange_real[-hour_offset + 1])
    ax.format_xdata = matplotlib.dates.DateFormatter("%Y-%m-%d %H:%M")
    ax.grid(True)
    return ax
Exemplo n.º 8
0
def plot_eeg_fft(data, ax: plt.Axes, fs: int = 256):
    N = data.shape[0]
    yf = fft(data)
    xf = fftfreq(N, 1 / fs)[:N // 2]

    ax.plot(xf, abs(yf[:N // 2]))
    ax.grid()
    pass
Exemplo n.º 9
0
 def plot_index(self, period: int, n: int, ax: plt.Axes = None):
     plot_data = self.featured_data(period, n) * 100
     if ax is None:
         _, ax = plt.subplots(1, 1)
     plot_data.plot(ax=ax)
     ax.set_xlim(left=plot_data.index[0], right=plot_data.index[-1])
     ax.grid(True)
     ax.yaxis.set_major_formatter(mtick.PercentFormatter())
     return ax
Exemplo n.º 10
0
def add_grid(ax: plt.Axes, is_grid: bool):  # pylint: disable=invalid-name
    """
    Add/remove grid to figure.

    :param ax: Figure axes.
    :type ax: matplotlib.pyplot.Axes
    :param is_grid: Add or remote grid to plot
    :type is_grid: bool
    """
    ax.grid(is_grid)
Exemplo n.º 11
0
def measureTau(abf: pyabf.ABF,
               sweep: int,
               epoch: int = 3,
               percentile: float = .05,
               ax: plt.Axes = None):

    abf.setSweep(sweep)

    # use epoch table to determine puff times
    puffTimeStart = abf.sweepEpochs.p1s[epoch] / abf.sampleRate
    puffTimeEnd = abf.sweepEpochs.p2s[epoch] / abf.sampleRate

    # calculate baseline level
    baselineStart = puffTimeStart - .1
    baselineEnd = puffTimeStart
    baselineMean = getMean(abf, baselineStart, baselineEnd)

    # find antipeak
    antipeakIndex = getAntiPeakIndex(abf.sweepY, abf.sampleRate, puffTimeStart,
                                     puffTimeStart + .5)
    antipeakLevel = abf.sweepY[antipeakIndex]

    # find portion of curve to fit
    curveIndex1, curveIndex2 = getCurveIndexes(abf.sweepY, antipeakIndex,
                                               baselineMean, percentile)
    curveYs = -abf.sweepY[curveIndex1:curveIndex2]
    curveXs = np.arange(len(curveYs)) / abf.sampleRate

    try:
        p0 = (500, 15, 0)  # start with values near those we expect
        params, cv = scipy.optimize.curve_fit(monoExp, curveXs, curveYs, p0)
    except:
        print(f"FIT FAILED (sweep {sweep})")
        return None
    m, t, b = params
    curveYsIdeal = monoExp(curveXs, m, t, b)
    tauMS = 1000 / t
    if (tauMS < 0):
        return None

    if ax:
        yPad = abs(antipeakLevel - baselineMean) * .1
        ax.plot(abf.sweepX, abf.sweepY, alpha=.5)
        ax.grid(alpha=.5, ls='--')
        ax.axhline(baselineMean, ls='--', color='k')
        ax.plot(abf.sweepX[curveIndex1:curveIndex2], -curveYsIdeal, color='k')
        ax.set(title=f"first sweep tau = {tauMS:.02f} ms")
        ax.axis([
            baselineStart - .1, baselineStart + 1, antipeakLevel - yPad,
            baselineMean + yPad
        ])
        ax.axvspan(puffTimeEnd, puffTimeEnd + .5, color='g', alpha=.1)
        ax.axvspan(puffTimeEnd + .5, puffTimeEnd + .6, color='m', alpha=.1)

    return tauMS
Exemplo n.º 12
0
    def _plot_deviation(self,
                        item: str,
                        ax: plt.Axes = None,
                        show: bool = True):
        """Helper function: Plot the sag in Cartesian coordinates.

        Parameters
        ----------
        item : {'gantry', 'epid', 'collimator', 'couch'}
            The axis to plot.
        ax : None, matplotlib.Axes
            The axis to plot to. If None, creates a new plot.
        show : bool
            Whether to show the image.
        """
        title = 'Relative {} displacement'.format(item)
        if item == EPID:
            attr = 'epid'
            item = GANTRY
        else:
            attr = 'bb'
        # get axis images, angles, and shifts
        imgs = [
            image for image in self.images
            if image.variable_axis in (item, REFERENCE)
        ]
        angles = [
            getattr(image, '{}_angle'.format(item.lower())) for image in imgs
        ]
        z_sag = np.array(
            [getattr(image, attr + '_z_offset') for image in imgs])
        y_sag = np.array(
            [getattr(image, attr + '_y_offset') for image in imgs])
        x_sag = np.array(
            [getattr(image, attr + '_x_offset') for image in imgs])
        rms = np.sqrt(x_sag**2 + y_sag**2 + z_sag**2)

        # plot the axis deviation
        if ax is None:
            ax = plt.subplot(111)
        ax.plot(angles, z_sag, 'bo', label='In/Out', ls='-.')
        ax.plot(angles, x_sag, 'm^', label='Left/Right', ls='-.')
        if item not in (COUCH, COLLIMATOR):
            ax.plot(angles, y_sag, 'r*', label='Up/Down', ls='-.')
        ax.plot(angles, rms, 'g+', label='RMS', ls='-')
        ax.set_title(title)
        ax.set_ylabel('mm')
        ax.set_xlabel("{} angle".format(item))
        ax.set_xticks(np.arange(0, 361, 45))
        ax.set_xlim([-15, 375])
        ax.grid(True)
        ax.legend(numpoints=1)
        if show:
            plt.show()
Exemplo n.º 13
0
def _axis_formatting(ax: plt.Axes, xlen: int, ylen: int) -> None:
    """Construct figure and set sensible defaults."""
    # Axes limits
    ax.set_xlim(0, xlen)
    ax.set_ylim(0, ylen)
    # Make ticks centred in each cell
    _set_ticks(xlen, ax.xaxis)
    _set_ticks(ylen, ax.yaxis)
    # Draw grid along minor ticks, then remove those ticks so they don't protrude
    ax.grid(which="minor", color="k")
    ax.tick_params(which="minor", length=0, width=0)
Exemplo n.º 14
0
def plot_text(axes: plt.Axes, text: str):
    """Plot text on an axes

    Args:
        axes (plt.Axes): an axes object
        text (str): the text
    """

    axes.axis('off')
    axes.grid('off')
    axes.text(x=0, y=0, s=text, horizontalalignment='left', fontdict=FONT)
Exemplo n.º 15
0
    def attach_electric_potential_plot_to_axis(
        self,
        axis: plt.Axes,
        show_electric_field: bool = True,
        show_vector_potential: bool = True,
        time_unit: u.Unit = "asec",
        legend_kwargs: Optional[dict] = None,
        show_y_label: bool = False,
    ):
        time_unit_value, time_unit_latex = u.get_unit_value_and_latex(
            time_unit)

        if legend_kwargs is None:
            legend_kwargs = dict()
        legend_defaults = dict(loc="lower left",
                               fontsize=10,
                               fancybox=True,
                               framealpha=0.3)
        legend_kwargs = {**legend_defaults, **legend_kwargs}

        if show_electric_field:
            axis.plot(
                self.sim.data_times / time_unit_value,
                self.sim.data.electric_field_amplitude /
                u.atomic_electric_field,
                color=vis.COLOR_EFIELD,
                linewidth=1.5,
                label=fr"$ {vis.LATEX_EFIELD}(t) $",
            )
        if show_vector_potential:
            axis.plot(
                self.sim.data_times / time_unit_value,
                u.proton_charge * self.sim.data.vector_potential_amplitude /
                u.atomic_momentum,
                color=vis.COLOR_AFIELD,
                linewidth=1.5,
                label=fr"$ e \, {vis.LATEX_AFIELD}(t) $",
            )

        if show_y_label:
            axis.set_ylabel(rf"${vis.LATEX_EFIELD}(t)$",
                            fontsize=13,
                            color=vis.COLOR_EFIELD)

        axis.set_xlabel(rf"Time $t$ (${time_unit_latex}$)", fontsize=13)

        axis.tick_params(labelright=True)

        axis.set_xlim(self.sim.times[0] / time_unit_value,
                      self.sim.times[-1] / time_unit_value)

        axis.legend(**legend_kwargs)

        axis.grid(True, **si.vis.DEFAULT_GRID_KWARGS)
Exemplo n.º 16
0
def draw_trajectory_axis(env_axes: typing.Tuple[typing.Tuple, typing.Tuple],
                         ax: plt.Axes,
                         legend: bool = True,
                         grid: bool = True):
    # Set axes limitations for x- and y-axis and add legend and grid to visualization.
    ax.set_xlim(*env_axes[0])
    ax.set_ylim(*env_axes[1])
    if grid:
        ax.grid()
    if legend:
        ax.legend()
    return ax
Exemplo n.º 17
0
def plot_sir_model(ax: plt.Axes,
                   model: "SIRModel",
                   include_susceptible=True) -> plt.Axes:

    ax.margins(0)

    xs = model.x_obs
    ys = model.observe()

    y_min = 0,
    if (include_susceptible):
        y_max = np.ceil(model.population_size / 1000) * 1000
    else:
        y_max = max([max(y[1:]) for y in ys])
        mag = np.floor(np.log10(y_max))
        y_max = (10**mag) * np.ceil(y_max / (10**mag))

    x_min = min(xs, key=lambda x: x[0])[0]
    x_max = max(xs, key=lambda x: x[0])[0]

    # S
    if (include_susceptible):
        i = 0
        y_obs = [y[i] for y in ys]
        ax.scatter(xs, y_obs, c="green", label="Susceptible")

    # I
    i = 1
    y_obs = [y[i] for y in ys]
    ax.scatter(xs, y_obs, c="blue", label="Infectious")

    # R
    i = 2
    y_obs = [y[i] for y in ys]
    ax.scatter(xs, y_obs, c="red", label="Removed")

    ax.set_title("Realisation of Population Sizes for Standard SIR Model",
                 fontsize=20)

    ax.set_xlabel("Time-Period", fontsize=16)
    ax.set_ylabel("Population Size", fontsize=16)

    ax.set_xticks(list(range(x_min, x_max, 7)) + [x_max])
    ax.set_yticks(np.linspace(0, y_max, 5))
    ax.set_yticklabels(["{:,.0f}".format(x) for x in np.linspace(0, y_max, 5)])

    ax.legend()
    ax.grid()

    return
Exemplo n.º 18
0
    def _plot_deviation(self,
                        item: str,
                        ax: plt.Axes = None,
                        show: bool = True):
        """Helper function: Plot the sag in Cartesian coordinates.

        Parameters
        ----------
        item : {'gantry', 'epid', 'collimator', 'couch'}
            The axis to plot.
        ax : None, matplotlib.Axes
            The axis to plot to. If None, creates a new plot.
        show : bool
            Whether to show the image.
        """
        title = f'In-plane {item} displacement'
        if item == EPID:
            attr = 'cax2epid_vector'
            item = GANTRY
        else:
            attr = 'cax2bb_vector'
        # get axis images, angles, and shifts
        imgs = [
            image for image in self.images
            if image.variable_axis in (item, REFERENCE)
        ]
        angles = [
            getattr(image, '{}_angle'.format(item.lower())) for image in imgs
        ]
        xz_sag = np.array([getattr(img, attr).x for img in imgs])
        y_sag = np.array([getattr(img, attr).y for img in imgs])
        rms = np.sqrt(xz_sag**2 + y_sag**2)

        # plot the axis deviation
        if ax is None:
            ax = plt.subplot(111)
        ax.plot(angles, y_sag, 'bo', label='Y-axis', ls='-.')
        ax.plot(angles, xz_sag, 'm^', label='X/Z-axis', ls='-.')
        ax.plot(angles, rms, 'g+', label='RMS', ls='-')
        ax.set_title(title)
        ax.set_ylabel('mm')
        ax.set_xlabel(f"{item} angle")
        ax.set_xticks(np.arange(0, 361, 45))
        ax.set_xlim([-15, 375])
        ax.grid(True)
        ax.legend(numpoints=1)
        if show:
            plt.show()
    def _draw_axes(self, ax: plt.Axes):
        ax.grid(which='both')
        max_magn = 1.0
        max_field = 2.0

        stepy = np.abs(max_magn / 10)
        zero_yy = np.arange(-max_magn - stepy, max_magn + 2 * stepy, stepy)
        zero_yx = np.zeros((len(zero_yy), 1))

        stepx = np.abs(max_field / 10)
        zero_xx = np.arange(-max_field - stepx, max_field + 2 * stepx, stepx)
        zero_xy = np.zeros((len(zero_xx), 1))

        ax.plot(zero_yx, zero_yy, '--k', zero_xx, zero_xy, '--k')
        ax.set_ylim(np.min(zero_yy), np.max(zero_yy))
        ax.set_xlim(np.min(zero_xx), np.max(zero_xx))
Exemplo n.º 20
0
    def style_twin_axes(self, ax1: plt.Axes, ax2: plt.Axes):
        """Apply styling to a twin axes

        Parameters
        ----------
        ax1 : plt.Axes
            Primary matplolib axis
        ax2 : plt.Axes
            Twinx matplolib axis

        """

        ax1.tick_params(axis="x", labelrotation=self.xticks_rotation)
        ax1.grid(axis="both", visible=True, zorder=0)

        ax2.grid(visible=False)
Exemplo n.º 21
0
def animate_waveforms(ax: plt.Axes, t: np.array, sol: np.array):
    ''' animate waveforms over time
    :param ax: plt.axis
    :param t: (N) times
    :param sol: (N, 2) pendulum solution
    :return: list of line plots
    '''
    lns = []
    for i in range(len(sol)):
        ln = ax.plot(t[:i], sol[:i, 0], 'g')
        ln1 = ax.plot(t[:i], sol[:i, 1], 'b')
        lns.append([*ln, *ln1])
    ax.legend(['position', 'rate'])
    ax.set_xlim(0, t.max())
    ax.set_ylim(sol.min(), sol.max())
    ax.grid()
    return lns
Exemplo n.º 22
0
def plot_throughput(df: pd.DataFrame, ax: plt.Axes,
                    grouping_columns: Tuple[str, ...], x_column: str,
                    y_columns: List[str]) -> None:
    def outlier_mean(c: str):
        def f(g: pd.DataFrame) -> float:
            cutoff = 0.5 * g[c].max()
            return g[g[c] >= cutoff][c].mean() / 100000

        return f

    def outlier_std(c: str):
        def f(g: pd.DataFrame):
            cutoff = 0.5 * g[c].max()
            return g[g[c] >= cutoff][c].std() / 100000

        return f

    # Draw throughput.
    grouped = df.groupby(grouping_columns)
    for (name, group) in grouped:
        name = [name] if len(grouping_columns) == 1 else name
        label = ','.join(f'{f}={x}' for (f, x) in zip(grouping_columns, name))
        by_acceptors = group.groupby(x_column)
        for c in y_columns:
            throughput = by_acceptors.apply(outlier_mean(c)).sort_index()
            std = by_acceptors.apply(outlier_std(c)).sort_index()
            line = ax.plot(throughput.index,
                           throughput,
                           '-',
                           marker=next(MARKERS),
                           label=f'{c} {label}',
                           linewidth=1.5)[0]
            # Draw error bars.
            ax.fill_between(throughput.index,
                            throughput - std,
                            throughput + std,
                            color=line.get_color(),
                            alpha=0.3)

    ax.set_xlabel(x_column)
    ax.set_ylabel('Throughput\n(100,000 commands per second)')
    ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
    ax.grid()
Exemplo n.º 23
0
    def _plot_deviation(self, item: str, ax: plt.Axes=None, show: bool=True):
        """Helper function: Plot the sag in Cartesian coordinates.

        Parameters
        ----------
        item : {'gantry', 'epid', 'collimator', 'couch'}
            The axis to plot.
        ax : None, matplotlib.Axes
            The axis to plot to. If None, creates a new plot.
        show : bool
            Whether to show the image.
        """
        title = f'Relative {item} displacement'
        if item == EPID:
            attr = 'epid'
            item = GANTRY
        else:
            attr = 'bb'
        # get axis images, angles, and shifts
        imgs = [image for image in self.images if image.variable_axis in (item, REFERENCE)]
        angles = [getattr(image, '{}_angle'.format(item.lower())) for image in imgs]
        z_sag = np.array([getattr(image, attr + '_z_offset') for image in imgs])
        y_sag = np.array([getattr(image, attr + '_y_offset') for image in imgs])
        x_sag = np.array([getattr(image, attr + '_x_offset') for image in imgs])
        rms = np.sqrt(x_sag**2+y_sag**2+z_sag**2)

        # plot the axis deviation
        if ax is None:
            ax = plt.subplot(111)
        ax.plot(angles, z_sag, 'bo', label='In/Out', ls='-.')
        ax.plot(angles, x_sag, 'm^', label='Left/Right', ls='-.')
        if item not in (COUCH, COLLIMATOR):
            ax.plot(angles, y_sag, 'r*', label='Up/Down', ls='-.')
        ax.plot(angles, rms, 'g+', label='RMS', ls='-')
        ax.set_title(title)
        ax.set_ylabel('mm')
        ax.set_xlabel(f"{item} angle")
        ax.set_xticks(np.arange(0, 361, 45))
        ax.set_xlim([-15, 375])
        ax.grid(True)
        ax.legend(numpoints=1)
        if show:
            plt.show()
Exemplo n.º 24
0
def plot_im(ax: plt.Axes, image: torch.Tensor, true_class: str):
    """Plots given image on given axes. Sets title of image to true_class.

    Args:
        ax (plt.Axes): Axes on which to draw.
        image (torch.Tensor): Tensor image which has to be drawn on axes.
        true_class (str): Name of image class.
    """
    image = un_normalize(image)
    image_cpu: np.ndarray = image.cpu().detach().numpy()
    im_max = np.max(image_cpu)
    im_min = np.min(image_cpu)
    image_cpu = (image_cpu - im_min) / (im_max - im_min)
    image_cpu = np.transpose(image_cpu, [1, 2, 0])
    ax.set_title(true_class)
    ax.annotate(true_class, xy=(112, 112))
    ax.grid(False)
    ax.set_axis_off()
    ax.imshow(image_cpu)
Exemplo n.º 25
0
    def _plot_analyzed_subimage(self,
                                subimage: str,
                                show: bool = True,
                                ax: plt.Axes = None):
        """Plot an individual piece of the VMAT analysis.

        Parameters
        ----------
        subimage : str
            Specifies which image to plot.
        show : bool
            Whether to actually plot the image.
        ax : matplotlib Axes, None
            If None (default), creates a new figure to plot to, otherwise plots to the given axes.
        """
        plt.ioff()
        if ax is None:
            fig, ax = plt.subplots()

        # plot DMLC or OPEN image
        if subimage in (DMLC, OPEN):
            if subimage == DMLC:
                img = self.dmlc_image
            elif subimage == OPEN:
                img = self.open_image
            ax.imshow(img, cmap=get_dicom_cmap())
            self._draw_segments(ax)
            plt.sca(ax)
            plt.axis('off')
            plt.tight_layout()

        # plot profile
        elif subimage == PROFILE:
            dmlc_prof, open_prof = self._median_profiles(
                (self.dmlc_image, self.open_image))
            ax.plot(dmlc_prof.values, label='DMLC')
            ax.plot(open_prof.values, label='Open')
            ax.autoscale(axis='x', tight=True)
            ax.legend(loc=8, fontsize='large')
            ax.grid()

        if show:
            plt.show()
Exemplo n.º 26
0
def plot_lt(df: pd.DataFrame, ax: plt.Axes, title: str) -> None:
    def outlier_throughput(g: pd.DataFrame) -> float:
        cutoff = 0.5 * g['throughput'].max()
        return g[g['throughput'] >= cutoff]['throughput'].mean() / 100000

    def outlier_throughput_std(g: pd.DataFrame) -> float:
        cutoff = 0.5 * g['throughput'].max()
        return g[g['throughput'] >= cutoff]['throughput'].std() / 100000

    # Draw throughput.
    grouped = df.groupby([
        'num_shards', 'num_replicas', 'num_proxy_replicas',
        'server_options.push_size', 'server_options.push_period',
        'aggregator_options.num_shard_cuts_per_proposal',
        'replica_options.unsafe_yolo_execution'
    ])
    for (name, group) in grouped:
        print(f'## {name}')
        print(group[['throughput', 'latency']])

        by_clients = group.groupby('num_clients')
        throughput = by_clients['throughput'].agg(np.mean).sort_index() / 1000
        throughput_std = by_clients['throughput'].agg(
            np.std).sort_index() / 1000
        latency = by_clients['latency'].agg(np.mean).sort_index()
        line = ax.plot(throughput,
                       latency,
                       '-',
                       marker=next(MARKERS),
                       label=name,
                       linewidth=2)[0]
        ax.fill_betweenx(latency,
                         throughput - throughput_std,
                         throughput + throughput_std,
                         color=line.get_color(),
                         alpha=0.25)

        ax.grid()
        ax.set_title(title)
        ax.set_xlabel('Throughput (100,000 commands per second)')
        ax.set_ylabel('Latency\n(milliseconds)')
        ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
Exemplo n.º 27
0
    def _plot_analyzed_subimage(self, subimage: str, show: bool=True, ax: plt.Axes=None):
        """Plot an individual piece of the VMAT analysis.

        Parameters
        ----------
        subimage : str
            Specifies which image to plot.
        show : bool
            Whether to actually plot the image.
        ax : matplotlib Axes, None
            If None (default), creates a new figure to plot to, otherwise plots to the given axes.
        """
        plt.ioff()
        if ax is None:
            fig, ax = plt.subplots()

        # plot DMLC or OPEN image
        if subimage in (DMLC, OPEN):
            if subimage == DMLC:
                img = self.dmlc_image
            elif subimage == OPEN:
                img = self.open_image
            ax.imshow(img, cmap=get_dicom_cmap())
            self._draw_segments(ax)
            plt.sca(ax)
            plt.axis('off')
            plt.tight_layout()

        # plot profile
        elif subimage == PROFILE:
            dmlc_prof, open_prof = self._median_profiles((self.dmlc_image, self.open_image))
            ax.plot(dmlc_prof.values, label='DMLC')
            ax.plot(open_prof.values, label='Open')
            ax.autoscale(axis='x', tight=True)
            ax.legend(loc=8, fontsize='large')
            ax.grid()

        if show:
            plt.show()
Exemplo n.º 28
0
def plot_rhythm_grid(axes: plt.Axes,
                     rhythm: Rhythm,
                     unit: Unit,
                     axis='x'):  # TODO fix axis option
    duration = rhythm.get_duration(unit, ceil=True)
    measure_duration = rhythm.get_measure_duration(unit)
    beat_duration = rhythm.get_beat_duration(unit)

    measure_grid_ticks = np.arange(0, duration + 1, measure_duration)
    beat_grid_ticks = np.arange(0, duration + 1, beat_duration)

    if len(axis) > 2:
        raise ValueError("Illegal axis: %s" % axis)

    axes.set_xticks(measure_grid_ticks)
    axes.set_xticks(beat_grid_ticks, minor=True)
    axes.set_yticks(measure_grid_ticks)
    axes.set_yticks(beat_grid_ticks, minor=True)

    axes.set_axisbelow(True)
    axes.grid(which='minor', alpha=0.2, axis=axis)
    axes.grid(which='major', alpha=0.5, axis=axis)
Exemplo n.º 29
0
    def style_primary_axis(
        self,
        ax: plt.Axes,
        data_index: Optional[List[int]] = None,
        tick_labels: Optional[List[str]] = None,
    ):
        """Apply styling to a primary axis.

        Parameters
        ----------
        ax : plt.Axes
            A matplolib axis
        """
        ax.yaxis.set_label_position("right")
        ax.grid(axis="both", visible=True, zorder=0)
        if (all([data_index, tick_labels]) and isinstance(data_index, list)
                and isinstance(tick_labels, list)):
            ax.xaxis.set_major_formatter(
                ticker.FuncFormatter(lambda value, _: tick_labels[int(value)]
                                     if int(value) in data_index else ""))
            ax.xaxis.set_major_locator(ticker.MaxNLocator(6, integer=True))
        ax.tick_params(axis="x", labelrotation=self.xticks_rotation)
def plot_lt(df: pd.DataFrame, ax: plt.Axes, title: str) -> None:
    def outlier_throughput(g: pd.DataFrame) -> float:
        cutoff = 0.5 * g['throughput'].max()
        return g[g['throughput'] >= cutoff]['throughput'].mean() / 100000

    def outlier_throughput_std(g: pd.DataFrame) -> float:
        cutoff = 0.5 * g['throughput'].max()
        return g[g['throughput'] >= cutoff]['throughput'].std() / 100000

    grouped = df.groupby([
        'num_replicas',
        'num_proxy_leaders',
        'num_acceptor_groups',
        'num_acceptors_per_group',
        'workload.write_size_mean',
        'leader_options.flush_phase2as_every_n'
    ])
    for (name, group) in grouped:
        print(f'## {name}')
        print(group[['throughput', 'latency']])

        by_clients = group.groupby('num_clients')
        throughput = by_clients['throughput'].agg(np.mean).sort_index() / 1000
        throughput_std = by_clients['throughput'].agg(np.std).sort_index() / 1000
        latency = by_clients['latency'].agg(np.mean).sort_index()
        line = ax.plot(throughput, latency, '-', marker=next(MARKERS),
                       label=name, linewidth=2)[0]
        ax.fill_betweenx(latency,
                         throughput - throughput_std,
                         throughput + throughput_std,
                         color = line.get_color(),
                         alpha=0.25)

    ax.set_title(title)
    ax.set_xlabel('Throughput (100,000 commands per second)')
    ax.set_ylabel('Latency\n(milliseconds)')
    ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
    ax.grid(b=True)
Exemplo n.º 31
0
def plot_word_frequency_vs_rank(text,
                                axes: plt.Axes = None,
                                label=None,
                                title=None,
                                annotate=True,
                                as_probability=False):

    vs_rank = word_frequency_vs_rank
    rank, frequency = vs_rank(text, as_probability=as_probability)

    new_figure_created = False
    if axes is None:
        new_figure_created = True
        figure = plt.figure(figsize=(12, 8))
        axes = figure.gca()

    axes.scatter(rank, frequency, label=label)
    axes.set_yscale('log')
    axes.set_xscale('log')
    axes.grid()

    if annotate:
        axes.set_xlabel('Word rank')
        if as_probability:
            y_label = 'Probability of occurrence'
        else:
            y_label = 'Frequency of occurrence'

        axes.set_ylabel(y_label)

    if title is not None:
        axes.set_title(title)

    if new_figure_created:
        format_figure(figure)

    return axes
Exemplo n.º 32
0
def set_axes(xvalues: list,
             ax: plt.Axes = None,
             title: str = '',
             xlabel: str = '',
             ylabel: str = '',
             percentage=False,
             hidegrid=False):

    if ax is None:
        ax = plt.gca()

    if hidegrid:
        ax.grid(False)

    ax.set_title(title)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    if percentage:
        ax.set_ylim(0.0, 1.0)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    ax.set_xticklabels(xvalues, fontsize='small', ha='center', rotation=90)

    return ax