Пример #1
0
    def __make_table(self):
        '''
        Transforms the filter model into a table. This code is based on the code in matplotlib.table
        :return: the table.
        '''
        if len(self.__filter_model) > 0 and self.__magnitude_model is not None:
            fc = self.__magnitude_model.limits.axes_1.get_facecolor()
            cell_kwargs = {}

            if self.__filter_axes is not None:
                table_axes = self.__filter_axes
                table_loc = {'loc': 'center'}
            else:
                table_axes = self.__magnitude_model.limits.axes_1
                table_loc = {'bbox': (self.x0.value(), self.y0.value(),
                                      self.x1.value() - self.x0.value(), self.y1.value() - self.y0.value())}
            # this is some hackery around the way the matplotlib table works
            # multiplier = 1.2 * 1.85 if not self.__first_create else 1.2
            multiplier = self.filterRowHeightMultiplier.value()
            self.__first_create = False
            row_height = (
                    self.tableFontSize.value() / 72.0 * self.preview.canvas.figure.dpi / table_axes.bbox.height * multiplier)
            cell_kwargs['facecolor'] = fc

            table = Table(table_axes, **table_loc)
            table.set_zorder(1000)
            self.__add_filters_to_table(table, row_height, cell_kwargs)
            table.auto_set_font_size(False)
            table.set_fontsize(self.tableFontSize.value())
            return table
        return None
Пример #2
0
def draw_policy(policy):
    fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(5, 5))
    ax.set_axis_off()
    tb = Table(ax, bbox=[0, 0, 1, 1])

    num_rows, num_cols = (11, 11)
    per_height, per_width = 1.0 / num_rows, 1.0 / num_cols

    for i in range(policy.shape[0]):
        for j in range(policy.shape[1]):
            val = policy[i, j]
            print(i, j, val)
            if val == 2:
                val = 'up'
            if val == 3:
                val = 'down'
            if val == 0:
                val = 'right'
            if val == 1:
                val = 'left'
            if val == -np.inf:
                val = 'wall'
            tb.add_cell(i,
                        j,
                        text=val,
                        width=per_width,
                        height=per_height,
                        loc='center')
        tb.set_fontsize(20)
        ax.add_table(tb)
Пример #3
0
def draw_policy(dic):
    fig, ax = plt.subplots(ncols=1, nrows=1, figsize=(5, 5))
    ax.set_axis_off()
    tb = Table(ax, bbox=[0, 0, 1, 1])

    num_rows, num_cols = (5, 5)
    per_height, per_width = 1.0 / num_rows, 1.0 / num_cols

    for (i, j), val in dic.items():
        #print(i,j,val)
        if np.array_equal(np.array([-1, 0]), val):
            val = 'up'
        if np.array_equal(np.array([1, 0]), val):
            val = 'down'
        if np.array_equal(np.array([0, 1]), val):
            val = 'right'
        if np.array_equal(np.array([0, -1]), val):
            val = 'left'
        tb.add_cell(i,
                    j,
                    text=val,
                    width=per_width,
                    height=per_height,
                    loc='center')
        tb.set_fontsize(20)
        ax.add_table(tb)
Пример #4
0
def checkerboard_table(data,nc,npop,indexname, fmt='{:.0f}', bkg_colors=['yellow', 'white']):
    fig, ax = plt.subplots(figsize=(nc*1.5,npop*1.5))
    ax.set_axis_off()
    ax.set_xlabel('Population')
    tb = Table(ax)
    tb.auto_set_font_size(False)
    tb.set_fontsize(14)

    nrows, ncols = data.shape
    width, height = 1.0 / ncols, 1.0 / nrows

    # Add cells
    for (i,j), val in np.ndenumerate(data):
        # Index either the first or second item of bkg_colors based on
        # a checker board pattern
        idx = 0 if val ==1 else 1
        color = bkg_colors[idx]

        tb.add_cell(i, j, width, height, text=fmt.format(val), 
                    loc='center', facecolor=color)

    # Row Labels...
    for i, label in enumerate(data.index):
        tb.add_cell(i, -1, width, height, text= indexname + ' ' + str(label + 1), loc='right', 
                    edgecolor='none', facecolor='none')
    # Column Labels...
    for j, label in enumerate(data.columns):
        tb.add_cell(-1, j, width, height/2, text=label, loc='center', 
                           edgecolor='none', facecolor='none')
    ax.add_table(tb)
    #plt.savefig("hk.pdf")
    return fig
