Пример #1
0
    def _sub_plot_single(self, ax:plt.axis, column:str, legend=None):
        '''
        Create a sub-plot for a given column. 

        Parameters
        ----------
        ax : :plt.axis
            figure axis
        
        column : str
            column name
        '''
        if legend == None:
            ax.plot(self.m_data_df[column],linestyle='-',linewidth=0.1)
        else:
            ax.plot(self.m_data_df[column],linestyle='-',linewidth=0.1,label=legend)
        
        ax.set_xlabel('Rollouts')
        if False and column == 'Num_timesteps':
            column += ' (approx. run time: {0:.2f} hours)'.format(self.estimated_run_time())
        ax.set_title(column) 
Пример #2
0
def plot_speeds(
    body_speed,
    start: int = 0,
    end: int = -1,
    is_moving: np.ndarray = None,
    ax: plt.axis = None,
    show: bool = True,
    **other_speeds,
):
    """
        Just plot some speeds for debugging stuff
    """
    if ax is None:
        f, ax = plt.subplots(figsize=(14, 8))

    ax.plot(body_speed[start:end], label="body", color="salmon")
    for name, speed in other_speeds.items():
        ax.plot(speed[start:end], label=name)

    if is_moving is not None:
        ax.plot(is_moving, lw=4, color="k")

    ax.legend()
    ax.set(xlabel="time (frames)", ylabel="speed (cm/s)")
    if show:
        plt.show()
Пример #3
0
def plot_tensorboard(
        ax: plt.axis,
        tag: str,
        tb_data: Iterable[Iterable[Iterable[Path]]],
        names: Iterable[str],
        percentiles: Optional[Tuple[float, float]] = (0.25, 0.75),
        alpha: float = 0.1,
        use_data_cache: bool = False,
        data_cache_fname: str = ".rlgear_data.p",
        show_same_num_timesteps: bool = False,
        max_step: Optional[int] = None) -> None:

    if use_data_cache:
        with open(data_cache_fname, 'rb') as f:
            out_dfs = pickle.load(f)
    else:
        out_dfs = []
        for grouped_files in tb_data:
            out_dfs.append(tb_to_df(
                grouped_files,
                tag, max_step=max_step, only_complete_data=True))

        with open(data_cache_fname, 'wb') as f:
            pickle.dump(out_dfs, f)

    if show_same_num_timesteps:
        shorten_dfs(out_dfs)

    for name, df in zip(names, out_dfs):
        ax.plot(df.index, df.mean(axis=1), label=name)

        if percentiles:
            plot_percentiles(ax, df, percentiles, alpha)

    # https://stackoverflow.com/a/25750438
    ax.xaxis.set_major_formatter(mtick.FormatStrFormatter('%.1e'))
    ax.set_xlabel('Training Step')
    plt.tight_layout()
Пример #4
0
def plot_balls_errors(
    x: np.ndarray,
    y: np.ndarray,
    yerr: np.ndarray,
    ax: plt.axis,
    s: int = 150,
    colors: Union[list, str] = None,
):
    """
        Given a serires of XY values and Y errors it plots a scatter for each XY point and a line
        to mark each Y error
    """
    if colors is None:
        colors = [blue_grey] * len(x)
    elif isinstance(colors, str):
        colors = [colors] * len(x)

    ax.scatter(x, y, s=s, c=colors, zorder=100, lw=1, ec=[0.3, 0.3, 0.3])
    ax.plot(x, y, lw=3, color=colors[0], zorder=-1)

    if yerr is not None:
        for n in range(len(x)):
            ax.plot(
                [x[n], x[n]],
                [y[n] - yerr[n], y[n] + yerr[n]],
                lw=4,
                color=[0.3, 0.3, 0.3],
                zorder=96,
                solid_capstyle="round",
            )
            ax.plot(
                [x[n], x[n]],
                [y[n] - yerr[n], y[n] + yerr[n]],
                lw=2,
                color=colors[n],
                zorder=98,
                solid_capstyle="round",
            )
