示例#1
0
def plot_data_distribution(plot: plt,
                           data,
                           feature_extractor,
                           num_classes=3,
                           small_points=False):
    features = feature_extractor.predict(data)
    labels = np.concatenate([y for x, y in data], axis=0)
    if small_points:
        marker_data = 'x'
        marker_colour = ['k', 'k', 'k', 'k', 'k', 'k', 'k', 'k', 'k', 'k']
        markersize = 3
        alpha = 0.3
    else:
        marker_data = 'x'
        marker_colour = [
            'tab:blue', 'tab:orange', 'tab:green', 'tab:red', 'tab:purple',
            'tab:brown', 'tab:pink', 'tab:gray', 'tab:olive', 'tab:cyan'
        ]
        markersize = 3
        alpha = 0.7

    for class_id in range(num_classes):
        x_class = features[labels == class_id]
        plot.plot(x_class[:, 1],
                  x_class[:, 0],
                  marker_data,
                  color=marker_colour[class_id],
                  ms=markersize,
                  alpha=alpha)
示例#2
0
    def save_chart_image(self, chart_data_dict: dict, mpl_plt: plt) -> Path:
        """
        Save image in db, and return path to file in temp storage.

        :param chart_data_dict: dict
        :param mpl_plt: matplotlib.pyplot
        :return: Path
        """
        # Get image data:
        image = BytesIO()
        mpl_plt.savefig(image, format='png',
                        dpi=300)  # dpi - 120 comes to 1920*1080, 80 - 1280*720
        image.seek(0)  # Return pointer to start of binary stream.

        # Save image in db
        with self.session_scope() as session:
            chart = session.query(
                self.Chart).filter_by(id=chart_data_dict['chart_id']).one()
            chart.image = image.read()

            session.commit()
        image.seek(0)

        # Save file to temp and pass back Path
        temp_image_path = Path(
            DataFolder.generate_rel_path(DataFolder.TEMP_DIR.value),
            f"{chart_data_dict['chart_name']}.png")
        temp_image_path.write_bytes(image.read())
        return temp_image_path
 def plotSignal(self, ax: plt, n: int, xpos: int, ypos: float, sig: str, sig_type: str) -> None:
     if sig_type == "NS1":
         color = "deepskyblue"
         shift = 3
     elif sig_type == "NS2":
         color = "deepskyblue"
         shift = 4
     elif sig_type == "NS3":
         color = "deepskyblue"
         shift = 4
     elif sig_type == "CON1":
         color = "goldenrod"
         shift = 3
     elif sig_type == "CON2":
         color = "goldenrod"
         shift = 4
     elif sig_type == "CON3":
         color = "goldenrod"
         shift = 4
     elif sig_type == "RAP":
         color = "violet"
         shift = 2
     else:
         raise ValueError("Wrong sig_type:" + sig_type)
     color = "gray"
     ax.plot(self.xMl[n - shift: n + 1], self.yMl[n - shift: n + 1], color=color, linewidth=1)
     # ax.text(xpos - 30, ypos - 0.004, sig, fontsize=12, color=color, fontweight="bold")
     ax.text(xpos - 120, ypos - 0.03, sig_type, fontsize=6, color=color, fontweight="bold")
 def closeShortPosition(self, ax: plt, n: int, xpos: int, ypos: float,
                        sig_type: int) -> None:
     if self.plot is True:
         if sig_type == 0:
             marker = "*k"
         elif sig_type == 1:
             marker = "xk"
         else:
             raise ValueError("Wrong sig_type:" + sig_type)
         ax.plot([
             xpos,
         ], [
             ypos,
         ], marker, markersize=5)
         if ypos != self.short_start_price:
             color = "red" if ypos < self.short_start_price else "blue"
             x = self.xMl[self.short_start_pos]
             ax.plot([x, x + 0.001], [
                 self.short_start_price, 2 * self.short_start_price - ypos
             ],
                     color=color,
                     linewidth=1)
     # print("close at", "\tn:", n, "\txpos:", xpos, "\typos:", ypos, "\tslope:",self.slope_list[n], "\tnadir:", self.short_nadir_price)
     self.pnl += self.short_start_price - ypos
     self.update_stat_df(pos_type="short", close_price=ypos)
     self.initDailyParam(pos_type="short")