Пример #5
0
def view_board(np_data, fmt='{:s}', bkg_colors=['pink', 'pink']):
    data = pd.DataFrame(np_data, columns=['0','1','2','3','4','5','6'])
    fig, ax = plt.subplots(figsize=[7,7])
    ax.set_axis_off()
    tb = Table(ax, bbox=[0,0,1,1])
    nrows, ncols = data.shape
    width, height = 1.0 / ncols, 1.0 / nrows

    for (i,j), val in np.ndenumerate(data):
        idx = [j % 2, (j + 1) % 2][i % 2]
        color = bkg_colors[idx]

        tb.add_cell(i, j, width, height, text=fmt.format(val), 
                    loc='center', facecolor=color)

    for i, label in enumerate(data.index):
        tb.add_cell(i, -1, width, height, text=label, loc='right', 
                    edgecolor='none', facecolor='none')

    for j, label in enumerate(data.columns):
        tb.add_cell(-1, j, width, height/2, text=label, loc='center', 
                           edgecolor='none', facecolor='none')
    tb.set_fontsize(24)
    ax.add_table(tb)
    return fig
def checkerboard_table(ax, region, fmt='{:.2f}'):
    loaded_region = region
    nrows = 18
    ncolumns = 18
    ax.set_axis_off()
    tb = Table(ax, bbox=[0, 0, 1, 1])
    colors = COLORS[:len(loaded_region)]
    width, height = 1.0 / ncolumns, 1.0 / nrows

    # Add cells
    row_index = 1
    for unit_id in range(1, 18 * 18 + 1):
        column_index = unit_id % ncolumns
        column_index = column_index if column_index != 0 else ncolumns

        color_id = find_district_id_by_unit_id(loaded_region, unit_id)
        color = colors[color_id - 1]

        # facecolor - background color
        tb.add_cell(row_index,
                    column_index,
                    width,
                    height,
                    loc='center',
                    facecolor=color)

        if column_index == ncolumns:
            row_index += 1

    # Row Labels...
    for i in range(1, nrows + 1):
        tb.add_cell(i,
                    -1,
                    width,
                    height,
                    text=i,
                    loc='right',
                    edgecolor='none',
                    facecolor='none')
    # Column Labels...
    for j in range(1, ncolumns + 1):
        tb.add_cell(-1,
                    j,
                    width,
                    height / 2,
                    text=j,
                    loc='center',
                    edgecolor='none',
                    facecolor='none')

    tb.set_fontsize(16)
    ax.add_table(tb)

    color_patches = get_color_patches(colors)
    ax.legend(handles=color_patches,
              loc='upper center',
              bbox_to_anchor=(0.5, 0),
              shadow=True,
              ncol=4)
Пример #7
0
    def plot_gridvalue(self, ax, mat):
        ax.set_axis_off()
        tb = Table(ax, bbox=[0, 0, 1, 1])

        nrows, ncols = mat.shape
        width, height = 1.0 / ncols, 1.0 / nrows
        # Add cells
        for (i, j), val in np.ndenumerate(mat):
            tb.add_cell(i, j, width, height, text=val,
                        loc='center', facecolor='white')
        tb.set_fontsize(20)
        ax.add_table(tb)
Пример #8
0
def view_board(np_data, fmt='{:s}', bkg_colors=['pink', 'pink']):
    """
    Remember to add a '-' sign to the cell that is the old move
    leading to the current state;
    :param np_data: numpy array of shape (9,9)
    :param fmt: format of the data
    :param bkg_colors: originally used for chess board with intermittent colors
    :return:
    """
    data = pd.DataFrame(np_data,
                        columns=['0', '1', '2', '3', '4', '5', '6', '7', '8'])
    fig, ax = plt.subplots(figsize=[9, 9])
    ax.set_axis_off()
    tb = Table(ax, bbox=[0, 0, 1, 1])
    nrows, ncols = data.shape
    width, height = 1.0 / ncols, 1.0 / nrows

    for (i, j), val in np.ndenumerate(data):
        idx = [j % 2, (j + 1) % 2][i % 2]
        color = bkg_colors[idx]

        tb.add_cell(i,
                    j,
                    width,
                    height,
                    text=fmt.format(val),
                    loc='center',
                    facecolor=color)

    for i, label in enumerate(data.index):
        tb.add_cell(i,
                    -1,
                    width,
                    height,
                    text=label,
                    loc='right',
                    edgecolor='none',
                    facecolor='none')

    for j, label in enumerate(data.columns):
        tb.add_cell(-1,
                    j,
                    width,
                    height / 2,
                    text=label,
                    loc='center',
                    edgecolor='none',
                    facecolor='none')
    tb.set_fontsize(24)
    ax.add_table(tb)
    return fig
