Example #1
0
    def plot_gridpolicy(self, ax, mat):
        ax.set_axis_off()
        tb = Table(ax, bbox=[0, 0, 1, 1])
        w = self.w
        d = 0.03
        width = height = 1.0 / w
        p2g = lambda p: (p[1]*width + width/2, 1 - p[0]*height - height/2)

        for i in range(w):
            for j in range(w):
                s = (i, j)
                if s in [(0, 0), (w-1, w-1)]:
                    tb.add_cell(i, j, width, height, text='', facecolor='gray')
                    continue
                else:
                    tb.add_cell(i, j, width, height, text='')

                m = mat[s].max()
                dire = mat[s] == m
                x, y = p2g(s)

                if all(dire == [1, 1, 1, 1]):
                    ax.arrow(x, y, 0, d, head_width=d, fc='k')
                    ax.arrow(x, y, 0, -d, head_width=d, fc='k')
                    ax.arrow(x, y, d, 0, head_width=d, fc='k')
                    ax.arrow(x, y, -d, 0, head_width=d, fc='k')
                elif all(dire == [1, 0, 0, 0]):
                    # up
                    ax.arrow(x, y - width / 2 + d, 0, width / 2, head_width=d, fc='k')
                elif all(dire == [0, 1, 0, 0]):
                    # down
                    ax.arrow(x, y + width / 2 - d, 0, - width / 2, head_width=d, fc='k')
                elif all(dire == [0, 0, 1, 0]):
                    # <-
                    ax.arrow(x + width / 2 - d, y, - width / 2, 0, head_width=d, fc='k')
                elif all(dire == [0, 0, 0, 1]):
                    # ->
                    ax.arrow(x - width / 2 + d, y, width / 2, 0, head_width=d, fc='k')
                elif all(dire == [1, 0, 0, 1]):
                    # ^
                    # |->
                    ax.arrow(x - width / 2 + 2*d, y - width / 2 + 2*d, 0, width / 2 - d, head_width=d, fc='k')
                    ax.arrow(x - width / 2 + 2*d, y - width / 2 + 2*d, width / 2 - d, 0, head_width=d, fc='k')
                elif all(dire == [1, 0, 1, 0]):
                    #   ^
                    # <-|
                    ax.arrow(x + width / 2 - 2*d, y - width / 2 + 2*d, 0, width / 2 - d, head_width=d, fc='k')
                    ax.arrow(x + width / 2 - 2*d, y - width / 2 + 2*d, - width / 2 + d, 0, head_width=d, fc='k')
                elif all(dire == [0, 1, 1, 0]):
                    # <-|
                    #   v
                    ax.arrow(x + width / 2 - 2*d, y + width / 2 - 2*d, - width / 2 + d, 0, head_width=d, fc='k')
                    ax.arrow(x + width / 2 - 2*d, y + width / 2 - 2*d, 0, - width / 2 + d, head_width=d, fc='k')
                elif all(dire == [0, 1, 0, 1]):
                    # |->
                    # v
                    ax.arrow(x - width / 2 + 2*d, y + width / 2 - 2*d, width / 2 - d, 0, head_width=d, fc='k')
                    ax.arrow(x - width / 2 + 2*d, y + width / 2 - 2*d, 0, - width / 2 + d, head_width=d, fc='k')
        ax.add_table(tb)
Example #2
0
def plot_change_maze(out, data, agents, maze, change_step, xlim, ylim, xticks,
                     yticks):
    plt.figure(figsize=(6, 6))
    ax = plt.subplot()

    for i in range(data.shape[0]):
        ax.plot(range(data.shape[1]), data[i], 'k-', lw=1)
        x = data.shape[1] // 5 * 4
        ha, va = [('right', 'bottom'), ('left', 'top')][i]
        ax.text(x,
                data[i][x],
                agents[i].method,
                horizontalalignment=ha,
                verticalalignment=va)
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.spines['bottom'].set_bounds(xlim[0], xlim[1])
    ax.spines['left'].set_bounds(ylim[0], ylim[1])
    ax.set_xlim((xlim[0], xlim[2]))
    ax.set_ylim((ylim[0], ylim[2]))
    ax.set_xticks(xticks)
    ax.set_yticks(yticks[0])
    ax.set_yticklabels(yticks[1])
    ax.set_xlabel('Time steps', fontsize=15, labelpad=15)
    ax.text(-xlim[1] // 5,
            ylim[1] // 2,
            'Cumulative\nreward',
            fontsize=15,
            verticalalignment='center',
            horizontalalignment='center')

    ax.plot([change_step, change_step, xlim[1] // 2, xlim[1] // 2],
            [ylim[0], ylim[1], ylim[2] * .75, ylim[2]],
            'k--',
            lw=.6)

    Δh, Δw = 1 / maze.H, 1 / maze.W
    tb = Table(ax,
               bbox=[abs(xlim[0]) / (abs(xlim[0]) + xlim[2]), .75, .4, .25])
    tb2 = Table(ax, bbox=[.6, .75, .4, .25])
    for i in range(maze.H):
        for j in range(maze.W):
            t = ''
            if (i, j) == maze.S: t = 'S'
            elif (i, j) == maze.G: t = 'G'
            else: t = ''
            c = tb.add_cell(i, j, Δw, Δh, text=t, loc='center')
            c.set_lw(.5)
            c.set_fontsize(10)
            c2 = tb2.add_cell(i, j, Δw, Δh, text=t, loc='center')
            c2.set_lw(.5)
            c2.set_fontsize(10)
            if (i, j) in maze.OBSTACLE: c.set_fc('#aaaaaa')
            if (i, j) in maze.OBSTACLE2: c2.set_fc('#aaaaaa')
    ax.add_table(tb)
    ax.add_table(tb2)

    plt.savefig(out, dpi=300, bbox_inches='tight', pad_inches=.3)
    plt.close()
def draw_value_image(iteration, value_image, env):
    fig, ax = plt.subplots()
    plt.suptitle('Policy Evaluation: Iteration:{:d}'.format(iteration))
    ax.set_axis_off()
    tb = Table(ax, bbox=[0, 0, 1, 1])

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

    # Add cells
    for (i, j), val in np.ndenumerate(value_image):
        if env.is_terminal([i, j]):
            tb.add_cell(i,
                        j,
                        height,
                        width,
                        text=' ',
                        loc='center',
                        facecolor='white')
        elif env.is_on_obstacle([i, j]):
            tb.add_cell(i,
                        j,
                        height,
                        width,
                        text='╳',
                        loc='center',
                        facecolor='white')
        else:
            tb.add_cell(i,
                        j,
                        height,
                        width,
                        text=val,
                        loc='center',
                        facecolor='white')

    # Row and column labels...
    for i in range(nrows):
        tb.add_cell(i,
                    -1,
                    height,
                    width,
                    text=i + 1,
                    loc='right',
                    edgecolor='none',
                    facecolor='none')
    for i in range(ncols):
        tb.add_cell(nrows,
                    i,
                    height,
                    width / 2,
                    text=i + 1,
                    loc='center',
                    edgecolor='none',
                    facecolor='none')
    ax.add_table(tb)
    plt.show()
Example #4
0
    def run(self):
        self.parent.clear_plots()
        if self.data is None:
            length, tMin, tMax, fMin, fMax, lMin, lMax, peakF, peakL, peakT = ("",) * 10
        else:
            length = len(self.data)
            tMin = format_time(self.extent.tMin, True)
            tMax = format_time(self.extent.tMax, True)
            fMin = format_precision(self.settings, freq=self.extent.fMin, fancyUnits=True)
            fMax = format_precision(self.settings, freq=self.extent.fMax, fancyUnits=True)
            lMin = format_precision(self.settings, level=self.extent.lMin, fancyUnits=True)
            lMax = format_precision(self.settings, level=self.extent.lMax, fancyUnits=True)
            peak = self.extent.get_peak_flt()
            peakF = format_precision(self.settings, freq=peak[0], fancyUnits=True)
            peakL = format_precision(self.settings, level=peak[1], fancyUnits=True)
            peakT = format_time(peak[2], True)

        text = [
            ["Sweeps", "", length],
            ["Extents", "", ""],
            ["", "Start", tMin],
            ["", "End", tMax],
            ["", "Min frequency", fMin],
            ["", "Max frequency", fMax],
            ["", "Min level", lMin],
            ["", "Max level", lMax],
            ["Peak", "", ""],
            ["", "Level", peakL],
            ["", "Frequency", peakF],
            ["", "Time", peakT],
        ]

        table = Table(self.axes, loc="center")
        table.set_gid("table")

        rows = len(text)
        cols = len(text[0])
        for row in xrange(rows):
            for col in xrange(cols):
                table.add_cell(row, col, text=text[row][col], width=1.0 / cols, height=1.0 / rows)

        if self.settings.grid:
            colour = "LightGray"
        else:
            colour = "w"
        set_table_colour(table, colour)

        for i in range(3):
            table.auto_set_column_width(i)

        self.axes.add_table(table)
        self.parent.redraw_plot()

        self.parent.threadPlot = None
Example #5
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)
def show_grids(value_function, time_step):
    fig = plt.figure()
    ax = fig.add_subplot(1, 2, 1)
    ax.set_axis_off()
    tb = Table(ax)
    plt.title(r"$V_" + str(time_step + 1) + "$ for the random policy")

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

    for (i, j), val in np.ndenumerate(value_function):
        tb.add_cell(row=i,
                    col=j,
                    width=width,
                    height=height,
                    text=val,
                    loc='center')

    ax.add_table(tb)

    ax2 = fig.add_subplot(1, 2, 2)
    ax2.set_axis_off()
    tb2 = Table(ax2)
    plt.title(r"Greedy policy on $V_" + str(time_step + 1) + "$")

    for (i, j), val in np.ndenumerate(value_function):
        if (i, j) in TERMINAL_STATE:
            text = ""
        else:  # Compute the greedy policy by using the value function
            max_action = -np.inf
            max_action_index = []
            for index, action in enumerate(ACTIONS):
                new_pos = manage_boundaries((i + action[0], j + action[1]))
                if (value_function[new_pos] == max_action
                    ):  # There are multiple optimal actions
                    max_action_index.append(index)
                elif (value_function[new_pos] > max_action):
                    max_action = value_function[new_pos]
                    max_action_index = [index]
            text = "{} {} {} {}".format(
                (0 in max_action_index) * "↑", (2 in max_action_index) * "←",
                (3 in max_action_index) * "→", (1 in max_action_index) * "↓")
        tb2.add_cell(row=i,
                     col=j,
                     width=width,
                     height=height,
                     text=text,
                     loc='center')
    ax2.add_table(tb2)
    print("Use q to close the figure")
    plt.draw()
    plt.show()