示例#5
0
    def save_chart_image(self, chart_data_dict: dict, mpl_plt: plt) -> Path:
        """
        Save image in db, and return path to file in temp storage.

        :param chart_data_dict: dict
        :param mpl_plt: matplotlib.pyplot
        :return: Path
        """
        # Get image data:
        image = BytesIO()
        mpl_plt.savefig(image, format='png',
                        dpi=300)  # dpi - 120 comes to 1920*1080, 80 - 1280*720
        image.seek(0)  # Return pointer to start of binary stream.

        # Save image in db
        with self._connection() as conn:
            cursor = conn.cursor()
            cursor.execute(
                """
                UPDATE chart
                SET image=?
                WHERE id=?;
                """, (image.read(), chart_data_dict['chart_id']))
            image.seek(0)
            conn.commit()
        conn.close()

        # Save file to temp and pass back Path
        temp_image_path = Path(
            DataFolder.generate_rel_path(DataFolder.TEMP_DIR.value),
            f"{chart_data_dict['chart_name']}.png")
        temp_image_path.write_bytes(image.read())
        return temp_image_path
示例#6
0
def capture_figure(metadata: ReportFigure, figure: pyplot):
    fig_rel_path = os.path.join('figures', f'{metadata.title}.png')
    fig_path = os.path.join(report_directory, fig_rel_path)
    
    figure.savefig(fig_path)
    metadata.img_path = fig_rel_path
    
    report.figures.append(metadata)
示例#7
0
文件: ui_api.py 项目: jvitku/torchsim
    def matplot(self, plot: plt, win: str):
        """Draw matplot chart"""

        buffer = io.StringIO()
        plot.savefig(buffer, format='svg')
        buffer.seek(0)
        svg = buffer.read()
        buffer.close()

        return self.svg(svg=svg, win=win)
示例#8
0
 def plotSignal(self, ax: plt, n: int, xpos: int, ypos: float, sig: str, sig_type: str) -> None:
     if sig_type == "CON1":
         shift = 3
     elif sig_type == "CON3":
         shift = 4
     elif sig_type == "RAP":
         shift = 2
     else:
         raise ValueError("Wrong sig_type:" + sig_type)
     ax.plot(self.xMl[n - shift: n + 1], self.yMl[n - shift: n + 1], color="gray",linewidth=1)
     ax.text(xpos - 120, ypos - 0.03, sig_type, fontsize=6, color="gray", fontweight="bold")
示例#9
0
 def closePosition(self, close_type: str, ax: plt, n: int, xpos: int, ypos: float, marker: str):
     start_price = self.long_start_price if close_type == "long" else self.short_start_price
     pos = self.long_start_pos if close_type == "long" else self.short_start_pos
     if self.plot is True:
         ax.plot([xpos, ], [ypos, ], marker, markersize=5)
         if ypos != start_price:
             color = "red" if ypos > start_price else "blue"
             x = self.xMl[pos]
             ax.plot([x, x + 0.0001], [start_price, ypos], color=color, linewidth =1)
     self.pnl += ypos - start_price
     self.update_stat_df(pos_type=close_type, close_price=ypos)
     self.initDailyParam(pos_type=close_type)
示例#10
0
 def plotSignal(self, ax: plt, n: int, xpos: int, ypos: float, sig: str,
                sig_type: str) -> None:
     shift = 3 if sig_type == "CON1" else 2
     ax.plot(self.xMl[n - shift:n + 1],
             self.yMl[n - shift:n + 1],
             color="gray",
             linewidth=1)
     ax.text(xpos - 120,
             ypos - 0.03,
             sig_type,
             fontsize=6,
             color="gray",
             fontweight="bold")