Пример #9
0
def checkerboard_table(ax, data, fmt='{:.2f}'):
    BLUE = "#6475A6"
    RED = "#C02D16"
    nrows = data["rows"][0]
    ncolumns = data["columns"][0]
    ax.set_axis_off()
    tb = Table(ax, bbox=[0, 0, 1, 1])
    width, height = 1.0 / ncolumns, 1.0 / nrows

    # Add cells
    row_index = 1
    for _, unit_data in enumerate(data["units"]):
        color = "lightgray"
        id_val = unit_data["id"]
        rep = unit_data["registration"]["rep"]
        column_index = id_val % ncolumns
        column_index = column_index if column_index != 0 else ncolumns

        if rep < 0.5:
            color = BLUE

        if rep > 0.5:
            color = RED

        # facecolor - background color
        tb.add_cell(row_index, column_index, width, height, text=fmt.format(rep),
                    loc='center', facecolor=color)

        if column_index == ncolumns:
            row_index += 1

    # Row Labels...
    for i in range(1, nrows + 1):
        tb.add_cell(i, -1, width, height, text=i, loc='right', edgecolor='none',
                    facecolor='none')
    # Column Labels...
    for j in range(1, ncolumns + 1):
        tb.add_cell(-1, j, width, height / 2, text=j, loc='center', edgecolor='none',
                    facecolor='none')

    tb.set_fontsize(16)
    ax.add_table(tb)

    blue_patch = mpatches.Patch(color=BLUE, label='Democratic units')
    red_patch = mpatches.Patch(color=RED, label='Republican units')
    white_patch = mpatches.Patch(color='lightgray', label='Even support')
    ax.legend(handles=[red_patch, blue_patch, white_patch], loc='upper center',
              bbox_to_anchor=(0.5, 0), shadow=True, ncol=2)
Пример #10
0
def plot_table(ax, data, float_format='{:.2f}', columns=None, bbox=None, cell_font_size=6):
    if columns is not None:
        if type(columns) is dict:
            data = data[columns.keys()]
            
            data = data.rename(columns)
        
        else:
            data = data[columns]
    
    if bbox is None:
        bbox = [0, 0, 1, 1]
    
    ax.set_axis_off()
    
    table = Table(ax, bbox=bbox)

    num_rows, num_cols = data.shape
    
    width = 1.0 / num_cols
    
    #height = 1.0 / num_rows 
    height = table._approx_text_height()

    # Add cells
    for (i,j), val in np.ndenumerate(data):
        val = float_format.format(val)
        
        table.add_cell(i, j, width, height, text=val, loc='center')
    
    cells = table.get_celld()
    
    for index, val in np.ndenumerate(data):
        cells[index].set_fontsize(cell_font_size)

    # Row Labels...
    for i, label in enumerate(data.index):
        table.add_cell(i, -1, width, height, text=label, loc='right', edgecolor='none', facecolor='none')
    
    # Column Labels...
    for j, label in enumerate(data.columns):
        table.add_cell(-1, j, width, height/2, text=label, loc='center', edgecolor='none', facecolor='none')
    
    ax.add_table(table)
    
    table.set_fontsize(cell_font_size)
    
    return ax
Пример #11
0
    def _build_states(self):
        self.t_ax = self.fig.add_axes([0.05, 0.05, .75, .9])
        self.t_ax.set_axis_off()

        nrows = max(self.data['row'])
        ncols = max(self.data['column'])
        width = 1.0 / ncols
        height = 1.0 / nrows

        tb = Table(self.t_ax)
        for abb, row, col in zip(self.data['abbrev'], self.data['row'], self.data['column']):
            tb.add_cell(row-1, col-1, width, height, text=abb.upper(), edgecolor='b',
                        loc='center')

        tb.set_fontsize(20)
        self.tb = self.t_ax.add_table(tb)