def plotGrid(value, title):
    value = np.round(value, decimals=1)
    fig, ax = plt.subplots()
    ax.set_axis_off()
    tb = Table(ax, bbox=[0, 0, 1, 1])

    nrows, ncols = value.shape
    width, height = 1.0 / ncols, 1.0 / nrows
    for (i, j), val in np.ndenumerate(value):
        tb.add_cell(i, j, width, height, text=val, loc='center')
    ax.add_table(tb)
    plt.title(title)
    plt.show()
Example #8
0
def probability_plot(probabilities,
                     selected_sentence,
                     dataset,
                     ploting_path,
                     top_n_probabilities=20,
                     max_length=120):

    # Pyplot options
    fig, ax = plt.subplots()
    ax.set_axis_off()
    tb = Table(ax, bbox=[0, 0, 1, 1])
    ncols = probabilities.shape[0]
    width, height = 1.0 / (ncols + 1), 1.0 / (top_n_probabilities + 1)

    # Truncate the time
    selected_sentence = selected_sentence[:max_length]
    probabilities = probabilities[:max_length]

    # Sort the frequencies
    sorted_indices = np.argsort(probabilities, axis=1)
    probabilities = probabilities[
        np.repeat(np.arange(probabilities.shape[0])[:, None],
                  probabilities.shape[1],
                  axis=1), sorted_indices][:, ::-1]

    # Truncate the probabilities
    probabilities = probabilities[:, :top_n_probabilities]

    for (i, j), _ in np.ndenumerate(probabilities):
        tb.add_cell(j + 1,
                    i,
                    height,
                    width,
                    text=unicode(str(
                        conv_into_char(sorted_indices[i, j, 1], dataset)[0]),
                                 errors='ignore'),
                    loc='center',
                    facecolor=(1, 1 - probabilities[i, j, 0],
                               1 - probabilities[i, j, 0]))

    for i, char in enumerate(selected_sentence):
        tb.add_cell(0,
                    i,
                    height,
                    width,
                    text=unicode(char, errors='ignore'),
                    loc='center',
                    facecolor='green')
    ax.add_table(tb)

    plt.savefig(ploting_path)
Example #9
0
        def checkerboard_table(self, data, preyPosition):
            fig, ax = plt.subplots()
            ax.set_axis_off()
            tb = Table(ax, bbox=[0,0,1,1])

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

            # Add cells
            for i in range(self.boardSize[0]):
                for j in range(self.boardSize[1]):
                    if(i == preyPosition[0] and j == preyPosition[1]):
                        tb.add_cell(i, j, width, height, text=str(data[i][j]),
                            loc='center', facecolor='yellow')
                    else:
                        tb.add_cell(i, j, width, height, text=str(data[i][j]),
                            loc='center', facecolor='white')

            # Row Labels...
            for i in range(self.boardSize[0]):
                tb.add_cell(i, -1, width, height, text=str(i), loc='right',
                            edgecolor='none', facecolor='none')
            # Column Labels...
            for j in range(self.boardSize[1]):
                tb.add_cell(-1, j, width, height/2, text=str(j), loc='center',
                                   edgecolor='none', facecolor='none')
            ax.add_table(tb)
Example #10
0
def drawtable(data, rows, columns, title, folder='Table', rowname='',fmt='{:.2f}'):
	nrows = len(rows)
	ncols = len(columns)
	fig, ax = plt.subplots(figsize=(ncols+2,nrows+2))
	ax.set_axis_off()
	rowlc='#F0F0F0'
	collc='#F0F0F0'
	cellc='#FFFFFF'
	ecol='#0000FF'
	font1 = FontProperties()
	font1.set_size('9')
	fontl = font1.copy()
	fontl.set_weight('bold')
	tb = Table(ax)#, bbox=[0.10,0.10,0.90,0.90])
	tb.auto_set_font_size(False)
	#tb.set_fontsize(100.0)
	width, height = 0.95/(ncols+1), 0.95/(nrows+1)
	for i in range(nrows):
		tb.add_cell(i,-1, width*2, height, text=rows[i][:20], loc='right',edgecolor=ecol, facecolor=rowlc,fontproperties=fontl)
	# Column Labels
	for j in range(ncols):
		tb.add_cell(-1, j, width, height/1.5, text=columns[j][:10], loc='center', edgecolor=ecol, facecolor=collc,fontproperties=fontl)
	tb.add_cell(-1,-1, width*2, height/1.5, text=rowname[:10], loc='right',edgecolor=ecol, facecolor=rowlc,fontproperties=fontl)

	# Add cells
	for i in range(len(data)):
		for j in range(len(data[i])):
			val = data[i][j]
			tb.add_cell(i,j,width, height, text=fmt.format(val), loc='center', edgecolor=ecol, facecolor=cellc, fontproperties=font1)
	# Row Labels
	ax.add_table(tb)
	plt.savefig(folder+'/'+title+'.pdf')
	#plt.show()
	#sys.exit(0)
	plt.close()
Example #11
0
def task_table_plot(task_data):
    """
    Plot task table, save in png file.
    :param task_data: dataframe from get_task_table().
    """
    groups = task_data.Group.values
    task_no_group = task_data.drop('Group', axis=1)
    nrows, ncols = task_no_group.shape
    width, height = 1.0 / ncols, 1.0 / nrows

    fig, ax = plt.subplots(figsize=(1, nrows*0.25))
    ax.set_axis_off()
    tbl = Table(ax)
    tbl.auto_set_font_size(False)
    # Columns width for non-auto-width columns
    col_widths = [1, 1, 0.5, 1, 0.7, 0.7, 0.7, 0.7, 0.7]
    palette = get_palette()
    fontcolor = 'w'
    for (i, j), val in np.ndenumerate(task_no_group):
        fc = palette[groups[i]]
        fontsize = 10
        if j < 2:
            loc = 'left'
            font_family = None
            if j == 0:
                fontsize = 9
        else:
            loc = 'center'
            font_family = 'DINPro'
            if j > 3:
                fontsize = 9
        tbl.add_cell(i, j, col_widths[j], height, text=val,
                     loc=loc, facecolor=fc, edgecolor=fontcolor)
        cell = tbl.get_celld()[(i, j)]
        cell.set_linewidth(0.5)
        cell.set_text_props(color=fontcolor, family=font_family, weight='bold', fontsize=fontsize)

    # Column Labels...
    for j, label in enumerate(task_no_group.columns):
        tbl.add_cell(-1, j, col_widths[j], height*0.8, text=label, loc='center',
                     facecolor='gray', edgecolor='w')
        cell = tbl.get_celld()[(-1, j)]
        cell.set_linewidth(0.5)
        cell.set_text_props(color=fontcolor, weight='bold', family='Verdana', fontsize=9)

    tbl._autoColumns = [0, 1]
    tbl.scale(1, 1.5)  # scale y to cover blank in the bottom
    ax.add_table(tbl)
    ax.margins(0, 0)
    fig.savefig('img/task_table', bbox_inches='tight', pad_inches=0.1, dpi=200)
Example #12
0
def task_table_plot(task_data):
    """
    Plot task table, save in png file.
    :param task_data: dataframe from get_task_table().
    """
    groups = task_data.Group.values
    task_no_group = task_data.drop('Group', axis=1)
    nrows, ncols = task_no_group.shape
    width, height = 1.0 / ncols, 1.0 / nrows

    fig, ax = plt.subplots(figsize=(1, nrows*0.25))
    ax.set_axis_off()
    tbl = Table(ax)
    tbl.auto_set_font_size(False)
    # Columns width for non-auto-width columns
    col_widths = [1, 1, 0.5, 1, 0.7, 0.7, 0.7, 0.7, 0.7]
    palette = get_palette()
    fontcolor = 'w'
    for (i, j), val in np.ndenumerate(task_no_group):
        fc = palette[groups[i]]
        fontsize = 10
        if j < 2:
            loc = 'left'
            font_family = None
            if j == 0:
                fontsize = 9
        else:
            loc = 'center'
            #font_family = 'DINPro'
            if j > 3:
                fontsize = 9
        tbl.add_cell(i, j, col_widths[j], height, text=val,
                     loc=loc, facecolor=fc, edgecolor=fontcolor)
        cell = tbl.get_celld()[(i, j)]
        cell.set_linewidth(0.5)
        cell.set_text_props(color=fontcolor, family=font_family, weight='bold', fontsize=fontsize)

    # Column Labels...
    for j, label in enumerate(task_no_group.columns):
        tbl.add_cell(-1, j, col_widths[j], height*0.8, text=label, loc='center',
                     facecolor='gray', edgecolor='w')
        cell = tbl.get_celld()[(-1, j)]
        cell.set_linewidth(0.5)
        cell.set_text_props(color=fontcolor, weight='bold', family='Verdana', fontsize=9)

    tbl._autoColumns = [0, 1]
    tbl.scale(1, 1.5)  # scale y to cover blank in the bottom
    ax.add_table(tbl)
    ax.margins(0, 0)
    fig.savefig('img/task_table', bbox_inches='tight', pad_inches=0.1, dpi=200)
Example #13
0
def checkerboard_table(data, columns, rows, title, fmt='{:.2f}', logarea = 0.035):
    fig, ax = plt.subplots()
    plt.set_cmap('cool')
    ax.set_axis_off()

    tb = Table(ax, bbox=[0,0,1,1])
    #plt.suptitle(title)
    nrows, ncols = data.shape
    width, height = 1.0 / ncols, 1.0 / nrows
    min_color = np.min(data)/logarea
    max_color = np.max(data)/logarea
    # 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
        color = (val/logarea)/max_color
        print val
        if val > 0.0:
            tb.add_cell(i, j, width, height, text=fmt.format(val),
                        loc='center', facecolor = str(1.0 - val/np.sum(data)))
        else:
            tb.add_cell(i, j, width, height)
    # Row Labels...
    for i in range(0,len(rows)):
        tb.add_cell(i, -1, width, height, text=rows[i], loc='top',
                    edgecolor='none', facecolor='none')
    # Column Labels...
    for j in range(0,len(columns)):
        tb.add_cell(-1, j, width, height/2.0, text=columns[j], loc='left',
                           edgecolor='none', facecolor='none')
    ax.add_table(tb)
    #.colorbar()
    return fig