示例#11
0
    def __init__(
        self,
        chart: MatPlotLibPlot,
        width: Optional[Decimal] = None,
        height: Optional[Decimal] = None,
    ):
        byte_buffer = io.BytesIO()
        chart.savefig(byte_buffer, format="png")
        byte_buffer.seek(0)

        super(Chart, self).__init__(image=PILImage.open(byte_buffer),
                                    width=width,
                                    height=height)
def plot(masking: "Masking", mplot: plt) -> plt:
    """
    Plot layer wise density bar plot.

    :param masking: Masking instance
    :type masking: sparselearning.core.Masking
    :param mplot: matplotlib object
    :type mplot: pyplot
    :return: matplotlib plot
    :rtype: pyplot
    """

    density_ll = _get_density_ll(masking)
    bin_ll = np.arange(len(density_ll)) + 1
    width = 0.8

    mplot.clf()
    mplot.bar(bin_ll, density_ll, width, color="b")

    # Gets too crowded when including layer names
    # layer_name_ll = list(masking.masks.keys())
    # plt.xticks(bin_ll, layer_name_ll)

    mplot.ylabel("Density")
    mplot.xlabel("Layer Number")

    return mplot
示例#13
0
    def set_plt_rc(self, plot: plt) -> plt:
        """Takes a plot and applies a style as rc params"""

        ft_background = "#FFF1E5"
        ft_democrat_blue = "#0F56B5"
        ft_republican_red = "#EF4647"
        ft_pink = "#E95D8C"
        ft_darkred = "#7D062E"
        ft_darkblue = "#065296"
        ft_blue = "#2591CE"
        ft_lightblue = "#72D9E7"
        ft_greenish = "#A2BC5D"
        ft_maybe_grey = "#716962"
        ft_golden = "#B89E17"

        plot.rcParams['figure.facecolor'] = ft_background
        plot.rcParams['axes.facecolor'] = ft_background
        plot.rcParams['text.color'] = ft_maybe_grey
        plot.rcParams['xtick.color'] = ft_maybe_grey
        plot.rcParams['ytick.color'] = ft_maybe_grey
        plot.rcParams['axes.labelcolor'] = ft_maybe_grey

        #plot.rcParams["axes.grid.axis"] ="y"
        #plot.rcParams["axes.grid"] = True
        plot.rcParams['axes.spines.left'] = True
        plot.rcParams['axes.spines.right'] = False
        plot.rcParams['axes.spines.top'] = False
        plot.rcParams['axes.spines.bottom'] = True
        #plot.rcParams['figure.figsize'] = (20,12)

        #plot.rcParams['lines.linewidth'] = self.line_width

        #plot.rcParams['axes.titlesize'] = self.large_font
        #plot.rcParams['font.size'] = self.small_font
        #plot.rcParams['xtick.labelsize'] = self.small_font
        #plot.rcParams['ytick.labelsize'] = self.small_font
        #plot.rcParams['axes.labelsize']  = self.small_font
        #plot.rcParams['ytick.labelsize'] = self.small_font
        plot.rcParams['xtick.major.size'] = 10
        plot.rcParams['xtick.major.pad'] = 10
        plot.rcParams['ytick.major.size'] = 0
        plot.rcParams['ytick.major.pad'] = 10
        plot.rcParams['figure.constrained_layout.use'] = True

        plot.rc('axes',
                prop_cycle=(cycler.cycler('color', [
                    ft_darkblue, ft_blue, ft_lightblue, ft_pink, ft_darkred,
                    ft_greenish
                ])))
        return plot