Пример #12
0
def main():
    a, b, dot_num, additional_length_multiplier_x, additional_length_multiplier_y, plot_style, borders_style, \
    solution_style, figsize, methods_number, solution_exact, data, target, epsilon, iter_lim \
        = -0.5, 2.0, 1000, 0.0, 0.0, 'k-', 'k--', 'ro', (15.0, 7.5), 5, 0.0, [], "min", 1e-6, 1000
    optimization_methods = (nlopt.dichotomy, nlopt.gsection, nlopt.fibonacci, nlopt.tangent, nlopt.parabolic)
    optimization_methods_names = ("Метод дихотомии", "Метод золотого сечения", "Метод Фибоначчи", "Метод касательных",
                                  "Метод парабол")
    table_head = ("Название\nметода", "Численное\nрешение", "Значение\nцелевой\nфункции",
                  "Абсолютная\nпогрешность\n(аргумент)", "Абсолютная\nпогрешность\n(функция)")
    fmt_a, fmt_b, fmt_solution_exact, fmt_target_value = r"%.", r"%.", r"%.", r"%."
    fmt_a += r"%sf" % str(main_digits_num(a, int(-np.log10(epsilon))))
    fmt_b += r"%sf" % str(main_digits_num(b, int(-np.log10(epsilon))))
    fmt_solution_exact += r"%sf" % str(main_digits_num(solution_exact, int(-np.log10(epsilon))))
    fmt_target_value += r"%sf" % str(main_digits_num(f(solution_exact), int(-np.log10(epsilon))))
    x = np.linspace(a - additional_length_multiplier_x * (b - a), b + additional_length_multiplier_x * (b - a), dot_num)
    y = f(x)
    ncols, nrows = len(table_head), methods_number + 1
    for i in range(methods_number):
        solution_numerical = optimization_methods[i](f, a, b, target=target, epsilon=epsilon, iter_lim=iter_lim)
        plt.figure(num=i + 1, figsize=figsize)
        plt.title(optimization_methods_names[i])
        plt.plot(x, y, plot_style, solution_numerical, f(solution_numerical), solution_style,
                 [a, a], [np.min(y) - additional_length_multiplier_y * (np.max(y) - np.min(y)),
                          np.max(y) + additional_length_multiplier_y * (np.max(y) - np.min(y))], borders_style,
                 [b, b], [np.min(y) - additional_length_multiplier_y * (np.max(y) - np.min(y)),
                          np.max(y) + additional_length_multiplier_y * (np.max(y) - np.min(y))], borders_style)
        plt.grid(True)
        data.append([optimization_methods_names[i], solution_numerical, f(solution_numerical),
                     np.abs(solution_numerical - solution_exact), np.abs(f(solution_numerical) - f(solution_exact))])
    fig = plt.figure(num=methods_number + 1, figsize=figsize)
    ax = plt.subplot()
    ax.axis('off')
    tab = Table(ax, bbox=[0, 0, 1, 1])
    tab.auto_set_column_width(False)
    tab.auto_set_font_size(False)
    for j in range(ncols):
        tab.add_cell(0, j, figsize[0] / ncols, 0.1, text=table_head[j], loc="center")
    for i in range(1, nrows):
        for j in range(ncols):
            tab.add_cell(i, j, figsize[0] / ncols, 0.1, text=str(data[i - 1][j]), loc="center")
    tab.set_fontsize(9.0)
    ax.add_table(tab)
    plt.title(r"$Задача: f(x) = |x| + 2x^2 \rightarrow %s, x\in[$" % target + fmt_a % a + r"; " + fmt_b % b
              + r"]%sТочное решение:" % "\n\n" + r"$x_{%s}$ = " % target + fmt_solution_exact % solution_exact +
              r"; $f(x_{%s})$ = " % target + fmt_target_value % f(solution_exact))
    plt.show()
    plt.close()
Пример #13
0
def draw_grid_world(value_array):
    fig, ax = plt.subplots(1, 1)
    ax.set_axis_off()
    tb = Table(ax, bbox=[0, 0, 1, 1])

    num_rows, num_cols = value_array.shape
    per_height, per_width = 1.0 / num_rows, 1.0 / num_cols

    for (i, j), val in np.ndenumerate(value_array):

        tb.add_cell(i,
                    j,
                    text=val,
                    width=per_width,
                    height=per_height,
                    loc='center')

    tb.set_fontsize(28)
    ax.add_table(tb)
Пример #14
0
def checkerboard_table(data, w_path, w_file_name, fmt='{:.2f}'):
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.set_axis_off()
    tb = Table(ax, bbox=[0, 0, 1, 1])

    nrows, ncols = data.shape
    width, height = 1.2 / ncols, 1 / nrows

    tb.auto_set_font_size(False)
    tb.set_fontsize(0.0001)
    for (i, j), val in np.ndenumerate(data):
        tb.add_cell(i, j, width, height, text=fmt.format(val), loc='center')

    # row label
    for i, label in enumerate(data.index):
        tb.add_cell(i,
                    -1,
                    width,
                    height,
                    text=label,
                    loc='right',
                    edgecolor='none')

    # col label
    for j, label in enumerate(data.columns):
        tb.add_cell(-1,
                    j,
                    width,
                    height / 2,
                    text=label,
                    loc='center',
                    edgecolor='none')
    ax.add_table(tb)
    plt.subplots_adjust(left=0.15, right=0.985, bottom=0.3, top=0.6)
    # plt.subplots_adjust(left=0.15, right=0.985, bottom=0.02, top=0.84)

    # fig, ax = plt.subplots(figsize=(300, 300))
    # ax.axis('off')
    # ax.axis('tight')
    # ax.table(cellText=data.values, colLabels=data.columns, rowLabels=data.index, loc='center', bbox=[0, 0, 1, 1])
    plt.savefig(w_path + w_file_name)
def checkerboard_table(ax, data, region_json_str, fmt='{:.2f}'):
    loaded_region = region_json_str
    nrows = data["rows"][0]
    ncolumns = data["columns"][0]
    ax.set_axis_off()
    tb = Table(ax, bbox=[0, 0, 1, 1])
    colors = COLORS[:len(loaded_region)]
    width, height = 1.0 / ncolumns, 1.0 / nrows

    # Add cells
    row_index = 1
    for _, unit_data in enumerate(data["units"]):
        id_val = unit_data["id"]
        rep = unit_data["registration"]["rep"]
        column_index = id_val % ncolumns
        column_index = column_index if column_index != 0 else ncolumns

        color_id = find_district_id_by_unit_id(loaded_region, id_val)
        color = colors[color_id - 1]

        # facecolor - background color
        tb.add_cell(row_index, column_index, width, height, text=fmt.format(rep),
                    loc='center', facecolor=color)

        if column_index == ncolumns:
            row_index += 1

    # Row Labels...
    for i in range(1, nrows + 1):
        tb.add_cell(i, -1, width, height, text=i, loc='right',
                    edgecolor='none', facecolor='none')
    # Column Labels...
    for j in range(1, ncolumns + 1):
        tb.add_cell(-1, j, width, height / 2, text=j, loc='center',
                    edgecolor='none', facecolor='none')

    tb.set_fontsize(16)
    ax.add_table(tb)

    color_patches = get_color_patches(colors)
    ax.legend(handles=color_patches, loc='upper center', bbox_to_anchor=(0.5, 0), shadow=True,
              ncol=4)