Example #14
0
def show_grid(grid):
    fig, ax = plt.subplots()
    ax.set_axis_off()
    tb = Table(ax, bbox=[0, 0, 1, 1])

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

    for (i, j), val in np.ndenumerate(grid):
        color = 'grey' if (i, j) == (0, 0) or (i, j) == (3, 3) else 'white'
        tb.add_cell(i, j, width, height, text="{0:.2f}".format(val),
                    loc='center', facecolor=color)

    ax.add_table(tb)
    return ax
Example #15
0
def draw_image(image):
    plt.figure()
    ax = plt.gca()
    ax.set_axis_off()

    table = Table(ax, bbox=[0, 0, 1, 1])

    width, height = 1.0 / world_size, 1.0 / world_size

    for i in range(world_size):
        for j in range(world_size):
            # image, i is x, j is y
            table.add_cell(j, i, width, height, text=image[i, j], loc='center')

    ax.add_table(table)
Example #16
0
def probability_plot(probabilities,
                     selected,
                     vocab,
                     ploting_path,
                     top_n_probabilities=20,
                     max_length=120):
    selected = selected[:max_length]
    probabilities = probabilities[:max_length]
    # target = ['a', 'b', 'c', 'd', 'e', 'f', 'a', 'b', 'c', 'd']
    # probabilities = np.random.uniform(low=0, high=1, size=(10, 6))  # T x C
    sorted_probabilities = np.zeros(probabilities.shape)
    sorted_indices = np.zeros(probabilities.shape)
    for i in range(probabilities.shape[0]):
        sorted_probabilities[i, :] = np.sort(probabilities[i, :])
        sorted_indices[i, :] = np.argsort(probabilities[i, :])
    concatenated = np.zeros(
        (probabilities.shape[0], probabilities.shape[1], 2))
    concatenated[:, :, 0] = sorted_probabilities[:, ::-1]
    concatenated[:, :, 1] = sorted_indices[:, ::-1]

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

    ncols = concatenated.shape[0]
    width, height = 1.0 / (ncols + 1), 1.0 / (top_n_probabilities + 1)

    for (i, j), v in np.ndenumerate(concatenated[:, :top_n_probabilities, 0]):
        tb.add_cell(j + 1,
                    i,
                    height,
                    width,
                    text=unicode(vocab[concatenated[i, j, 1].astype('int')],
                                 errors='ignore'),
                    loc='center',
                    facecolor=(1, 1 - concatenated[i, j, 0],
                               1 - concatenated[i, j, 0]))
    for i, char in enumerate(selected):
        tb.add_cell(0,
                    i,
                    height,
                    width,
                    text=unicode(char, errors='ignore'),
                    loc='center',
                    facecolor='green')
    ax.add_table(tb)

    plt.savefig(ploting_path)
Example #17
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)
 def _create_table(self):
     """Creates a table for displaying the entire field using matplotlib table."""
     _, axis = plt.subplots()
     axis.set_axis_off()
     table = Table(axis, bbox=[0, 0, 1, 1])
     try:
         width, height = 1.0 / self.rows, 1.0 / self.cols
     except ZeroDivisionError:
         # No table is going to be drawn, cols or rows is 0
         return
     current_col = 0
     while current_col < self.cols:
         for current_row in range(0, self.rows):
             value = self.data[current_row][current_col]
             cell = table.add_cell(current_col,
                                   current_row,
                                   width,
                                   height,
                                   text=value or "",
                                   loc='center')
             if value != MINE:
                 text_color = self._get_color(value)
                 cell.get_text().set_color(text_color)
             cell.get_text().set_fontsize(FONT_SIZE)
         current_col += 1
     title = f"Game, W: {self.rows}, H: {self.cols}, Mines: {self.mines}"
     axis.set_title(title)
     axis.add_table(table)
Example #19
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()
def square_table(data, fmt='{:.0f}'):
	fig, ax = plt.subplots()
	ax.set_axis_off()
	tb = Table(ax, bbox=[0,0,1,1])
	nrows, ncols = data.shape
	width, height = 1.0 / ncols, 1.0 / nrows
	# Add cells
	for (i,j), val in np.ndenumerate(data):
		tb.add_cell(i, j, width, height, text=fmt.format(val), loc='center')
	"""
    # Row and Column Labels...
	for i, label in enumerate(data.columns):
		tb.add_cell(i, -1, width, height, text=label, loc='right', edgecolor='none', facecolor='none')
		tb.add_cell(-1, i, width, height/2, text=label, loc='center', edgecolor='none', facecolor='none')
    """
	ax.add_table(tb)
	return fig
Example #21
0
def drawTable(data, rowLabels, columnLabels, max, isPositive, fmt='{:.2f}'):
    fig, ax = plt.subplots()
    ax.set_axis_off()
    tb = Table(ax, bbox=[0, 0, 1, 1])

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

    # Add cells
    for (i, j), val in np.ndenumerate(data):
        # https://matplotlib.org/2.0.2/api/colors_api.html
        if isPositive:
            color = (1 - (data[i][j] / max), 1, 1 - (data[i][j] / max))
        else:
            color = (1, 1 - (data[i][j] / max), 1 - (data[i][j] / max))

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

        if j == 0:
            tb.add_cell(i,
                        -1,
                        width,
                        height,
                        text=rowLabels[i],
                        loc='right',
                        edgecolor='white',
                        facecolor='white')

        if i == 0:
            tb.add_cell(-1,
                        j,
                        width,
                        height / 2,
                        text=columnLabels[j],
                        loc='center',
                        edgecolor='white',
                        facecolor='white')

    tb.add_cell(-1,
                -1,
                width,
                height / 2,
                text="",
                loc='center',
                edgecolor='white',
                facecolor='white')

    ax.add_table(tb)
    return fig
Example #22
0
    def plot_value(ax: plt.Axes):
        rounded_value = np.round(learner.value, decimals=1)
        ax.set_axis_off()
        tb = Table(ax, bbox=[0, 0, 1, 1])

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

        for (i, j), val in np.ndenumerate(rounded_value):
            tb.add_cell(i,
                        j,
                        width,
                        height,
                        text=val,
                        loc="center",
                        facecolor="white")

        ax.add_table(tb)
Example #23
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)
Example #24
0
def plot_param_legend(legend, plot_size, placement):
    # LEGEND
    rowSpan = max(plot_size[0] - 1, 1 / len(legend))
    ax = plt.subplot2grid(plot_size,
                          placement,
                          colspan=plot_size[1] - placement[1],
                          rowspan=rowSpan)
    ax.set_axis_off()
    plt.title("Parametrization\nused")
    tb = Table(ax, bbox=[0, 0, 1, 1])
    height = 1. / len(legend)
    for row, lgd in enumerate(legend):
        tb.add_cell(row,
                    0,
                    1.,
                    height,
                    text=lgd,
                    loc='left',
                    edgecolor='white')
    ax.add_table(tb)
Example #25
0
def test_table_cells():
    fig, ax = plt.subplots()
    table = Table(ax)

    cell = table.add_cell(1, 2, 1, 1)
    assert isinstance(cell, CustomCell)
    assert cell is table[1, 2]

    cell2 = CustomCell((0, 0), 1, 2, visible_edges=None)
    table[2, 1] = cell2
    assert table[2, 1] is cell2
def test_table_cells():
    fig, ax = plt.subplots()
    table = Table(ax)

    cell = table.add_cell(1, 2, 1, 1)
    assert isinstance(cell, CustomCell)
    assert cell is table[1, 2]

    cell2 = CustomCell((0, 0), 1, 2, visible_edges=None)
    table[2, 1] = cell2
    assert table[2, 1] is cell2
def probability_plot(probabilities, selected_sentence, dataset, ploting_path,
                     top_n_probabilities=20, max_length=120):

    # Pyplot options
    fig, ax = plt.subplots()
    ax.set_axis_off()
    tb = Table(ax, bbox=[0, 0, 1, 1])
    ncols = probabilities.shape[0]
    width, height = 1.0 / (ncols + 1), 1.0 / (top_n_probabilities + 1)

    # Truncate the time
    selected_sentence = selected_sentence[:max_length]
    probabilities = probabilities[:max_length]

    # Sort the frequencies
    sorted_indices = np.argsort(probabilities, axis=1)
    probabilities = probabilities[
        np.repeat(np.arange(probabilities.shape[0])[
            :, None], probabilities.shape[1], axis=1),
        sorted_indices][:, ::-1]

    # Truncate the probabilities
    probabilities = probabilities[:, :top_n_probabilities]

    for (i, j), _ in np.ndenumerate(probabilities):
        tb.add_cell(j + 1, i, height, width,
                    text=unicode(str(conv_into_char(sorted_indices[i, j, 1],
                                                    dataset)[0]),
                                 errors='ignore'),
                    loc='center',
                    facecolor=(1,
                               1 - probabilities[i, j, 0],
                               1 - probabilities[i, j, 0]))

    for i, char in enumerate(selected_sentence):
        tb.add_cell(0, i, height, width,
                    text=unicode(char, errors='ignore'),
                    loc='center', facecolor='green')
    ax.add_table(tb)

    plt.savefig(ploting_path)
Example #28
0
def fill_table(values):
    """Fill the values in a table

    :param values: state values
    :type values: dict
    :return: None
    :rtype: None
    """
    fig, ax = plt.subplots()
    tb = Table(ax, bbox=[0, 0, 1, 1])
    for (x, y), val in values.items():
        tb.add_cell(x,
                    y,
                    1 / 5,
                    1 / 5,
                    text=round(val, 1),
                    loc='center',
                    facecolor='white')

    ax.add_table(tb)
    ax.set_axis_off()
Example #29
0
def checkerboard_table(data, fmt='{:.2f}', bkg_colors=['yellow', 'white']):
    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.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')
    ax.add_table(tb)
    return fig