示例#14
0
    def add_scatter_and_annotate(self,
                                 fig: plt,
                                 x_all: np.array,
                                 y_all: np.array,
                                 colour: str,
                                 idxs: np.array,
                                 annotate=False):
        x = x_all[idxs]
        y = y_all[idxs]
        ax = fig.scatter(x, y, c=colour, alpha=self.opacity, s=20)

        # Check if we want to annotate any of these with their gene IDs

        if self.values_to_label is not None:
            texts = []
            labels = self.df[self.label_column].values[idxs]
            for i, name in enumerate(labels):
                if name in self.values_to_label:
                    lbl_bg = self.values_colours.get(name)
                    color = self.text_colours.get(name)
                    texts.append(
                        fig.text(x[i],
                                 y[i],
                                 name,
                                 color=color,
                                 fontsize=self.label_font_size,
                                 bbox=dict(fc=lbl_bg, alpha=1.0)))
            adjust_text(texts, force_text=2.0)
        # Check if the user wants these labeled
        if self.label_big_sig and annotate:
            # If they do have a limit on the number of ones we show (i.e. we don't want 10000 gene names...)
            max_values = -1 * self.max_labels
            if len(y) < self.max_labels:
                max_values = -1 * (len(y) - 1)
            most_sig_idxs = np.argpartition(y, max_values)[max_values:]
            labels = self.df[self.label_column].values[idxs][most_sig_idxs]
            x = x[most_sig_idxs]
            y = y[most_sig_idxs]
            # We only label the ones with the max log fc
            for i, name in enumerate(labels):
                fig.annotate(name, (x[i], y[i]),
                             xytext=(0, 10),
                             textcoords='offset points',
                             ha='center',
                             va='bottom',
                             bbox=dict(boxstyle='round,pad=0.5',
                                       fc='white',
                                       alpha=0.2))
        return ax
def export_plt(plot_obj: plt, filename: str, filepath: str) -> str:
    """
    Exports single frames from pyplot object.
    :param plot_obj: pyplot object to store frame from.
    :param filename: Desired file name of the *.png.
    :param filepath: Desired file path to store the frame.
    :return: Full storage path of the new *.png file (with extension)
    """
    sub_folder = filepath  # os.path.join(ICAP_DIR, filepath)
    if not os.path.exists(
            sub_folder):  # Creates folder if folder does not exist
        os.makedirs(sub_folder)
    full_path = os.path.join(sub_folder, filename + '.png')
    plot_obj.savefig(full_path)
    return full_path
def get_plot(plot_obj: plt, data: List[IContainer]) -> (Figure, Subplot):
    """Returns plt object"""
    # Data
    labeled_dict = {}
    for collection in data:
        if collection.label not in labeled_dict:
            labeled_dict[collection.label] = list()
        labeled_dict[collection.label].append(collection)
    fig, ax = plot_obj.subplots()
    # Set plot layout
    ax.title.set_text(
        "Expectation value for different noise models and molecule parameters"
    )  # Title "Eigen Energy depending on Noise Channel"
    ax.set_xlabel("Interatomic Distance [$\AA$]")  # X axis label
    ax.set_ylabel("Energy (Hartree) [$a.u.$]")  # Y axis label

    # Set plot points
    reference_key = None
    for key in labeled_dict.keys():
        reference_key = key
        x = [collection.molecule_param for collection in labeled_dict[key]]
        y = [collection.measured_value for collection in labeled_dict[key]]
        e = [collection.measured_std for collection in labeled_dict[key]]
        ax.errorbar(x, y, yerr=e, linestyle='None', marker='^',
                    label=key)  # "STO-3G"

    x = [
        collection.molecule_param for collection in labeled_dict[reference_key]
    ]
    f = [collection.fci_value for collection in labeled_dict[reference_key]]
    h = [collection.hf_value for collection in labeled_dict[reference_key]]
    ax.plot(x, f, 'o', label="fci energy")
    ax.plot(x, h, 'o', label="HF energy")
    ax.legend(loc=0)
    return fig, ax