Пример #16
0
    def plot_gridworld(self, ax):
        fs = 20
        ax.set_axis_off()
        tb = Table(ax, bbox=[0, 0, 1, 1])
        w = self.w
        width = height = 1.0 / w
        # Add cells
        for i in range(w):
            for j in range(w):
                val = ''
                if (i, j) == self.A:
                    val = 'A'
                elif (i, j) == self.B:
                    val = 'B'
                elif (i, j) == self.A_:
                    val = 'A\''
                elif (i, j) == self.B_:
                    val = 'B\''
                tb.add_cell(i,
                            j,
                            width,
                            height,
                            text=val,
                            loc='center',
                            facecolor='white')
        tb.set_fontsize(fs)
        ax.add_table(tb)

        p2g = lambda p: (p[1] * width + width / 2 + 0.05, 1 - p[0] * height -
                         height / 2)
        for x, y, t in [(p2g(self.A), p2g(self.A_), '+10'),
                        (p2g(self.B), p2g(self.B_), '+5')]:
            arrow = patches.FancyArrowPatch(
                x,
                y,
                connectionstyle="arc3,rad=-.5",
                arrowstyle="Simple,tail_width=0.5,head_width=4,head_length=8",
                color="k")
            ax.add_artist(arrow)
            plt.text((x[0] + y[0]) / 2, (x[1] + y[1]) / 2, t, fontsize=fs - 2)
Пример #17
0
def draw_policy(dic):
    fig, ax = plt.subplots(figsize=(10, 10))
    ax.set_axis_off()
    tb = Table(ax, bbox=[0, 0, 1, 1])

    num_rows, num_cols = (5, 5)
    per_height, per_width = 1.0 / num_rows, 1.0 / num_cols

    for (i, j), val in dic.items():
        #print(i,j,val)
        val = describe(val)
        text = ''
        for k in range(len(val)):
            text += val[k] + ','
        tb.add_cell(i,
                    j,
                    text=text,
                    width=per_width,
                    height=per_height,
                    loc='center')
        tb.set_fontsize(28)
        ax.add_table(tb)
Пример #18
0
def checkerboard_plot(ary,
                      cell_colors=('white', 'black'),
                      font_colors=('black', 'white'),
                      fmt='%.1f',
                      figsize=None,
                      row_labels=None,
                      col_labels=None,
                      fontsize=None):
    """
    Plot a checkerboard table / heatmap via matplotlib.

    Parameters
    -----------
    ary : array-like, shape = [n, m]
        A 2D Nnumpy array.
    cell_colors : tuple or list (default: ('white', 'black'))
        Tuple or list containing the two colors of the
        checkerboard pattern.
    font_colors : tuple or list (default: ('black', 'white'))
        Font colors corresponding to the cell colors.
    figsize : tuple (default: (2.5, 2.5))
        Height and width of the figure
    fmt : str (default: '%.1f')
        Python string formatter for cell values.
        The default '%.1f' results in floats with 1 digit after
        the decimal point. Use '%d' to show numbers as integers.
    row_labels : list (default: None)
        List of the row labels. Uses the array row
        indices 0 to n by default.
    col_labels : list (default: None)
        List of the column labels. Uses the array column
        indices 0 to m by default.
    fontsize : int (default: None)
        Specifies the font size of the checkerboard table.
        Uses matplotlib's default if None.

    Returns
    -----------
    fig : matplotlib Figure object.

    """

    fig, ax = subplots(figsize=figsize)
    ax.set_axis_off()
    tb = Table(ax, bbox=[0, 0, 1, 1])

    n_rows, n_cols = ary.shape

    if row_labels is None:
        row_labels = np.arange(n_rows)
    if col_labels is None:
        col_labels = np.arange(n_cols)

    width, height = 1.0 / n_cols, 1.0 / n_rows

    for (row_idx, col_idx), cell_val in np.ndenumerate(ary):

        idx = (col_idx + row_idx) % 2
        tb.add_cell(row_idx, col_idx, width, height,
                    text=fmt % cell_val,
                    loc='center',
                    facecolor=cell_colors[idx])

    for row_idx, label in enumerate(row_labels):
        tb.add_cell(row_idx, -1,
                    width, height,
                    text=label, loc='right',
                    edgecolor='none', facecolor='none')

    for col_idx, label in enumerate(col_labels):
        tb.add_cell(-1, col_idx,
                    width, height / 2.,
                    text=label, loc='center',
                    edgecolor='none', facecolor='none')

    for (row_idx, col_idx), cell_val in np.ndenumerate(ary):
        idx = (col_idx + row_idx) % 2
        tb._cells[(row_idx, col_idx)]._text.set_color(font_colors[idx])

    ax.add_table(tb)
    tb.set_fontsize(fontsize)

    return fig