def draw_q_value_image(dyna_maze, q_value, run, planning_steps, episode):
    # 축 표시 제거, 크기 조절 등 이미지 그리기 이전 설정 작업
    fig, axis = plt.subplots()
    axis.set_axis_off()
    table = Table(axis, bbox=[0, 0, 1, 1])

    num_rows, num_cols = dyna_maze.MAZE_HEIGHT, dyna_maze.MAZE_WIDTH
    width, height = 1.0 / num_cols, 1.0 / num_rows

    for i in range(dyna_maze.MAZE_HEIGHT):
        for j in range(dyna_maze.MAZE_WIDTH):
            if np.sum(q_value[i][j]) == 0.0:
                symbol = " "
            else:
                action_idx = np.argmax(q_value[i][j])
                symbol = dyna_maze.ACTION_SYMBOLS[action_idx]
            table.add_cell(i, j, width, height, text=symbol, loc='center', facecolor='white')

    # 행, 열 라벨 추가
    for i in range(dyna_maze.MAZE_HEIGHT):
        table.add_cell(i, -1, width, height, text=i, loc='right', edgecolor='none', facecolor='none')

    for j in range(dyna_maze.MAZE_WIDTH):
        table.add_cell(-1, j, width, height/2, text=j, loc='center', edgecolor='none', facecolor='none')

    for key, cell in table.get_celld().items():
         cell.get_text().set_fontsize(20)

    axis.add_table(table)
    plt.savefig('images/maze_action_values_{0}_{1}_{2}.png'.format(run, planning_steps, episode))
    plt.close()
Example #31
0
def draw_lat_matrix(fname,
                    data,
                    title="",
                    lat_type=None,
                    lat_types=None,
                    columns=[],
                    rows=[]):
    bkg_colors = ['#CCFFFF', 'white']
    fmt = '{:.3f}'
    fig, ax = plt.subplots()
    ax.set_axis_off()
    tb = Table(ax, bbox=[0, 0, 1, 1])
    nrows, ncols = data.shape
    assert nrows == len(rows)
    assert ncols == len(columns)
    width, height = 1.0 / ncols * 2, 1.0 / nrows * 2
    for (i, j), val in np.ndenumerate(data):
        idx = [j % 2, (j + 1) % 2][i % 2]
        color = bkg_colors[idx]
        if val:
            if lat_type:
                txt = fmt.format(ls.exec_fn(val, lat_type))
            else:
                assert lat_types
                txt = fmt.format(ls.exec_fn(val, lat_types[i]))
        else:
            txt = "-"
        tb.add_cell(i,
                    j,
                    width,
                    height,
                    text=txt,
                    loc='center',
                    facecolor=color)
    # Row Labels...
    for i, label in enumerate(rows):
        tb.add_cell(i,
                    -1,
                    width,
                    height,
                    text=label,
                    loc='right',
                    edgecolor='none',
                    facecolor='none')
    # Column Labels...
    for j, label in enumerate(columns):
        tb.add_cell(-1,
                    j,
                    width,
                    height / 2,
                    text=label,
                    loc='center',
                    edgecolor='none',
                    facecolor='none')
    ax.add_table(tb)

    if title:
        ax.set_title("\n".join(wrap(title)), y=1.08)
    savefig('../figs/' + fname + '.pdf', bbox_inches='tight')
    plt.close()
Example #32
0
    def display(self, agent):
        fig = plt.figure()
        ax = fig.add_subplot(1, 1, 1)
        ax.set_axis_off()
        tb = Table(ax)

        nrows, ncols = self.world.shape
        width, height = 1.0 / ncols, 1.0 / nrows

        for (i, j), val in np.ndenumerate(self.world):
            if (i, j) == (agent.pos_y, agent.pos_x):
                tb.add_cell(row=i,
                            col=j,
                            width=width,
                            height=height,
                            facecolor=agent.color)
            elif (i, j) == self.ending_point:
                tb.add_cell(row=i,
                            col=j,
                            width=width,
                            height=height,
                            facecolor="red")
            else:
                tb.add_cell(row=i,
                            col=j,
                            width=width,
                            height=height,
                            text=self.dict_world_to_text[val],
                            facecolor=self.dict_world_to_color[val],
                            loc="center")
        ax.add_table(tb)

        plt.plot()
        plt.show()
Example #33
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)
Example #34
0
def checkerboard_table(data, fmt='{:.2f}', bkg_colors=['yellow', 'white']):
    fig, ax = plt.subplots()
    ax.set_axis_off()
    tb = Table(ax, bbox=[0,0,1,1])

    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 = [j % 2, (j + 1) % 2][i % 2]
        color = bkg_colors[idx]

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

    # Row Labels...
    for i, label in enumerate(data.index):
        tb.add_cell(i, -1, width, height, text=label, 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)
    return fig
def draw_image(image):
    fig, ax = plt.subplots()
    ax.set_axis_off()
    tb = Table(ax, bbox=[0,0,1,1])

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

    # Add cells
    for (i,j), val in np.ndenumerate(image):
        # Index either the first or second item of bkg_colors based on
        # a checker board pattern
        idx = [j % 2, (j + 1) % 2][i % 2]
        color = 'white'

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

    # Row Labels...
    for i, label in enumerate(range(len(image))):
        tb.add_cell(i, -1, width, height, text=label+1, loc='right', 
                    edgecolor='none', facecolor='none')
    # Column Labels...
    for j, label in enumerate(range(len(image))):
        tb.add_cell(-1, j, width, height/2, text=label+1, loc='center', 
                           edgecolor='none', facecolor='none')
    ax.add_table(tb)
    plt.show()
Example #36
0
def plot_show(sample_count):
    fig, ax = plt.subplots(figsize=(25,25))
    ax.set_axis_off()
    tb = Table(ax, bbox=[0, 0, 1, 1])
    all_cards = get_all_cards()

    # nrows, ncols = len(label), len(label)
    nrows, ncols = len(all_cards), len(all_cards)
    width, height = 1.0 / ncols, 1.0 / nrows

    # Add cells
    for i in range(len(all_cards)):
        for j in range(len(all_cards)):
            if all_cards[i] == all_cards[j]:
                EHS_value = 0.0
            else:
                EHS_value = computer_EHS([all_cards[i], all_cards[j]], sample_count) * 100

            color = get_color(EHS_value)
            tb.add_cell(i+1, j, width, height, text=str(int(EHS_value)),
                        loc='center', facecolor=color)

    # Row Labels...
    for i in range(len(all_cards)):
        tb.add_cell(i + 1, -1, width, height, text=all_cards[i], loc='right',
                    edgecolor='none', facecolor='none')
    # Column Labels...
    for j in range(len(all_cards)):
        tb.add_cell(0, j, width, height / 2, text=all_cards[j], loc='center',
                    edgecolor='none', facecolor='none')
    ax.add_table(tb)
    plt.title("EHS")
    plt.show()
Example #37
0
def draw_image(image):
    fig, ax = plt.subplots()
    ax.set_axis_off()
    tb = Table(ax, bbox=[0, 0, 1, 1])

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

    # Add cells
    for (i,j), val in np.ndenumerate(image):
        # Index either the first or second item of bkg_colors based on
        # a checker board pattern
        idx = [j % 2, (j + 1) % 2][i % 2]
        color = 'white'

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

    # Row Labels...
    for i, label in enumerate(range(len(image))):
        tb.add_cell(i, -1, width, height, text=label+1, loc='right',
                    edgecolor='none', facecolor='none')
    # Column Labels...
    for j, label in enumerate(range(len(image))):
        tb.add_cell(-1, j, width, height/2, text=label+1, loc='center',
                           edgecolor='none', facecolor='none')
    ax.add_table(tb)
Example #38
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
Example #39
0
def visualize_results_plate_class_membership(data, fmt='{:.2f}', bkg_colors=['cyan', 'white']):
    fig, ax = plt.subplots()
    ax.set_axis_off()
    tb = Table(ax, bbox=[0,0,1,1])

    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 = [j % 2, (j + 1) % 2][i % 2]
        #color = bkg_colors[idx]

        if (val > 0.5):
            color = bkg_colors[0]
        else:
            color = bkg_colors[1]

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

    # axis labels for rows ...
    for i, label in enumerate(string.ascii_uppercase[:nrows:]):
        tb.add_cell(i, -1, width, height, text=label, loc='right', edgecolor='none', facecolor='none')

    # axis labels for cols ...
    for j, label in enumerate(data.columns):
        tb.add_cell(-1, j, width, height/2, text=label+1, loc='center', edgecolor='none', facecolor='none')

    ax.add_table(tb)

    fig.suptitle("Visualize classification results - Plate with class memberships")

    return fig
def draw_image(image):
    fig, ax = plt.subplots()
    ax.set_axis_off()
    tb = Table(ax, bbox=[0, 0, 1, 1])

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

    # Add cells
    for (i, j), val in np.ndenumerate(image):

        # add state labels
        if [i, j] == A_POS:
            val = str(val) + " (A)"
        if [i, j] == A_PRIME_POS:
            val = str(val) + " (A')"
        
        tb.add_cell(i, j, width, height, text=val,
                    loc='center', facecolor='white')
        

    # Row and column labels...
    for i in range(len(image)):
        tb.add_cell(i, -1, width, height, text=i+1, loc='right',
                    edgecolor='none', facecolor='none')
    for i in range(len(image[0])):
        tb.add_cell(-1, i, width, height/2, text=i+1, loc='center',
                    edgecolor='none', facecolor='none')

    ax.add_table(tb)
Example #41
0
def sort_fellows_table_pdf(names, jobs, companies, projects, subjects, unis, degs, name_plot):

    table = OrderedDict((
    ('Name',names),
    ('Job',jobs),
    ('Company',companies),
    ('Project',projects),
    ('Subject',subjects),
    ('University', unis),
    ('Degree',degs)))

    Headn = ['Name','Job','Company','Project','Subject','University','Degree']
    data = pandas.DataFrame(table)

    #print data
    
    fig, ax = plt.subplots()
    ax.set_axis_off()
    tb = Table(ax, bbox=[0,0,1,1])

    nrows, ncols = data.shape
    wcell = 1
    hcell = 1
    wpad = 0.5
    hpad = 0.5
    print "Making table" 
    #fig = plt.figure(figsize=(5, 20))
    width, height = 1.0 / (ncols*1.0), 1.0 / (nrows*2.0)
    matplotlib.rcParams.update({'font.size': 50})
    print nrows, ncols
    # Add cells
    print data[Headn[1]].iloc[0]

    for i in range(0,ncols):
        for j in range(0,nrows-1):
            # Index either the first or second item of bkg_colors based on
            # a checker board pattern
            #idx = [j % 2, (j + 1) % 2][i % 2]
            txt = "\n".join(wrap(data[Headn[i]].iloc[j], 40))
            nmrows = len(txt)/20.0
            print len(txt), nmrows
            #raw_input('check')
            color = "white"
            tb.add_cell(j, i, width, height*2.0, text=txt, 
                    loc='center', facecolor="white")

    # Row Labels...
    for i in range(0,nrows-1):
        label = str(i)
        tb.add_cell(i, -1, width, height*2.0, text=label, loc='right', 
                    edgecolor='black', facecolor='lightblue')
    # Column Labels...
    for j, label in enumerate(data.columns):
        tb.add_cell(-1, j, width, height, text=label, loc='center', 
                           edgecolor='black', facecolor='lightcoral')
    ax.add_table(tb)
    plt.savefig(name_plot+'.pdf', bbox_inches = "tight")
    return ''