示例#17
0
    def generate(self, plot: pyplot, data: Any) -> None:
        stages = {row[0]: True for row in data}.keys()
        compilers = {row[1]: True for row in data}.keys()
        parameters = {row[2]: True for row in data}.keys()
        matplotlib.rcParams.update({'figure.autolayout': True})
        number_of_stages = len(stages)
        figure, axes_list = plot.subplots(1, number_of_stages)
        # Change the height to be three fourths that of the original height as
        # it becomes very narrow otherwise
        figure_width, figure_height = figure.get_size_inches()
        figure.set_size_inches(figure_width, figure_height * 0.75)
        colors = [
            "#e6194B", "#3cb44b", "#4363d8", "#f58231", "#469990", "#800000",
            "#9A6324", "#000075"
        ]

        for i, stage in enumerate(stages):
            axes = axes_list[i]
            for j, parameter in enumerate(parameters):
                for k, compiler in enumerate(compilers):
                    specific_data = [
                        [row[0], row[3], row[4]] for row in data
                        if (row[1] == compiler and row[2] == parameter
                            and row[0] == stage)
                    ]
                    yy = [row[2] for row in specific_data]
                    axes.plot(range(1,
                                    len(yy) + 1),
                              yy,
                              marker='.',
                              color=colors[j * 2 + k])

            labels = [pow(2, i) for i in range(0, len(yy))]
            axes.xaxis.set_major_locator(
                ticker.FixedLocator(range(1,
                                          len(labels) + 1)))
            axes.set_xticklabels(labels=labels, fontsize=7)
            for tick in axes.yaxis.get_major_ticks():
                tick.label.set_fontsize(7)
            axes.set_title(stage, fontsize=7)

        axes_list[0].set_ylabel("Throughput")
        figure.text(0.5, 0, "Number of Threads", ha="center")
        legend = []
        for parameter in parameters:
            for compiler in compilers:
                if parameter == "":
                    legend.append(compiler)
                else:
                    legend.append(compiler + "-" + parameter)

        figure.suptitle("", fontsize=10)
        figure.legend(legend,
                      bbox_to_anchor=(.5, 1),
                      loc="upper center",
                      fontsize=7,
                      ncol=len(legend))

        return figure
def render_bounding_box(comma_delimited_rect: str, plot: plt):
    """ Helper method to render bounding box around the detected word """
    box_coordinates = comma_delimited_rect.strip().split(',')
    x = int(box_coordinates[0].strip())
    y = int(box_coordinates[1].strip())
    width = int(box_coordinates[2].strip())
    height = int(box_coordinates[3].strip())
    bottom_left = [x, y]
    bottom_right = [x + width, y]
    top_left = [x, y + height]
    top_right = [x + width, y + height]
    points = [bottom_left, top_left, top_right, bottom_right, bottom_left]
    polygon = plt.Polygon(points,
                          fill=None,
                          edgecolor='xkcd:rusty red',
                          closed=False)
    plot.gca().add_line(polygon)
示例#19
0
def scatter_plot(plot: plt, df: HogwartsDataDescriber, course1: str,
                 course2: str):
    """
    Scatter plot for 2 courses
    :param plot: matplotlib.axes._subplots.AxesSubplot
    :param df: HogwartsDataDescriber
    :param course1: course 1 name
    :param course2: course 2 name
    :return: None
    """

    for house, color in zip(df.houses, df.colors):
        # choose course marks of students belonging to the house
        x = df[course1][df['Hogwarts House'] == house]
        y = df[course2][df['Hogwarts House'] == house]

        plot.scatter(x, y, color=color, alpha=0.5)