Пример #5
0
def plot_bouts_2d(
    tracking: Union[dict, pd.DataFrame],
    bouts: pd.DataFrame,
    ax: plt.axis,
    direction: bool = None,
    zorder: int = 100,
    lw: float = 2,
    c: str = None,
    unit: pd.Series = None,
    **kwargs,
):
    # select bouts by direction
    if direction is not None:
        bouts = bouts.loc[bouts.direction == direction]

    # plot
    for i, bout in bouts.iterrows():
        # prepare data
        x = tracking["x"][bout.start_frame:bout.end_frame]
        y = tracking["y"][bout.start_frame:bout.end_frame]

        if c is None:
            color = colors.bout_direction_colors[bout.direction]
        else:
            color = c

        # plot tracking
        ax.plot(x, y, color=color, zorder=zorder, lw=lw, **kwargs)

        if unit is None:
            # mark start and end
            ax.scatter(
                x[0],
                y[0],
                color="white",
                lw=1,
                ec=color,
                s=25,
                zorder=101,
                **kwargs,
            )
            ax.scatter(
                x[-1],
                y[-1],
                color=[0.2, 0.2, 0.2],
                lw=1,
                ec=color,
                s=25,
                zorder=101,
                **kwargs,
            )
        else:
            # mark unit spikes
            spikes = unit.spikes[(unit.spikes > bout.start_frame)
                                 & (unit.spikes < bout.end_frame)]
            ax.scatter(
                tracking["x"][spikes],
                tracking["y"][spikes],
                s=15,
                zorder=101,
                color=unit.color,
            )
Пример #6
0
    def _plot_summary_on_axis(
        self,
        ax: plt.axis,
        label_y_axis: bool,
        use_title: bool,
    ):
        """used to plot summary on multi-axis figure, or in standalone figure"""

        # axis
        if use_title:
            ax.set_title('Average', fontsize=configs.Figs.title_font_size)
            y_axis_label = self.y_axis_label
        else:
            y_axis_label = f'Average {self.y_axis_label}'
        ax.spines['right'].set_visible(False)
        ax.spines['top'].set_visible(False)
        ax.spines['top'].set_visible(False)
        ax.set_ylim(self.y_lims)

        # x-axis
        ax.set_xticks([self.last_step])
        ax.set_xticklabels([shorten_tick_label(self.last_step)],
                           fontsize=configs.Figs.tick_font_size)
        ax.set_xlabel(self.x_axis_label, fontsize=configs.Figs.ax_font_size)

        # y axis
        if label_y_axis:
            ax.set_ylabel(y_axis_label, fontsize=configs.Figs.ax_font_size)
            ax.set_yticks(self.y_ticks)
            ax.set_yticklabels(self.y_ticks,
                               fontsize=configs.Figs.tick_font_size)
        else:
            ax.set_ylabel('', fontsize=configs.Figs.ax_font_size)
            ax.set_yticks([])
            ax.set_yticklabels([], fontsize=configs.Figs.tick_font_size)

        # collect curves for each replication across all paradigms
        gn2rep2curves_by_pd = defaultdict(dict)
        for pd in self.pds:
            for gn, rep2curve in pd.group_name2rep2curve.items():
                for rep, curve in rep2curve.items():
                    # this curve is performance collapsed across template and for a unique rep and paradigm
                    gn2rep2curves_by_pd[gn].setdefault(rep, []).append(curve)

        # plot
        for gn, rep2curves_by_pd in gn2rep2curves_by_pd.items():
            # average across paradigms
            rep2curve_avg_across_pds = {
                rep: np.array(curves_by_pd).mean(axis=0)
                for rep, curves_by_pd in rep2curves_by_pd.items()
            }
            curves = np.array([
                rep2curve_avg_across_pds[rep]
                for rep in rep2curve_avg_across_pds
            ])  # one for each rep

            color = f'C{self.pds[0].group_names.index(gn)}'
            x = np.arange(0, self.last_step + self.step_size, self.step_size)

            # plot averages for BabyBERTa
            y = np.array(curves).mean(axis=0)
            ax.plot(x, y, linewidth=self.line_width, color=color)

            # plot average for RoBERTa-base
            y_roberta_base = np.repeat(
                np.mean(list(self.paradigm2roberta_base_accuracy.values())),
                len(x))
            ax.plot(x,
                    y_roberta_base,
                    linewidth=self.line_width,
                    **self.ax_kwargs_roberta_base)

            # plot average for frequency baseline
            y_baseline = np.repeat(
                np.mean(list(self.paradigm2baseline_accuracy.values())),
                len(x))
            ax.plot(x,
                    y_baseline,
                    linewidth=self.line_width,
                    **self.ax_kwargs_baseline)

            # plot the margin of error (shaded region)
            n = len(curves)
            h = sem(curves, axis=0) * t.ppf(
                (1 + self.confidence) / 2, n - 1)  # margin of error
            ax.fill_between(x, y + h, y - h, alpha=0.2, color=color)

            # printout
            if use_title:  # to prevent printing summary twice
                print(f'{gn} avg acc at step {self.last_step} = {y[-1]:.3f}')

        if use_title:
            y_roberta_base = np.mean(
                list(self.paradigm2roberta_base_accuracy.values()))
            print(
                f'roberta-base Liu2019 avg acc at step {self.last_step} = {y_roberta_base:.3f}'
            )