Example #42
0
def probability_plot(probabilities, selected, vocab, ploting_path,
                     top_n_probabilities=20, max_length=120):
    selected = selected[:max_length]
    probabilities = probabilities[:max_length]
    # target = ['a', 'b', 'c', 'd', 'e', 'f', 'a', 'b', 'c', 'd']
    # probabilities = np.random.uniform(low=0, high=1, size=(10, 6))  # T x C
    sorted_probabilities = np.zeros(probabilities.shape)
    sorted_indices = np.zeros(probabilities.shape)
    for i in range(probabilities.shape[0]):
        sorted_probabilities[i, :] = np.sort(probabilities[i, :])
        sorted_indices[i, :] = np.argsort(probabilities[i, :])
    concatenated = np.zeros((
        probabilities.shape[0], probabilities.shape[1], 2))
    concatenated[:, :, 0] = sorted_probabilities[:, ::-1]
    concatenated[:, :, 1] = sorted_indices[:, ::-1]

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

    ncols = concatenated.shape[0]
    width, height = 1.0 / (ncols + 1), 1.0 / (top_n_probabilities + 1)

    for (i, j), v in np.ndenumerate(concatenated[:, :top_n_probabilities, 0]):
        tb.add_cell(j + 1, i, height, width,
                    text=unicode(vocab[concatenated[i, j, 1].astype('int')],
                                 errors='ignore'),
                    loc='center', facecolor=(1,
                                             1 - concatenated[i, j, 0],
                                             1 - concatenated[i, j, 0]))
    for i, char in enumerate(selected):
        tb.add_cell(0, i, height, width,
                    text=unicode(char, errors='ignore'),
                    loc='center', facecolor='green')
    ax.add_table(tb)

    plt.savefig(ploting_path)
Example #43
0
def test_table_cells():
    fig, ax = plt.subplots()
    table = Table(ax)

    cell = table.add_cell(1, 2, 1, 1)
    assert isinstance(cell, CustomCell)
    assert cell is table[1, 2]

    cell2 = CustomCell((0, 0), 1, 2, visible_edges=None)
    table[2, 1] = cell2
    assert table[2, 1] is cell2

    # make sure gettitem support has not broken
    # properties and setp
    table.properties()
    plt.setp(table)
Example #44
0
def show_interface(result,A,startPos,endPos):
    colors=['white','grey']
    fig=plt.figure(figsize=(10,10))
    ax=plt.subplot(111)    
    ax.set_ylim([0,A.shape[0]])
    ax.set_xlim([0,A.shape[1]])
    ax.set_axis_off()
    tb = Table(ax, bbox=[0,0,1,1])
    nrows, ncols = A.shape
    width, height = 1.0 / ncols, 1.0 / nrows
    # Add cells
    for (i,j),val in np.ndenumerate(A):
        color=colors[val]
        tb.add_cell(i, j, width, height,loc='center', facecolor=color)
    # Row Labels...
    for i in range(A.shape[0]):
        tb.add_cell(i, -1, width, height, text=i, loc='right', 
                    edgecolor='none', facecolor='none')
    # Column Labels
    for j in range(A.shape[1]):
        tb.add_cell(-1, j, width, height/2, text=j, loc='center', 
                           edgecolor='none', facecolor='none')
    ax.add_table(tb)
    
    #Ajout Chemin
    for i,j in result[2]:
        ax.add_line(lines.Line2D((i[1],j[1]),(i[0],j[0]),linewidth=3,zorder=1))
    
    #Ajout Depart
    start=startPos[:2][::-1]
    start_circle=Circle(start,radius=0.2,alpha=0.8, color='g',zorder=2,label='Position de Depart')
    ax.add_patch(start_circle)
    
    #Ajout Direction de Depart
    start_dir=startPos[2]
    start_posA=start
    if(start_dir==1):        
        start_posB=(start_posA[0],start_posA[1]-1)
    if(start_dir==2):
        start_posB=(start_posA[0]+1,start_posA[1])
    if(start_dir==3):
        start_posB=(start_posA[0],start_posA[1]+1)
    if(start_dir==4):
        start_posB=(start_posA[0]-1,start_posA[1])    
    arrow=FancyArrowPatch(start_posA,start_posB,arrowstyle='->',color='m',mutation_scale=15.0,lw=2,zorder=3,label='Sens de Depart')
    ax.add_patch(arrow)

    #Ajout Arrivee
    end=endPos[:2][::-1]
    end_circle=Circle(end,radius=0.2,alpha=0.9, color='r',zorder=2,label='Position d\'arrivee')
    ax.add_patch(end_circle)
    
    ax.invert_yaxis()
    ax.legend(bbox_to_anchor=(1.1, 1.05))
    plt.show()
Example #45
0
def sort_fellows_table_nproj_pdf(names, jobs, companies, subjects, unis, degs, name_plot):

    table = OrderedDict((
    ('Name',names),
    ('Job',jobs),
    ('Company',companies),
    ('Subject',subjects),
    ('University', unis),
    ('Degree',degs)))

    Headn = ['Name','Job','Company', 'Subject','University','Degree']
    data = pandas.DataFrame(table)

    #print data
    
    fig, ax = plt.subplots()
    ax.set_axis_off()
    tb = Table(ax, bbox=[0,0,1,1])

    nrows, ncols = data.shape
 
    #fig = plt.figure(figsize=(5, 20))
    width, height = 1.0 / (ncols), 1.0 / (nrows)
    matplotlib.rcParams.update({'font.size': 20})
    print nrows, ncols
    # Add cells
    print data[Headn[1]].iloc[0]

    for i in range(0,ncols):
        for j in range(0,nrows-1):
            txt = "\n".join(wrap(data[Headn[i]].iloc[j], 40))
            color = "white"
            tb.add_cell(j, i, width, height, text=txt, 
                    loc='center', facecolor="white")

    # Row Labels...
    for i in range(0,nrows-1):
        label = str(i)
        tb.add_cell(i, -1, width, height, text=label, loc='right', 
                    edgecolor='black', facecolor='lightblue')
    # Column Labels...
    for j, label in enumerate(data.columns):
        tb.add_cell(-1, j, width, height/2.0, text=label, loc='center', 
                           edgecolor='black', facecolor='lightcoral')
    ax.add_table(tb)
    plt.savefig(name_plot+'.pdf', bbox_inches = "tight")
    return ''
Example #46
0
def draw_lat_matrix(fname,data,title="",lat_type=None,lat_types=None,columns=[],rows=[]):
    bkg_colors=['#CCFFFF','white']
    fmt='{:.3f}'
    fig,ax=plt.subplots()
    ax.set_axis_off()
    tb=Table(ax,bbox=[0,0,1,1])
    nrows,ncols=data.shape
    assert nrows==len(rows)
    assert ncols==len(columns)
    width, height = 1.0 / ncols * 2, 1.0 / nrows * 2 
    for (i,j),val in np.ndenumerate(data):
        idx = [j % 2, (j + 1) % 2][i % 2]
        color = bkg_colors[idx]
        if val:
            if lat_type:
                txt=fmt.format(ls.exec_fn(val,lat_type))
            else:
                assert lat_types
                txt=fmt.format(ls.exec_fn(val,lat_types[i]))
        else:
            txt="-"
        tb.add_cell(i, j, width, height, text=txt, 
                loc='center', facecolor=color)
    # Row Labels...
    for i, label in enumerate(rows):
        tb.add_cell(i, -1, width, height, text=label, loc='right', 
                edgecolor='none', facecolor='none')
    # Column Labels...
    for j, label in enumerate(columns):
        tb.add_cell(-1, j, width, height/2, text=label, loc='center', 
                edgecolor='none', facecolor='none')
    ax.add_table(tb)

    if title:
        ax.set_title("\n".join(wrap(title)), y=1.08)
    savefig('../figs/' + fname +'.pdf', bbox_inches='tight')
    plt.close()