Пример #19
0
def main():
    a, b, a_lst, b_lst, dot_num, additional_length_multiplier_x, additional_length_multiplier_y, plot_style, \
    borders_style, solution_style, a_style, b_style, figsize, methods_number, solution_exact, data, target, epsilon, iter_lim \
        = -1.5, 0.0, [], [], 1000, 0.0, 0.0, 'k-', 'k--', 'ko', '<k', 'k>', (15.0, 7.5), 3, -1.0, [], "min", 1e-3, 1000
    optimization_methods = (nlopt.dichotomy, nlopt.gsection, nlopt.fibonacci,
                            nlopt.tangent, nlopt.parabolic)
    optimization_methods_names = (u"Метод дихотомії",
                                  u"Метод золотого перерізу",
                                  u"Метод Фібоначчи", u"Метод дотичних",
                                  u"Метод парабол")
    table_head = (u"Назва\nметоду", u"Чисельний\nрозв'язок",
                  u"Значення\nцільової\nфункції",
                  u"Абсолютна\nпохибка\n(аргумент)",
                  u"Абсолютна\nпохибка\n(функція)")
    fmt_a, fmt_b, fmt_solution_exact, fmt_target_value = r"%.", r"%.", r"%.", r"%."
    fmt_a += r"%sf" % str(main_digits_num(a, int(-np.log10(epsilon))))
    fmt_b += r"%sf" % str(main_digits_num(b, int(-np.log10(epsilon))))
    fmt_solution_exact += r"%sf" % str(
        main_digits_num(solution_exact, int(-np.log10(epsilon))))
    fmt_target_value += r"%sf" % str(
        main_digits_num(f(solution_exact), int(-np.log10(epsilon))))
    x = np.linspace(a - additional_length_multiplier_x * (b - a),
                    b + additional_length_multiplier_x * (b - a), dot_num)
    y = f(x)
    ncols, nrows = len(table_head), methods_number + 1
    for i in range(methods_number):
        a_lst.append([])
        b_lst.append([])
        solution_numerical = optimization_methods[i](f,
                                                     a,
                                                     b,
                                                     a_lst[i],
                                                     b_lst[i],
                                                     target=target,
                                                     epsilon=epsilon,
                                                     iter_lim=iter_lim)
        plt.figure(num=i + 1, figsize=figsize)
        plt.title(optimization_methods_names[i])
        plt.plot(x, y, plot_style, [a, a], [
            np.min(y) - additional_length_multiplier_y *
            (np.max(y) - np.min(y)),
            np.max(y) + additional_length_multiplier_y *
            (np.max(y) - np.min(y))
        ], borders_style, [b, b], [
            np.min(y) - additional_length_multiplier_y *
            (np.max(y) - np.min(y)),
            np.max(y) + additional_length_multiplier_y *
            (np.max(y) - np.min(y))
        ], borders_style)
        # plt.plot(np.array(a_lst[i]), np.zeros_like(a_lst[i]) + np.min(y) - additional_length_multiplier_y *
        #          (np.max(y) - np.min(y)), a_style, alpha=0.5, label=r'$a_k$')
        # plt.plot(np.array(b_lst[i]), np.zeros_like(b_lst[i]) + np.min(y) - additional_length_multiplier_y *
        #          (np.max(y) - np.min(y)), b_style, alpha=0.5, label=r'$b_k$')
        plt.plot(solution_numerical,
                 f(solution_numerical),
                 solution_style,
                 label=u'Чисельний розв\'язок')
        plt.legend(loc='best',
                   shadow=False,
                   fontsize='x-large',
                   facecolor='black',
                   framealpha=0.15)
        plt.grid(True)
        data.append([
            optimization_methods_names[i], solution_numerical,
            f(solution_numerical),
            np.abs(solution_numerical - solution_exact),
            np.abs(f(solution_numerical) - f(solution_exact))
        ])
    plt.figure(num=methods_number + 1, figsize=figsize)
    ax = plt.subplot()
    ax.axis('off')
    tab = Table(ax, bbox=[0, 0, 1, 1])
    tab.auto_set_column_width(False)
    tab.auto_set_font_size(False)
    for j in range(ncols):
        tab.add_cell(0,
                     j,
                     figsize[0] / ncols,
                     0.1,
                     text=table_head[j],
                     loc="center")
    for i in range(1, nrows):
        for j in range(ncols):
            tab.add_cell(i,
                         j,
                         figsize[0] / ncols,
                         0.1,
                         text=str(data[i - 1][j]),
                         loc="center")
    tab.set_fontsize(9.0)
    ax.add_table(tab)
    plt.title(r"$Задача: f(x) = \frac{x}{x^2 + 1} \rightarrow %s, x\in[$" %
              target + fmt_a % a + r"; " + fmt_b % b +
              r"]%sТочное решение:" % "\n\n" + r"$x_{%s}$ = " % target +
              fmt_solution_exact % solution_exact +
              r"; $f(x_{%s})$ = " % target +
              fmt_target_value % f(solution_exact))
    plt.show()
    plt.close()
    print("a:")
    for arr in a_lst:
        for a in arr:
            print("%.4f" % a)
        print("---------------")
    print("b:")
    for arr in b_lst:
        for b in arr:
            print("%.4f" % b)
        print("---------------")
    print("f(a):")
    for arr in a_lst:
        for a in arr:
            print("%.4f" % f(a))
        print("---------------")
    print("f(b):")
    for arr in b_lst:
        for b in arr:
            print("%.4f" % f(b))
        print("---------------")
