Ejemplo n.º 1
0
    def _sub_plot_multiple_twin(self, axis:plt.axis, columns:tuple):
        '''
        Create a sub-plot for the given columns. 
        Create a twin x-axis with new y scale for the second column. 

        Parameters
        ----------
        ax : plt.axis
            figure axis
        column : tuple
            2 column names
        twin : bool
            
        '''
        # PLot first column
        axis.plot(self.m_data_df[columns[0]], label=columns[0], color='tab:blue',linestyle='-',linewidth=0.1)
        axis.tick_params(axis='y', labelcolor='tab:blue')
        axis.set_xlabel('Rollouts')
        axis.set_ylabel(columns[0])
        axis.set_title(columns[0] + ' ~ ' + columns[1])

        # PLot second column 
        ax = axis.twinx()
        ax.plot(self.m_data_df[columns[1]], label=columns[1], color='tab:red',linestyle='-',linewidth=1)
        ax.set_ylabel(columns[1])
        ax.tick_params(axis='y', labelcolor='tab:red')
Ejemplo n.º 2
0
def plot(ax: plt.axis, R, data, title=""):
    """
    Plot function for subtask 1
    """
    ax.set_aspect('equal')
    arrowed_spines(ax)
    ax.set_title(title)
Ejemplo n.º 3
0
def plot(ax: plt.axis, x, y, u, v, trajectory, pause=0.2, title=""):
    """
    Plot function for subtask 1
    """
    ax.set_aspect('equal')
    arrowed_spines(ax)
    ax.set_xlim([min(x) * 1, max(x) * 1])
    ax.set_ylim([min(y) * 1, max(y) * 1])
    ax.set_title(title)
    ax.streamplot(x, y, u, v)
    ax.plot(trajectory[:, 0], trajectory[:, 1])
Ejemplo n.º 4
0
    def add_descriptions(
        self,
        ax: plt.axis,
        experiment: Union[str, None] = 'Belle II',
        luminosity: Union[str, int, float, None] = '',
        additional_info: Union[str, None] = None,
        small_title: Union[bool, None] = False,
        preliminary: Union[bool, None] = True,
        title_indent: Union[int, None] = 0,
        exp_nr: Union[int, None] = None,
        proc_nr: Union[int, None] = None,
        buck_nr: Union[int, None] = None,
    ):

        # generate luminosity text
        if type(luminosity) == int or type(luminosity) == float:
            luminosity = r"$\int \mathcal{L} \,\mathrm{d}t=" + "{:.0f}".format(
                np.round(luminosity, 0)) + "\,\mathrm{pb}^{-1}$"

        # add some additional dataset meta data
        if exp_nr:
            luminosity += f"\nExp. {exp_nr}"
            if proc_nr:
                luminosity += f", Proc {proc_nr}"
            if buck_nr:
                luminosity += f", Buck. {buck_nr}"

        if small_title:
            ax.set_title('{}'.format(' ' * title_indent) + experiment +
                         '\n{}'.format(' ' * title_indent) +
                         '{}'.format('(Preliminary)' if preliminary else ''),
                         loc="left",
                         fontdict={
                             'style': 'normal',
                             'weight': 'bold'
                         })
            ax.set_title(luminosity, loc="right")
        else:
            ax.set_title('{}'.format(' ' * title_indent) + experiment,
                         loc="left",
                         fontdict={
                             'size': 16,
                             'style': 'normal',
                             'weight': 'bold'
                         })
            ax.set_title('{}'.format('(Preliminary) ' if preliminary else '') +
                         luminosity,
                         loc="right")

        ax.annotate(additional_info, (0.02, 0.98),
                    xytext=(4, -4),
                    xycoords='axes fraction',
                    textcoords='offset points',
                    fontweight='bold',
                    ha='left',
                    va='top')
Ejemplo n.º 5
0
    def _sub_plot_single_from_array(self, ax:plt.axis, data:np.array, x_title:str, title:str, legend=None):
        '''
        Create a sub-plot for a given column. 

        Parameters
        ----------
        ax : plt.axis
            figure axis
        
        data : np.array
            data to plot
        '''
        if legend == None:
            ax.plot(data,linestyle='-',linewidth=1)
        else:
            ax.plot(data,linestyle='-',linewidth=1,label=legend)
        ax.set_xlabel(x_title)
        ax.set_title(title) 