def plot_box(a:ndarray,b:ndarray,ax:pyplot=None,figsize=FIGSIZE,grid:bool=False,
                                facecolor=None,edgecolor=None,alpha=0.15,label=None,zorder=None): # plot the box from intervals a and b
    '''
    INPUTS

    a: 1x2 ndarray 
        x-interval
    
    b: 1x2 ndarray
        y-interval
    '''
    fig=None
    if ax is None: 
        fig,ax = pyplot.subplots(figsize=figsize)
        if grid: ax.grid()
    ax.fill_between(x=[a[0],a[1]], y1=[b[0],b[0]], y2=[b[1],b[1]],facecolor=facecolor,edgecolor=edgecolor,alpha=alpha,label=label,zorder=zorder)
    return fig,ax
示例#21
0
    def interface(self, configurator: Config, plot: plt, tiers: Dict):
        """Draws image's size plot and captures the percent user value.

        :param Config configurator:
        :param plt plot:
        :param Dict tiers:
        :return:
        """

        # Drawing plot.
        print('Drawing plot...')
        plot.draw()
        plot.pause(0.001)

        print('Results:')
        for tier, count in tiers.items():
            print('* TIER {}%: {} images.'.format(tier, count))

        # User interaction.
        executing = True
        while executing:
            selected = -1
            while not (0 <= selected <= 100):
                try:
                    selected = int(
                        input(
                            '> Enter a percent value (1 to 100) or enter 0 to finish: '
                        ))
                except ValueError:
                    print('Please, enter a NUMBER between 0 and 100')

            if selected != 0:
                result_dir = '{}{}/'.format(
                    configurator.get_work_path(),
                    FOLDER_NAME_OUTPUT_RESULT.format(selected))
                if not path.exists(result_dir):
                    self.get_result(configurator, selected)
                else:
                    print('Selected_{} already exist!'.format(selected))
            else:
                executing = False
示例#22
0
    def save_chart_image(self, chart_data_dict: dict, mpl_plt: plt) -> Path:
        """
        Save image, and return path to file in application storage.

        Save to app_data/classname/chart_data with same filename as
        chart_name and chart_data_file name.

        NB User copy stored elsewhere.

        :param chart_data_dict: dict
        :param mpl_plt: plt - matplotlib.pyplot object
        :return: Path
        """
        class_id = chart_data_dict['class_id']
        default_chart_name = chart_data_dict['chart_default_filename']
        app_data_save_pathname = self.class_data_path.joinpath(class_id,
                                                               'chart_data',
                                                               f"{default_chart_name}.png")
        Path.mkdir(app_data_save_pathname.parent, parents=True, exist_ok=True)
        # Save in app_data/class_data/class_id/chart_data with chart_default_filename

        mpl_plt.savefig(app_data_save_pathname, format='png',
                        dpi=300)  # dpi - 120 comes to 1920*1080, 80 - 1280*720
        return app_data_save_pathname