Пример #7
0
def plot_cluster_metric_scores(
    metric_scores: list,
    hyperparameters: list,
    best_score_idx: int,
    metric_name: str,
    scatter: bool = True,
    set_xticks: bool = True,
    set_xtickslabels: bool = True,
    xtickslabels_rotation: int = 90,
    ax: plt.axis = None,
    xlabel: str = "Hyperparameters",
    xrange: range = None,
    show_plot: bool = True,
) -> None:
    """
    Plots internal cluster validation metric scores

    Parameters
    ----------
    metric_scores : list
        List of scores computed using metric
    hyperparameters : list
        List of hyperparameters used to compute the scores
    best_score_idx : int
        Best score index
    metric_name : str
        Name of the internal cluster validation metric
    scatter : bool
        Whether or not to scatter points (defaults to True)
    set_xticks : bool
        Whether or not to set the ticks on the x-axis
    set_xtickslabels : bool
        Whether or not to set the labels on the x-axis
    xtickslabels_rotation : int
        Sets the xticks labels rotation (defaults to 90), set_xtickslabels
        must be set to True to have an effect.
    ax : plt.axis
        Matplotlib axis (defaults to None)
    xlabel : str
        X-axis label (defaults to "Hyperparameters")
    xrange : range
        Range to use for the x-axis (default starts from 0 to)
    show_plot : bool
        Whether or not to call plt.show() (defaults to True)
    """
    if ax is None:
        _, ax = plt.subplots()
    if xrange is None:
        xrange = range(len(hyperparameters))
    ax.plot(xrange, metric_scores)
    if scatter:
        ax.scatter(xrange, metric_scores)
    ax.scatter(xrange[best_score_idx],
               metric_scores[best_score_idx],
               c="r",
               s=72,
               zorder=10)
    if set_xticks:
        ax.set_xticks(xrange)
    if set_xtickslabels:
        ax.set_xticklabels(hyperparameters,
                           rotation=xtickslabels_rotation,
                           ha="center")
    ax.set_xlabel(xlabel)
    ax.set_ylabel(f"{metric_name} score")
    if show_plot:
        plt.tight_layout()
        plt.show()
Пример #8
0
 def drawPointToPoint(self, target_axis: plt.axis, init_axis: plt.axis, px1: np.array, px2: np.array, **kwargs):
     target_axis.plot([px1[0]],[px1[1]], 'rx', markersize=10)
     con = ConnectionPatch(xyA=px1, xyB=px2, coordsA="data", coordsB="data",
                     axesA=target_axis, axesB=init_axis, **kwargs)
     target_axis.add_artist(con)