Ejemplo n.º 6
0
    def _sub_plot_multiple(self, axis:plt.axis, columns:tuple):
        '''
        Create a sub-plot for the given columns. 

        Parameters
        ----------
        ax : plt.axis
            figure axis
        columns : tuple
            column names
        '''
        title = ''
        for col in columns:
            axis.plot(self.m_data_df[col], label=col,linestyle='-',linewidth=0.1)
            title += col + ', '
        axis.set_title(title) 
        axis.set_xlabel('Rollouts')
        axis.legend()
Ejemplo n.º 7
0
def add_descriptions_to_plot(
    ax: plt.axis,
    experiment: Union[str, None] = None,
    luminosity: Union[str, None] = None,
    additional_info: Union[str, None] = None,
):
    ax.set_title(experiment,
                 loc="left",
                 fontdict={
                     'size': 16,
                     'style': 'normal',
                     'weight': 'bold'
                 })
    ax.set_title(luminosity, loc="right")
    ax.annotate(additional_info, (0.02, 0.98),
                xytext=(4, -4),
                xycoords='axes fraction',
                textcoords='offset points',
                fontweight='bold',
                ha='left',
                va='top')
Ejemplo n.º 8
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) 
Ejemplo n.º 9
0
    def mpl_plot(self,
                 ax: plt.axis = None,
                 temp_unit: str = "GK",
                 **kwargs) -> plt.axis:
        """

        Parameters
        ----------
        ax : mpl.Axis
            mpl Axis to plot onto, if none provided get current axis is used.
        temp_unit : str {"Gk", "KeV"}
            Tempreture units for x axis.
        kwargs : key word args for mpl.plot
        """
        ax = ax or plt.gca()
        ax.set_title("Reaction Rate")
        ax.set_ylabel(r"Rate ($cm^3\;mol^{-1}\;sec^{-1}$)")

        if temp_unit is "GK":
            ax.set_xlabel("Temperature ($GK$)")

        return ax
Ejemplo n.º 10
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}'
            )
Ejemplo n.º 11
0
def plot_word_vectors(
    transformed_word_embeddings: np.ndarray,
    words: list,
    title: str,
    x_label: str,
    y_label: str,
    word_colors: np.ndarray = None,
    ax: plt.axis = None,
    show_plot: bool = True,
    interactive: bool = False,
    continuous_word_colors: bool = False,
) -> None:
    """
    Plots word vectors in transformed 2D space.

    Parameters
    ----------
    transformed_word_embeddings : np.ndarray
        Word embeddings transformed into 2D space.
    words : list
        List of words to plot
    title : str,
        Title to use for the plot.
    x_label : str,
        Label to use for the x-axis.
    y_label : str
        Label to use for the y-axis
    word_colors : np.ndarray, optional
        Numpy array consisting of unique labels for each word (i.e. cluster labels),
        (defaults to None).
    ax : plt.axis
        Matplotlib axis (defaults to None)
    show_plot : bool
        Whether or not to call plt.show() (defaults to True)
    interactive : bool
        Whether or not to make the visualization interactive
        using Plotly (defaults to False).
    continuous_word_colors : bool
        Whether or not to make the word color continuous (defaults to False).
    """
    if interactive:

        # Plot interactive plot
        fig = px.scatter(
            x=transformed_word_embeddings[:, 0],
            y=transformed_word_embeddings[:, 1],
            title=title,
            labels={
                "x": x_label,
                "y": y_label
            },
            color=[
                cluster_label if continuous_word_colors else str(cluster_label)
                for cluster_label in word_colors
            ] if word_colors is not None else None,
            hover_data={"word": words},
        )
        fig.show()
    else:
        if ax is None:
            _, ax = plt.subplots()
        ax.scatter(
            transformed_word_embeddings[:, 0],
            transformed_word_embeddings[:, 1],
            c=word_colors,
        )
        ax.set_title(title)
        ax.set_xlabel(x_label)
        ax.set_ylabel(y_label)
        if show_plot:
            plt.show()