示例#23
0
def plot_choice(num: int, plot: plt, df1: pd.DataFrame) -> None:
    """
    Function to re-draw the canvas
    :param num: int of the RadioButton selection
    :param plot: plt Matplotlib.pyplot instance
    :param df1: pd.DataFrame of the TSA data
    :return: None
    """
    plot.clf()
    blue = "#327ff6"
    gray = "#bdb8b6"
    if num == 1:
        # Daily raw pax numbers
        fig, axis = plt.subplots()
        axis.plot(df1['Date'], df1['2020'], color=blue, linestyle='-', label="2020")
        axis.plot(df1['Date'], df1['2019'], color=gray, linestyle='-', label="2019")
        plot.legend()
        plot.xlabel('Date')
        plot.ylabel('Passengers')
        plot.title('TSA Passenger Daily Throughput 2019 and 2020')
        axis.get_yaxis().set_major_formatter(FuncFormatter(lambda x, p: format(int(x), ',')))

        plot_new_canvas(fig, root)

    elif num == 2:
        # Weekly raw pax numbers
        weekly_data = df1.resample('W-Mon', label='right', closed='right',
                                   on='Date').sum().reset_index().sort_values(by='Date')
        fig, axis = plt.subplots()
        axis.plot(weekly_data['Date'], weekly_data['2020'], color=blue, linestyle='-',
                  label="2020")
        axis.plot(weekly_data['Date'], weekly_data['2019'], color=gray, linestyle='-',
                  label="2019")
        axis.get_yaxis().set_major_formatter(FuncFormatter(lambda x, p: format(int(x), ',')))
        plot.xlabel('Date')
        plot.ylabel('Passengers')
        plot.legend()
        plot.ylim(0, 20E6)
        plot.title('TSA Passenger Weekly Throughput 2019 and 2020')

        plot_new_canvas(fig, root)

    elif num == 3:
        # Daily YoY percentage
        fig, axis = plt.subplots()
        axis.plot(df1['Date'], df1['yoy'], color=blue, linestyle='-', label="2020")
        plot.legend()
        plot.xlabel('Date')
        plot.ylabel('Passenger Load Factor (%)')
        plot.title('TSA Passenger Daily Throughput in 2020 as a Percentage of 2019')

        plot_new_canvas(fig, root)

    elif num == 4:
        # Weekly YoY percentage
        weekly_data = df1.resample('W-Mon', label='right', closed='right',
                                   on='Date').sum().reset_index().sort_values(by='Date')
        weekly_data['yoy'] = (weekly_data['2020']/weekly_data['2019'])*100
        fig, axis = plt.subplots()
        axis.plot(weekly_data['Date'], weekly_data['yoy'], color=blue, linestyle='-',
                  label="2020")
        plot.xlabel('Date')
        plot.ylabel('Passenger Load Factor (%)')
        plot.legend()
        plot.title('TSA Passenger Daily Throughput in 2020 as a Percentage of 2019')

        plot_new_canvas(fig, root)
示例#24
0
 def generate(self, plot: pyplot, data: Any) -> None:
     # [("gcc", "ref", 184585549)]
     series: Dict[str, List[float]] = {}
     for row in data:
         label = " ".join(row[0:2])
         if label not in series:
             series[label] = []
         series[label].append(row[2])
     values = list(series.values())
     values.sort(key=lambda x: numpy.std(x), reverse=True)
     keys = list(series.keys())
     keys.sort(key=lambda x: numpy.std(series[x]), reverse=True)
     plot.boxplot(values, showfliers=False)
     plot.gcf().axes[0].yaxis.get_major_formatter().set_scientific(False)
     plot.gcf().axes[0].set_xticklabels(keys)
     plot.title("")
     plot.ylabel(self.options.event)
     plot.xlabel("Optimizations")
    def generate(self, plot: pyplot, data: Any) -> None:
        # [('low-end-laptop', 0, 'mceliece', '6960119f', 'clang', 'ref-optimized', 'keypair', 666.1022, 999, 665165462)]
        # clang, ref-optimized: [1, 2, 3, ...]
        series: Dict[str, Dict[int, float]] = {}
        # run_index: average duration
        baseline_average_durations: Dict[int, int] = {}
        # label: run_index: iteration: duration
        sum_per_label: Dict[str, Dict[int, Dict[int, int]]] = {}

        # Find values
        for row in data:
            compiler = row[4]
            features = row[5]
            run_index = row[1]
            if compiler == "gcc" and features == "ref":
                average_duration = row[7]
                baseline_average_durations[run_index] = average_duration
            else:
                label = "{} {}".format(compiler, features)
                if label not in sum_per_label:
                    sum_per_label[label] = {}

                if run_index not in sum_per_label[label]:
                    sum_per_label[label][run_index] = {}

                iteration = row[8]
                duration = row[9]
                sum_per_label[label][run_index][iteration] = duration

        baseline_avarage_duration = sum(baseline_average_durations.values()
                                        ) / len(baseline_average_durations)
        print("Baseline runs:", baseline_average_durations)
        print("Baseline average duration:", baseline_avarage_duration)

        for label in sum_per_label.keys():
            max_length = max([
                len(value.items()) for value in sum_per_label[label].values()
            ])
            for i in range(max_length):
                relevant_items = [
                    items[i] for items in sum_per_label[label].values()
                    if i in items
                ]
                duration = sum(relevant_items) / len(relevant_items)
                percentual_duration = (duration /
                                       1e6) / baseline_avarage_duration
                if label not in series:
                    series[label] = {}
                series[label][i] = (1 / percentual_duration - 1.0)

        colors = [
            "#e6194B", "#3cb44b", "#4363d8", "#f58231", "#800000", "#9A6324",
            "#000075", "#469990"
        ]
        for i, key in enumerate(series.keys()):
            # TODO: may be wrong if there are gaps in data as it does not care about the acutal indexing
            values = series[key].values()
            plot.plot(values, label=key, color=colors[i])
        plot.title("")
        plot.ylabel("Speedup")
        plot.xlabel("Iteration")
        plot.legend(bbox_to_anchor=(0.5, 1.05),
                    loc="lower center",
                    fontsize=8,
                    ncol=len(series))