Example #47
0
class Interface():
    def __init__(self,figsize=(6,6)):
        self.figsize=figsize
        self.size_slider=IntSlider(description='Grid Size',min=4,max=50)
        display(self.size_slider)

        self.nb_ob_slider=IntSlider(description='Obstacles',min=0,max=7)
        display(self.nb_ob_slider)

        self.gen_inst_button=Button(description='Generate Instance',margin=10)
        self.gen_pos_button=Button(description='Generate Start/End Positions',margin=10)
        self.gen_path_button=Button(description='Generate Path',margin=10)
        self.inst_but_container=HBox(children=[self.gen_inst_button,self.gen_pos_button,self.gen_path_button])
        self.inst_but_container.width = '100%'
        display(self.inst_but_container)


        self.show_path_button=Latex(value='Path: Value:  Actions:',margin=10)
        display(self.show_path_button)

        self.size_slider.on_trait_change(self._on_size_slider_change,'value')
        self.gen_inst_button.on_click(self._on_gen_inst_button_click)
        self.gen_pos_button.on_click(self._on_pos_button_click)
        self.gen_path_button.on_click(self._on_gen_path_button_click)
        
        self.gen_path_button.disabled=True
        self.gen_pos_button.disabled=True
            
        plt.close()
        plt.axis('off')
        self.fig=plt.figure(figsize=self.figsize)
        self.ax=self.fig.add_subplot(111)
        

    def _on_size_slider_change(self,name,value):
        self.nb_ob_slider.max=int(value)**2/2-4 #Constrain on number of obstacles
    
    def _on_gen_inst_button_click(self,b):
        self.gen_path_button.disabled=True
        self.gen_pos_button.disabled=False
            
        self.show_path_button.value='Path: Value:  Actions:'

        for line in self.ax.lines:
            line.set_visible(False)
            del(line)
        #Instance Generation
        self.M=self.size_slider.value
        self.nb_ob=self.nb_ob_slider.value
        
        self.A=gen_rand_instance(self.M,self.M,self.nb_ob)
        
        self.G=gen_graph(self.A)
               
        
        if hasattr(self, 'ax'):
        #    print self.ax
            self.ax.cla()
        if hasattr(self, 'start_circle'):
            del(self.start_circle)
            del(self.end_circle)
            del(self.arrow)


        
        colors=['white','grey']
        self.ax.set_ylim([0,self.A.shape[0]])
        self.ax.set_xlim([0,self.A.shape[1]])
        self.ax.set_axis_off()
        self.tb = Table(self.ax, bbox=[0,0,1,1])
        nrows, ncols = self.A.shape
        width, height = 1.0 / ncols, 1.0 / nrows
        # Add cells
        for (i,j),val in np.ndenumerate(self.A):
            color=colors[val]
            self.tb.add_cell(i, j, width, height,loc='center', facecolor=color)
        # Row Labels...
        for i in range(self.A.shape[0]):
            self.tb.add_cell(i, -1, width, height, text=i, loc='right', 
                        edgecolor='none', facecolor='none')
        # Column Labels
        for j in range(self.A.shape[1]):
            self.tb.add_cell(-1, j, width, height/2, text=j, loc='center', 
                               edgecolor='none', facecolor='none')
        self.ax.add_table(self.tb)
        self.ax.invert_yaxis()
        #self.leg=self.ax.legend(bbox_to_anchor=(1.3, 1.05),fancybox=True)
        #self.leg.get_frame().set_alpha(0.5)
        #self.ax.legend()
        plt.show()

        
    def _on_pos_button_click(self,b):
        for line in self.ax.lines:
            line.set_visible(False)
            del(line)
        self.gen_path_button.disabled=False

        self.start,self.end=gen_rand_positions(self.G)
        #Ajout Depart
        start_inst=self.start[:2][::-1]
        #Ajout Direction de Depart
        start_dir=self.start[2]
        start_posA=start_inst
        end_inst=self.end[:2][::-1]
        if(start_dir==1):        
            start_posB=(start_posA[0],start_posA[1]-1)
        if(start_dir==2):
            start_posB=(start_posA[0]+1,start_posA[1])
        if(start_dir==3):
            start_posB=(start_posA[0],start_posA[1]+1)
        if(start_dir==4):
            start_posB=(start_posA[0]-1,start_posA[1]) 
            
        if hasattr(self, 'start_circle'): #deja trace
            self.start_circle.set_visible(True)
            self.end_circle.set_visible(True)
            self.arrow.set_visible(True)
            self.start_circle.center=start_inst
            self.arrow.set_positions(start_posA,start_posB)
            self.end_circle.center=end_inst
            self.show_path_button.value='Path: Value:  Actions:'
            
        else: #jamais trace encore
            #Position de Depart
            self.start_circle=Circle(start_inst,radius=0.5,alpha=0.8, color='g',zorder=2,label='Depart',clip_on=False)
            self.ax.add_patch(self.start_circle)
            #Direction de Depart
            self.arrow=FancyArrowPatch(start_posA,start_posB,arrowstyle='->',color='m',mutation_scale=15.0,lw=2,zorder=3,clip_on=False)
            self.ax.add_patch(self.arrow)
            #Ajout Arrivee

            self.end_circle=Circle(end_inst,radius=0.5,alpha=0.8, color='r',zorder=2,label='Arrivee',clip_on=False)
            self.ax.add_patch(self.end_circle)
            self.leg=self.ax.legend(bbox_to_anchor=(1.1, 1.05),fancybox=True)
            self.leg.get_frame().set_alpha(0.5)
        
        plt.show()
        

        
    def _on_gen_path_button_click(self,b):
        self.gen_path_button.disabled=True

        self.result=gen_shortest_path(self.start,self.end,self.G)
        self.show_path_button.value='Path: Value:  '+str(self.result[0])+' Actions: '+' '.join(e for e in self.result[1])    
    
        #Ajout Chemin
        for i,j in self.result[2]:
            self.ax.add_line(lines.Line2D((i[1],j[1]),(i[0],j[0]),linewidth=3,zorder=1,clip_on=False))
        plt.draw()
Example #48
0
	def shmoo_plotting(self):
		''' pixel register shmoo plot '''
		shmoopdf = PdfPages('shmoo.pdf')
		shmoonp = np.array(self.shmoo_errors)
		data = shmoonp.reshape(len(self.voltages),-1,order='F')
		fig, ax = plt.subplots()
		plt.title('Pixel registers errors')
		ax.set_axis_off()
		fig.text(0.70, 0.05, 'SPI clock (MHz)', fontsize=14)
		fig.text(0.02, 0.90, 'Supply voltage (V)', fontsize=14, rotation=90)
		tb = Table(ax, bbox=[0.01,0.01,0.99,0.99])
		ncols = len(self.bitfiles)
		nrows = len(self.voltages)
		width, height = 1.0 / ncols, 1.0 / nrows
			# Add cells
		for (i,j), val in np.ndenumerate(data):
			color = ''
			if val == 0: color = 'green'
			if (val > 0 & val < 10): color = 'yellow'
			if val > 10: color = 'red'
			tb.add_cell(i, j, width, height, text=str(val),
				loc='center', facecolor=color)
		# Row Labels...
		for i in range(len(self.voltages)):
			tb.add_cell(i, -1, width, height, text=str(self.voltages[i]), loc='right',
						edgecolor='none', facecolor='none')
		# Column Labels...
		for j in range(len(self.bitfiles)):
			newlabel1 = str(self.bitfiles[j][-9:-7]).replace("_","")
			tb.add_cell(nrows+1, j, width, height/2, text=newlabel1, loc='center',
							   edgecolor='none', facecolor='none')
		ax.add_table(tb)
		shmoopdf.savefig()

		''' global register shmoo plot '''
		shmoo_glob_np = np.array(self.shmoo_global_errors)
		data_g = shmoo_glob_np.reshape(len(self.voltages),-1,order='F')
		fig_g, ax_g = plt.subplots()
		ax_g.set_axis_off()
		fig_g.text(0.70, 0.05, 'SPI clock (MHz)', fontsize=14)
		fig_g.text(0.02, 0.90, 'Supply voltage (V)', fontsize=14, rotation=90)
		tb_g = Table(ax_g, bbox=[0.01,0.01,0.99,0.99])
		plt.title('Global registers errors')
		# Add cells
		for (i,j), val_g in np.ndenumerate(data_g):
			color = ''
			if val_g == 0: color = 'green'
			if val_g > 0: color = 'red'
			tb_g.add_cell(i, j, width, height, text=str(val_g),
				loc='center', facecolor=color)
		# Row Labels...
		for i in range(len(self.voltages)):
			tb_g.add_cell(i, -1, width, height, text=str(self.voltages[i]), loc='right',
						edgecolor='none', facecolor='none')
		# Column Labels...
		for j in range(len(self.bitfiles)):
			newlabel = str(self.bitfiles[j][-9:-7]).replace("_","")
			tb_g.add_cell(nrows+1, j, width, height/2, text=newlabel, loc='center',
							   edgecolor='none', facecolor='none')
		ax_g.add_table(tb_g)
		shmoopdf.savefig()
		shmoopdf.close()
    def run(self):
        self.parent.clear_plots()
        if self.data is None:
            self.parent.threadPlot = None
            return

        tMin = format_time(self.extent.tMin, True)
        tMax = format_time(self.extent.tMax, True)
        fMin = format_precision(self.settings, freq=self.extent.fMin,
                                fancyUnits=True)
        fMax = format_precision(self.settings, freq=self.extent.fMax,
                                fancyUnits=True)
        lMin = format_precision(self.settings, level=self.extent.lMin,
                                fancyUnits=True)
        lMax = format_precision(self.settings, level=self.extent.lMax,
                                fancyUnits=True)
        peak = self.extent.get_peak_flt()
        peakF = format_precision(self.settings, freq=peak[0],
                                 fancyUnits=True)
        peakL = format_precision(self.settings, level=peak[1],
                                 fancyUnits=True)
        peakT = format_time(peak[2], True)

        text = [['Sweeps', '', len(self.data)],
                ['Extents', '', ''],
                ['', 'Start', tMin],
                ['', 'End', tMax],
                ['', 'Min frequency', fMin],
                ['', 'Max frequency', fMax],
                ['', 'Min level', lMin],
                ['', 'Max level', lMax],
                ['Peak', '', ''],
                ['', 'Level', peakL],
                ['', 'Frequency', peakF],
                ['', 'Time', peakT],
                ]

        table = Table(self.axes, loc='center', gid='table')

        rows = len(text)
        cols = len(text[0])
        for row in xrange(rows):
            for col in xrange(cols):
                table.add_cell(row, col,
                               text=text[row][col],
                               width=1.0 / cols, height=1.0 / rows)

        if self.settings.grid:
            colour = 'LightGray'
        else:
            colour = 'w'
        set_table_colour(table, colour)

        for i in range(3):
            table.auto_set_column_width(i)

        self.axes.add_table(table)
        noData = find_artists(self.axes, 'noData')
        noData[0].set_alpha(0)
        self.parent.redraw_plot()

        self.parent.threadPlot = None