Пример #20
0
def checkerboard_plot(ary,
                      cell_colors=('white', 'black'),
                      font_colors=('black', 'white'),
                      fmt='%.1f',
                      figsize=None,
                      row_labels=None,
                      col_labels=None,
                      fontsize=None):
    """
    Plot a checkerboard table / heatmap via matplotlib.

    Parameters
    -----------
    ary : array-like, shape = [n, m]
        A 2D Nnumpy array.
    cell_colors : tuple or list (default: ('white', 'black'))
        Tuple or list containing the two colors of the
        checkerboard pattern.
    font_colors : tuple or list (default: ('black', 'white'))
        Font colors corresponding to the cell colors.
    figsize : tuple (default: (2.5, 2.5))
        Height and width of the figure
    fmt : str (default: '%.1f')
        Python string formatter for cell values.
        The default '%.1f' results in floats with 1 digit after
        the decimal point. Use '%d' to show numbers as integers.
    row_labels : list (default: None)
        List of the row labels. Uses the array row
        indices 0 to n by default.
    col_labels : list (default: None)
        List of the column labels. Uses the array column
        indices 0 to m by default.
    fontsize : int (default: None)
        Specifies the font size of the checkerboard table.
        Uses matplotlib's default if None.

    Returns
    -----------
    fig : matplotlib Figure object.

    Examples
    -----------
    For usage examples, please see
    http://rasbt.github.io/mlxtend/user_guide/plotting/checkerboard_plot/

    """

    fig, ax = subplots(figsize=figsize)
    ax.set_axis_off()
    tb = Table(ax, bbox=[0, 0, 1, 1])

    n_rows, n_cols = ary.shape

    if row_labels is None:
        row_labels = np.arange(n_rows)
    if col_labels is None:
        col_labels = np.arange(n_cols)

    width, height = 1.0 / n_cols, 1.0 / n_rows

    for (row_idx, col_idx), cell_val in np.ndenumerate(ary):

        idx = (col_idx + row_idx) % 2
        tb.add_cell(row_idx,
                    col_idx,
                    width,
                    height,
                    text=fmt % cell_val,
                    loc='center',
                    facecolor=cell_colors[idx])

    for row_idx, label in enumerate(row_labels):
        tb.add_cell(row_idx,
                    -1,
                    width,
                    height,
                    text=label,
                    loc='right',
                    edgecolor='none',
                    facecolor='none')

    for col_idx, label in enumerate(col_labels):
        tb.add_cell(-1,
                    col_idx,
                    width,
                    height / 2.,
                    text=label,
                    loc='center',
                    edgecolor='none',
                    facecolor='none')

    for (row_idx, col_idx), cell_val in np.ndenumerate(ary):
        idx = (col_idx + row_idx) % 2
        tb._cells[(row_idx, col_idx)]._text.set_color(font_colors[idx])

    ax.add_table(tb)
    tb.set_fontsize(fontsize)

    return fig