示例#26
0
def save_plot(plot_to_save: plt, filename: str):
    plot_to_save.savefig(filename)
示例#27
0
def show_plot(plot_to_show: plt):
    plot_to_show.show()
示例#28
0
def plot3D(ax: plt, sub3d: plt, X: np.ndarray, y: np.ndarray, w: np.ndarray,
           name: str) -> None:
    '''
    Visualize decision boundary and data classes in 3D
    :param ax:  matplotlib
    :param sub3d: fig.add_subplot(XXX, projection='3d')
    :param X: data
    :param y: data labels
    :param w: model parameters
    :param name: plot name identifier
    :return:
    '''
    x1 = np.array(X[1, :])  # note: X_train[0,:] is the added row of 1s (bias)
    x2 = np.array(X[2, :])
    posterior1 = LOGREG().activationFunction(w, X)
    posterior1 = np.squeeze(np.asarray(posterior1))
    markers = ['o', '+']
    groundTruthLabels = np.unique(y)
    for li in range(len(groundTruthLabels)):
        x1_sub = x1[y[:] == groundTruthLabels[li]]
        x2_sub = x2[y[:] == groundTruthLabels[li]]
        m_sub = markers[li]
        posterior1_sub = posterior1[y[:] == groundTruthLabels[li]]
        sub3d.scatter(x1_sub,
                      x2_sub,
                      posterior1_sub,
                      c=posterior1_sub,
                      vmin=0,
                      vmax=1,
                      marker=m_sub,
                      label='ground truth label = ' + str(li))
    ax.legend()
    x = np.arange(x1.min(), x1.max(), 0.1)
    pms = [[0.1, 'k:'], [0.25, 'k--'], [0.5, 'r'], [0.75, 'k-.'], [0.9, 'k-']]
    for (p, m) in pms:
        yp = (-np.log((1 / p) - 1) - w[1] * x - w[0]) / w[2]
        yp = np.squeeze(np.asarray(yp))
        z = np.ones(yp.shape) * p
        sub3d.plot(x, yp, z, m, label='p = ' + str(p))
        ax.legend()
    ax.xlabel('feature 1')
    ax.ylabel('feature 2')
    ax.title(name + '\n Posterior for class labeled 1')
 def _save_to_bytes_image(plot: plt):
     bytes_image = io.BytesIO()
     plot.savefig(bytes_image, format='png')
     bytes_image.seek(0)
     return bytes_image
 def _save_to_png_image(plot: plt, filename):
     # write to disk isntead - this is used as alternative route for a different use case
     filedir = Path(__file__).parent
     relative_path = 'results'
     save_location = (filedir / relative_path / filename).resolve()
     plot.savefig(save_location, format='png')