Example #50
0
def table_plot(df, figsize=(12, 9), value_format='text', fontsize=None, 
               positive_color=None, negative_color=None, header_color=None, index_color=None, 
               fill_color=None, positive_fill_color=None, negative_fill_color=None, 
               header_fill_color=None, index_fill_color=None, title=None, decimals=2, **kwargs):
    """
    Plot DataFrame as a table

    Parameters
    ----------
    df : DataFrame
        Data to be plotted as a table
    figsize : tuple, optional
        2-ple of (x, y) dimensions for figures in inches
    value_format : string, optional
        Format of the table values. Options supported are 'text' and 'numeric'.
    fontsize : int, optional
        Font size
    positive_color : string, optional
        Color to print positive values
    negative_color : string, optional
        Color to print negative cells
    header_color : string, optional
        Color to print header values
    index_color : string, optional
        Color to print index values
    fill_color : string, optional
        Color to fill table cells
    positive_fill_color : string, optional
        Color to fill cells with positive values
    negative_fill_color : string, optional
        Color to fill cells with negative values
    header_fill_color : string, optional
        Color to fill header cells
    index_fill_color : string, optional
        Color to fill index cells
    title : string, optional
        Table title
    decimals : int, optional
        If value_format is numeric, the number of decimal places used to round values

    Returns
    -------
    fig : Figure
        Figure containing the table plot
    """
    if not isinstance(df, pd.DataFrame):
        raise TypeError('df should be a DataFrame object')    
    if value_format not in ['text', 'numeric']:
        raise ValueError('%s is not a valid format' % value_format)

    # draw table
    fig, ax = plt.subplots(figsize=figsize)
    ax.set_axis_off()
    tb = Table(ax, bbox=[0, 0, 1, 1])
    num_cols, num_rows = len(df.columns), len(df.index)
    width, height = 1.0 / num_cols, 1.0 / num_rows

    # add table cells
    loc='center'
    for (i, j), val in np.ndenumerate(df):
        value = df.iloc[i, j]
        text_color = 'black' 
        cell_color = 'none'
        if fill_color is not None:
            cell_color = fill_color            
        if isinstance(value, int) or isinstance(value, float):
            if np.isnan(value):
                continue
            if positive_color is not None and value >= 0:
                text_color = positive_color
            if positive_fill_color is not None and value >= 0:
                cell_color = positive_fill_color
            if negative_color is not None and value < 0:
                text_color = negative_color
            if negative_fill_color is not None and value < 0:
                cell_color = negative_fill_color
            if value_format == 'text':
                tb.add_cell(i + 1, j + 1, width, height, text=str(val), loc=loc, facecolor=cell_color)
            elif value_format == 'numeric':
                value_str = str(round(val, decimals))
                tb.add_cell(i + 1, j + 1, width, height, text=value_str, loc=loc, facecolor=cell_color)
            tb._cells[(i+1, j+1)]._text.set_color(text_color)
        elif isinstance(value, pd.tslib.Timestamp):
            tb.add_cell(i + 1, j + 1, width, height, text=val.strftime('%d-%b-%Y'), loc=loc, facecolor=cell_color)
            tb._cells[(i+1, j+1)]._text.set_color(text_color)
        else:
            tb.add_cell(i + 1, j + 1, width, height, text=str(val), loc=loc, facecolor=cell_color)
            tb._cells[(i+1, j+1)]._text.set_color(text_color)
            
    if index_color is None:
        index_color='black'
    if index_fill_color is not None:
        cell_color = index_fill_color 
    else:
        cell_color = 'none'
    # row labels
    for i, label in enumerate(df.index):
        tb.add_cell(i + 1, 0, width, height, text=label, loc=loc, edgecolor='none', facecolor=cell_color)
        tb._cells[(i+1, 0)]._text.set_color(index_color)

    if header_color is None:
        header_color='black'
    if header_fill_color is not None:
        cell_color = header_fill_color
    else:
        cell_color = 'none'
    # column labels
    for j, label in enumerate(df.columns):
        tb.add_cell(0, j + 1, width, height, text=label, loc=loc, edgecolor='none', facecolor=cell_color)
        tb._cells[(i+1, 0)]._text.set_color(header_color)

    # set font size
    if fontsize is not None:
        tb_cells = tb.properties()['child_artists']
        for cell in tb_cells:
            cell.set_fontsize(fontsize)
    
    # add table to figure        
    ax.add_table(tb)
    
    # set title
    if title is not None:
        if fontsize is not None:
            ax.set_title(title, fontsize=fontsize)
        else:
            ax.set_title(title)
            
    plt.tight_layout()
    
    return fig
Example #51
0
	def shmoo_plotting(self):
		''' pixel register shmoo plot '''
		shmoopdf = PdfPages('shmoo.pdf')
		shmoonp = np.array(self.shmoo_errors)
		data = shmoonp.reshape(len(self.voltages),-1,order='F')
		fig, ax = plt.subplots()
		plt.title('Pixel registers errors')
		ax.set_axis_off()
		tb = Table(ax, bbox=[0,0,1,1])
		ncols = len(self.bitfiles)
		nrows = len(self.voltages)
		width, height = 1.0 / ncols, 1.0 / nrows
			# Add cells
		for (i,j), val in np.ndenumerate(data):
			color = ''
			if val == 0: color = 'green'
			if (val > 0 & val < 10): color = 'yellow'
			if val > 10: color = 'red'
			tb.add_cell(i, j, width, height, text=str(val),
				loc='center', facecolor=color)
		# Row Labels...
		for i in range(len(self.voltages)):
			tb.add_cell(i, -1, width, height, text=str(self.voltages[i])+'V', loc='right',
						edgecolor='none', facecolor='none')
		# Column Labels...
		for j in range(len(self.bitfiles)):
			freq_label = self.bitfiles[j][-9:-7].translate(None, '_')
			tb.add_cell(nrows+1, j, width, height/2, text=freq_label+' MHz', loc='center',
							   edgecolor='none', facecolor='none')
		ax.add_table(tb)
		shmoopdf.savefig()

		''' global register shmoo plot '''
		shmoo_glob_np = np.array(self.shmoo_global_errors)
		data_g = shmoo_glob_np.reshape(len(self.voltages),-1,order='F')
		fig_g, ax_g = plt.subplots()
		ax_g.set_axis_off()
		tb_g = Table(ax_g, bbox=[0,0,1,1])
		plt.title('Global registers errors')
		# Add cells
		for (i,j), val_g in np.ndenumerate(data_g):
			color = ''
			if val_g == 0: color = 'green'
			if val_g > 0: color = 'red'
			tb_g.add_cell(i, j, width, height, text=str(val_g),
				loc='center', facecolor=color)
		# Row Labels...
		for i in range(len(self.voltages)):
			tb_g.add_cell(i, -1, width, height, text=str(self.voltages[i])+'V', loc='right',
						edgecolor='none', facecolor='none')
		# Column Labels...
		for j in range(len(self.bitfiles)):
			freq_label = self.bitfiles[j][-9:-7].translate(None, '_')
			tb_g.add_cell(nrows+1, j, width, height/2, text=freq_label+' MHz', loc='center',
							   edgecolor='none', facecolor='none')
		ax_g.add_table(tb_g)
		shmoopdf.savefig()
		shmoopdf.close()
Example #52
0
    def plot(self, experiment, **kwargs):
        """Plot a table"""
        
        if not experiment:
            raise util.CytoflowViewError("No experiment specified")
        
        if not self.channel or self.channel not in experiment.data:
            raise util.CytoflowViewError("Must set a channel")            
        
        if not (self.row_facet or self.column_facet):
            raise util.CytoflowViewError("Must set at least one of row_facet "
                                         "or column_facet")
            
        if self.subrow_facet and not self.row_facet:
            raise util.CytoflowViewError("Must set row_facet before using "
                                         "subrow_facet")
            
        if self.subcolumn_facet and not self.column_facet:
            raise util.CytoflowViewError("Must set column_facet before using "
                                         "subcolumn_facet")
            
        if self.row_facet and self.row_facet not in experiment.conditions:
            raise util.CytoflowViewError("Row facet {0} not in the experiment"
                                    .format(self.row_facet))        
            
        if self.subrow_facet and self.subrow_facet not in experiment.conditions:
            raise util.CytoflowViewError("Subrow facet {0} not in the experiment"
                                    .format(self.subrow_facet))  
            
        if self.column_facet and self.column_facet not in experiment.conditions:
            raise util.CytoflowViewError("Column facet {0} not in the experiment"
                                    .format(self.column_facet))  
            
        if self.subcolumn_facet and self.subcolumn_facet not in experiment.conditions:
            raise util.CytoflowViewError("Subcolumn facet {0} not in the experiment"
                                    .format(self.subcolumn_facet))  
            
        if not self.function:
            raise util.CytoflowViewError("Summary function isn't set")
            
        row_groups = np.sort(pd.unique(experiment[self.row_facet])) \
                     if self.row_facet else [None]
                     
        subrow_groups = np.sort(pd.unique(experiment[self.subrow_facet])) \
                        if self.subrow_facet else [None] 
        
        col_groups = np.sort(pd.unique(experiment[self.column_facet])) \
                     if self.column_facet else [None]
                     
        subcol_groups = np.sort(pd.unique(experiment[self.subcolumn_facet])) \
                        if self.subcolumn_facet else [None]


        if self.subset:
            try:
                data = experiment.query(self.subset).data.reset_index()
            except:
                raise util.CytoflowViewError("Subset string '{0}' isn't valid"
                                        .format(self.subset))
                
            if len(data.index) == 0:
                raise util.CytoflowViewError("Subset string '{0}' returned no events"
                                        .format(self.subset))
        else:
            data = experiment.data
            
        group_vars = []
        if self.row_facet: group_vars.append(self.row_facet) 
        if self.subrow_facet: group_vars.append(self.subrow_facet)
        if self.column_facet: group_vars.append(self.column_facet)
        if self.subcolumn_facet: group_vars.append(self.subcolumn_facet)
                
        agg = data.groupby(by = group_vars)[self.channel].aggregate(self.function)

        # agg is a multi-index series; we can get a particular value from it
        # with get(idx1, idx2...)

        row_offset = (self.column_facet != "") + (self.subcolumn_facet != "")        
        col_offset = (self.row_facet != "") + (self.subrow_facet != "")
        
        num_cols = len(col_groups) * len(subcol_groups) + col_offset
        
        fig = plt.figure()
        ax = fig.add_subplot(111)
        
        # hide the plot axes that matplotlib tries to make
        ax.xaxis.set_visible(False)
        ax.yaxis.set_visible(False)
        for sp in ax.spines.itervalues():
            sp.set_color('w')
            sp.set_zorder(0)
        
        loc = 'best'
        bbox = None
        
        t = Table(ax, loc, bbox, **kwargs)
        width = [1.0 / num_cols] * num_cols
        height = t._approx_text_height() * 1.8
        
         
        # make the main table       
        for (ri, r) in enumerate(row_groups):
            for (rri, rr) in enumerate(subrow_groups):
                for (ci, c) in enumerate(col_groups):
                    for (cci, cc) in enumerate(subcol_groups):
                        row_idx = ri * len(subrow_groups) + rri + row_offset
                        col_idx = ci * len(subcol_groups) + cci + col_offset
                        agg_idx = [x for x in (r, rr, c, cc) if x is not None]
                        agg_idx = tuple(agg_idx)
                        if len(agg_idx) == 1:
                            agg_idx = agg_idx[0]
                        t.add_cell(row_idx, 
                                   col_idx,
                                   width = width[col_idx],
                                   height = height,
                                   text = agg.get(agg_idx))
                        
        # row headers
        if self.row_facet:
            for (ri, r) in enumerate(row_groups):
                row_idx = ri * len(subrow_groups) + row_offset
                text = "{0} = {1}".format(self.row_facet, r)
                t.add_cell(row_idx,
                           0,
                           width = width[0],
                           height = height,
                           text = text)
                
        # subrow headers
        if self.subrow_facet:
            for (ri, r) in enumerate(row_groups):
                for (rri, rr) in enumerate(subrow_groups):
                    row_idx = ri * len(subrow_groups) + rri + row_offset
                    text = "{0} = {1}".format(self.subrow_facet, rr)
                    t.add_cell(row_idx,
                               1,
                               width = width[1],
                               height = height,
                               text = text)
                    
        # column headers
        if self.column_facet:
            for (ci, c) in enumerate(col_groups):
                col_idx = ci * len(subcol_groups) + col_offset
                text = "{0} = {1}".format(self.column_facet, c)
                t.add_cell(0,
                           col_idx,
                           width = width[col_idx],
                           height = height,
                           text = text)

        # column headers
        if self.subcolumn_facet:
            for (ci, c) in enumerate(col_groups):
                for (cci, cc) in enumerate(subcol_groups):
                    col_idx = ci * len(subcol_groups) + cci + col_offset
                    text = "{0} = {1}".format(self.subcolumn_facet, c)
                    t.add_cell(1,
                               col_idx,
                               width = width[col_idx],
                               height = height,
                               text = text)                
                        
        ax.add_table(t)