Пример #21
0
class TableAxis(object):
    def __init__(self, ax, df, colors):
        self._ax = ax
        self._df = df
        self._colors = colors

        # Create matplotlib's Table object
        self._tb = Table(self._ax, bbox=[0, 0, 1, 1])
        self._tb.auto_set_font_size(False)
        self._ax.add_table(self._tb)

        self._calculate_cell_size()
        self._add_cells()
        self._remove_ticks()

    def _calculate_cell_size(self):
        # The number of total rows and columns of the table
        self._nrows = self._df.shape[0]
        self._ncols = self._df.shape[1]

        # Calculate the width and height of a single cell in the table
        L = 1.0
        H = 1.0
        self._w_cell = L / self._ncols
        self._h_cell = H / self._nrows

    def _add_cells(self):
        raise NotImplementedError()

    def _remove_ticks(self):
        self._ax.get_xaxis().set_ticks([])
        self._ax.get_yaxis().set_ticks([])

    def add_row_labels(self):
        """Add row labels using y-axis
        """
        ylabels = list(self._df.index)
        self._ax.yaxis.tick_left()

        yticks = [self._h_cell / 2.0]  # The position of the first label

        # The row labels of condition subtable
        for j in range(1, self._nrows):
            yticks.append(yticks[j - 1] + self._h_cell)

        self._ax.set_yticks(yticks)
        self._ax.set_yticklabels(ylabels, minor=False)
        self._ax.tick_params(axis='y', which='major', pad=3)

        # Hide the small bars of ticks
        for tick in self._ax.yaxis.get_major_ticks():
            tick.tick1On = False
            tick.tick2On = False

    # end of def

    def add_column_labels(self):
        """
        Add column labels using x-axis
        """
        xlabels = list(self._df.columns)
        xticks = [self._w_cell / 2.0]  # The position of the first label
        # The column labels of condition subtable
        for j in range(1, self._ncols):
            xticks.append(xticks[j - 1] + self._w_cell)

        self._ax.xaxis.set_ticks_position('none')

        # # Hide the small bars of ticks
        # for tick in self._ax.xaxis.get_major_ticks():
        #     tick.tick1On = False
        #     tick.tick2On = False

        self._ax.set_xticks(xticks)
        self._ax.set_xticklabels(xlabels, rotation=90, minor=False)
        self._ax.tick_params(axis='x', which='major', pad=-2)

    # end of def

    @property
    def fontsize(self):
        return self._table_fontsize

    @fontsize.setter
    def fontsize(self, val):
        """
        Resize text fonts
        """
        self._table_fontsize = val
        self._tb.set_fontsize(val)

    @property
    def linewidth(self):
        return self._linewidth

    @linewidth.setter
    def linewidth(self, val):
        """Adjust the width of table lines
        """
        self._linewidth = val
        celld = self._tb.get_celld()
        for (i, j), cell in celld.items():
            cell.set_linewidth(self._linewidth)
Пример #22
0
def plot_episodes_result(ax, data, trajectory):
    ax.plot(data, range(len(data)), 'k-', lw=1)
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.spines['left'].set_bounds(-5, 170)
    ax.set_xlim((-150, 8000))
    ax.set_ylim((-5, 180))
    ax.set_yticks([0, 50, 100, 150, 170])
    ax.set_xlabel('Time steps', fontsize=15)
    ax.set_ylabel('Episodes', fontsize=15, labelpad=10)

    center = (5200, 132)
    d = 10
    ax.arrow(*center,
             0,
             d,
             head_width=50,
             head_length=.3 * d,
             length_includes_head=True,
             fc='k')
    ax.arrow(*center,
             0,
             -d,
             head_width=50,
             head_length=.3 * d,
             length_includes_head=True,
             fc='k')
    ax.arrow(*center,
             d * 30,
             0,
             head_width=d / 6,
             head_length=.3 * d * 30,
             length_includes_head=True,
             fc='k')
    ax.arrow(*center,
             -d * 30,
             0,
             head_width=d / 6,
             head_length=.3 * d * 30,
             length_includes_head=True,
             fc='k')
    ax.text(center[0],
            center[1] - 2 * d,
            'Actions',
            fontsize=10,
            horizontalalignment='center')

    tb = Table(ax, bbox=[0.09, 0.42, 0.45, 0.57])
    tb.set_fontsize(12)
    row, col = 8, 10
    h, w = 1 / row, 1 / col
    for i in range(row):
        for j in range(col):
            if (i, j) == WindyGridworld.START: t = 'S'
            elif (i, j) == WindyGridworld.GOAL: t = 'G'
            elif i == 7: t = WindyGridworld.WIND[j]
            else: t = ''
            c = tb.add_cell(i, j, w, h, text=t, loc='center')
            if i == 7:
                c.set_lw(0)
            else:
                c.set_ec('gray')
                c.set_lw(.5)

    ax.add_table(tb)
    ax.add_patch(patches.Rectangle((590, 86), 3660, 92, fill=False))
    ax.arrow(2800,
             90,
             0,
             30,
             width=200,
             head_width=400,
             head_length=10,
             length_includes_head=True,
             fc='gray',
             ec='gray')
    ax.arrow(2800,
             130,
             0,
             30,
             width=200,
             head_width=400,
             head_length=10,
             length_includes_head=True,
             fc='gray',
             ec='gray')

    dh, dw = 13, 365
    for i in range(1, len(trajectory)):
        s, s_ = trajectory[i - 1], trajectory[i]
        if i == 1:
            dx = 100 if s_[1] > s[1] else 0
            dy = 5 if s_[0] > s[0] else 0
            p = (780 + dx, 132 + dy)
        elif i == len(trajectory) - 1:
            dx = -110 if s_[1] < s[1] else 0
            dy = 4 if s_[0] > s[0] else 0
        else:
            dx = dy = 0
        q = (p[0] + dw * (s_[1] - s[1]) - dx, p[1] + dh * (s_[0] - s[0]) - dy)
        ax.plot([p[0], q[0]], [p[1], q[1]], 'k-')
        p = q