Example #53
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
def mytable(ax, csize=0.04,
    cellText=None, cellColours=None,
    cellLoc='right', colWidths=None,
    rowLabels=None, rowColours=None, rowLoc='left',
    colLabels=None, colColours=None, colLoc='center',
    loc='bottom', bbox=None):
    # Check we have some cellText
    if cellText is None:
        # assume just colours are needed
        rows = len(cellColours)
        cols = len(cellColours[0])
        cellText = [[''] * rows] * cols

    rows = len(cellText)
    cols = len(cellText[0])
    for row in cellText:
        assert len(row) == cols

    if cellColours is not None:
        assert len(cellColours) == rows
        for row in cellColours:
            assert len(row) == cols
    else:
        cellColours = ['w' * cols] * rows

    # Set colwidths if not given
    if colWidths is None:
        colWidths = [1.0/cols] * cols

    # Check row and column labels
    rowLabelWidth = 0
    if rowLabels is None:
        if rowColours is not None:
            rowLabels = [''] * cols
            rowLabelWidth = colWidths[0]
    elif rowColours is None:
        rowColours = 'w' * rows

    if rowLabels is not None:
        assert len(rowLabels) == rows

    offset = 0
    if colLabels is None:
        if colColours is not None:
            colLabels = [''] * rows
            offset = 1
    elif colColours is None:
        colColours = 'w' * cols
        offset = 1

    if rowLabels is not None:
        assert len(rowLabels) == rows

    # Set up cell colours if not given
    if cellColours is None:
        cellColours = ['w' * cols] * rows

    # Now create the table
    table = Table(ax, loc, bbox)
    height = csize

    # Add the cells
    for row in xrange(rows):
        for col in xrange(cols):
            table.add_cell(row+offset, col,
                           width=height, height=height,
                           text=cellText[row][col],
                           facecolor=cellColours[row][col],
                           loc=cellLoc)
    ax.add_table(table)
    return table
Example #55
0
    def run(self):
        self.parent.clear_plots()
        if self.data is None:
            length, tMin, tMax, fMin, fMax, lMin, lMax, peakF, peakL, peakT = ('-',) * 10
        else:
            length = len(self.data)
            tMin = format_time(self.extent.tMin, True)
            tMax = format_time(self.extent.tMax, True)
            fMin = format_precision(self.settings, freq=self.extent.fMin,
                                    fancyUnits=True)
            fMax = format_precision(self.settings, freq=self.extent.fMax,
                                    fancyUnits=True)
            lMin = format_precision(self.settings, level=self.extent.lMin,
                                    fancyUnits=True)
            lMax = format_precision(self.settings, level=self.extent.lMax,
                                    fancyUnits=True)
            peak = self.extent.get_peak_flt()
            peakF = format_precision(self.settings, freq=peak[0],
                                     fancyUnits=True)
            peakL = format_precision(self.settings, level=peak[1],
                                     fancyUnits=True)
            peakT = format_time(peak[2], True)

        text = [['Sweeps', '', length],
                ['Extent', '', ''],
                ['', 'Start', tMin],
                ['', 'End', tMax],
                ['', 'Min frequency', fMin],
                ['', 'Max frequency', fMax],
                ['', 'Min level', lMin],
                ['', 'Max level', lMax],
                ['Peak', '', ''],
                ['', 'Level', peakL],
                ['', 'Frequency', peakF],
                ['', 'Time', peakT],
                ]

        table = Table(self.axes, loc='center')
        table.set_gid('table')

        rows = len(text)
        cols = len(text[0])
        fontProperties = FontProperties()
        fontProperties.set_weight('semibold')
        for row in xrange(rows):
            for col in xrange(cols):
                fp = fontProperties if col == 0 else None
                table.add_cell(row, col,
                               text=text[row][col],
                               fontproperties=fp,
                               width=1.0 / cols, height=1.0 / rows)

        if self.settings.grid:
            colour = 'LightGray'
        else:
            colour = 'w'
        set_table_colour(table, colour)

        for i in range(2):
            table.auto_set_column_width(i)

        self.axes.add_table(table)
        self.parent.redraw_plot()

        self.parent.threadPlot = None
def make_tab_big(value_tab, col_tab, format_type = "cost", \
        cmap = ["#4575b4", "#ffffbf", "#d73027"], figsize = (10,10)):
    """
    
    
    """
    
    measures = list(value_tab.columns)
    
    # User-defined colormap from blue to red, going through a darker colour
    cm2 = mcol.LinearSegmentedColormap.from_list("new", \
        cmap)
    cnorm = mcol.Normalize(vmin = 0, vmax = 1)
    cpick = cm.ScalarMappable(norm = cnorm, cmap = cm2)
    
    fig, ax = plt.subplots()
    ax.set_axis_off()
    
    # Create the table (so that you can avoid colouring the ranks manually)
    tb = Table(ax, bbox=[0,0,1,1])
    
    nrows, ncols = value_tab.shape
    width, height = 1.0 / (ncols+1), 1.0 / (nrows+1)
    
    for (i, j), val in np.ndenumerate(value_tab):
        colour = cpick.to_rgba(col_tab.ix[i, j])
        alpha = 0.7
        colour = (colour[0], colour[1], colour[2], alpha)
        text_colour = "White" #cpick.to_rgba(1 - col_tab.ix[i, j])
        
        # Find the best text colour.  
        # If green is greater than 190/255 then use black.  
        # unless blue is greater than 150/255.  
        
        #[a < 0.9 for (r, g, b, a) in colour]
        if (colour[1] > 190./255) & (colour[2] > 150./255):
            text_colour = "Black"
        
        if np.isnan(val):
            colour = "White"
            text_colour = "Black"
        
        #if measures[j] == "Livestock culled":
        #    format_type = "culled"
        #else:
        #    format_type = "cost"
        
        # Format value string
        formatted_val = formatval(val, measures[j], format_type)
        
        # Add cell to the table
        tb.add_cell(i, j+1, width, height, text = formatted_val, 
                    loc = 'right', facecolor = colour, edgecolor = 'none')
        
        # Set the font colour
        tb._cells[(i, j+1)]._text.set_color(text_colour)
        
    # Columns
    for j, label in enumerate(measures):
        tb.add_cell(-1, j+1, width, height, text=label, loc='center', 
                           edgecolor='none', facecolor='none')
        tb._cells[(-1, j+1)]._text.set_weight('bold')
    
    # 'Control' and 'Model' labels
    tb.add_cell(-1, 0, width, height, text='Model', loc='center', 
                       edgecolor='none', facecolor='none')
    tb._cells[(-1, 0)]._text.set_weight('bold')
    
    tb.add_cell(-1, -1, width, height, text='            Control', loc='center', 
                       edgecolor='none', facecolor='none')
    tb._cells[(-1, -1)]._text.set_weight('bold')
    
    # Rows
    for i, label in enumerate(value_tab.index.labels[1]):
        tb.add_cell(i, 0, width, height, \
        text = value_tab.index.levels[1][label], \
        loc='center', edgecolor='none', facecolor='none')
    
    # Add table to the current axes
    ax.add_table(tb)
    
    # Bigger rows
    controls = [
    "Infected\npremises\nculling\n(IP)",
    "Dangerous\ncontacts\nculling\n(DC)",
    "Ring culling\nat 3km\n(RC)",
    "",
    "",
    "",
    ""]
    
    incr = float(len(controls))
    
    for k, label in enumerate(controls):
        ax.text(-0.05, 1 - (k+1)/incr + 1./15., label, fontsize = 10, \
             horizontalalignment = 'center', verticalalignment = 'center')
        if k < 4:
            pass
        else:
            ax.axhline(k/incr, -0.15, 1,c = "Black", clip_on = False)
    
    ax.axhline(2./incr, -0.15, 1,c = "Black", clip_on = False)
    ax.axhline(0./incr, -0.15, 1,c = "Black", clip_on = False)
    ax.axhline(1, -0.15, 1, c = "Black", clip_on = False)
    
    ax.axhline(3./incr, -0.02, 1,c = "Black", clip_on = False)
    ax.axhline(1./incr, -0.02, 1,c = "Black", clip_on = False)
    
    ax.text(-0.1, 1 - 4./incr, "Vaccinate\n at 3km", \
        fontsize = 10, horizontalalignment = 'center', \
        verticalalignment = 'center')
    
    ax.text(0.01, 1 - 4./incr + 1./15., "to live\n(V3L)", \
        fontsize = 10, horizontalalignment = 'center', \
        verticalalignment = 'center')
    
    ax.text(0.01, 1 - 5./incr + 1./15., "to kill\n(V3K)", \
        fontsize = 10, horizontalalignment = 'center', \
        verticalalignment = 'center')
    
    ax.text(-0.1, 1 - 6./incr, "Vaccinate\n at 10km", \
        fontsize = 10, horizontalalignment = 'center', \
        verticalalignment = 'center')
    
    ax.text(0.01, 1 - 6./incr + 1./15., "to live\n(V10L)", \
        fontsize = 10, horizontalalignment = 'center', \
        verticalalignment = 'center')
    
    ax.text(0.01, 1 - 7./incr + 1./15., "to kill\n(V10K)", \
        fontsize = 10, horizontalalignment = 'center', \
        verticalalignment = 'center')
    
    # Add the extra lines
    #ax.axhline(k/incr, -0.15, 1,c = "Black", clip_on = False)
    
    #ax.text(-0.05, 1 + 1./70 , 'Control', fontsize = 12, fontweight = 'bold',\
    #     horizontalalignment = 'center', verticalalignment = 'center')
    
    fig.set_size_inches(figsize)
    return fig, ax