Ejemplo n.º 1
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
Ejemplo n.º 2
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()
Ejemplo n.º 3
0
    def __make_table(self):
        '''
        Transforms the filter model into a table. This code is based on the code in matplotlib.table
        :return: the table.
        '''
        if len(self.__filter_model) > 0 and self.__magnitude_model is not None:
            fc = self.__magnitude_model.limits.axes_1.get_facecolor()
            cell_kwargs = {}

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

            table = Table(table_axes, **table_loc)
            table.set_zorder(1000)
            self.__add_filters_to_table(table, row_height, cell_kwargs)
            table.auto_set_font_size(False)
            table.set_fontsize(self.tableFontSize.value())
            return table
        return None
Ejemplo n.º 4
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)
Ejemplo n.º 5
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)
Ejemplo n.º 6
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()
Ejemplo n.º 7
0
def checkerboard_table(data, w_path, w_file_name, fmt='{:.2f}'):
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.set_axis_off()
    tb = Table(ax, bbox=[0, 0, 1, 1])

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

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

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

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

    # fig, ax = plt.subplots(figsize=(300, 300))
    # ax.axis('off')
    # ax.axis('tight')
    # ax.table(cellText=data.values, colLabels=data.columns, rowLabels=data.index, loc='center', bbox=[0, 0, 1, 1])
    plt.savefig(w_path + w_file_name)
Ejemplo n.º 8
0
        pilotDict[name] = pilotRow

maxLength = 0
for i in pilotRows:
    if len(i) > maxLength:
        maxLength = len(i)

fig = plt.figure(dpi=150)
ax = fig.add_subplot(1, 1, 1)
frame1 = plt.gca()
frame1.axes.get_xaxis().set_ticks([])
frame1.axes.get_yaxis().set_ticks([])

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

tb.auto_set_font_size(False)

n_cols = maxLength + 2
n_rows = len(pilots) + 1
width, height = 100 / n_cols, 100.0 / n_rows
anchor = '⚓'
#unicorn='✈️'
blankcell = '#1A392A'
colors = ['red', 'orange', 'orange', 'yellow', 'lightgreen']

minDate = data[-1]['ServerDate']
maxDate = data[0]['ServerDate']
textcolor = '#FFFFF0'
edgecolor = '#708090'
cell = tb.add_cell(0,
                   0,
Ejemplo n.º 9
0
    def plot(self, experiment, plot_name = None, **kwargs):
        """Plot a table"""
        
        if experiment is None:
            raise util.CytoflowViewError('experiment', "No experiment specified")   
        
        if self.statistic not in experiment.statistics:
            raise util.CytoflowViewError('statistic', 
                                         "Can't find the statistic {} in the experiment"
                                         .format(self.statistic))
        else:
            stat = experiment.statistics[self.statistic]    
            
        data = pd.DataFrame(index = stat.index)
        data[stat.name] = stat   
        
        if self.subset:
            try:
                data = data.query(self.subset)
            except Exception as e:
                raise util.CytoflowViewError('subset',
                                             "Subset string '{0}' isn't valid"
                                             .format(self.subset)) from e
                
            if len(data) == 0:
                raise util.CytoflowViewError('subset',
                                             "Subset string '{0}' returned no values"
                                             .format(self.subset))
            
        names = list(data.index.names)
        for name in names:
            unique_values = data.index.get_level_values(name).unique()
            if len(unique_values) == 1:
                warn("Only one value for level {}; dropping it.".format(name),
                     util.CytoflowViewWarning)
                try:
                    data.index = data.index.droplevel(name)
                except AttributeError as e:
                    raise util.CytoflowViewError(None,
                                                 "Must have more than one "
                                                 "value to plot.") from e
        
        if not (self.row_facet or self.column_facet):
            raise util.CytoflowViewError('row_facet',
                                         "Must set at least one of row_facet "
                                         "or column_facet")
            
        if self.subrow_facet and not self.row_facet:
            raise util.CytoflowViewError('subrow_facet',
                                         "Must set row_facet before using "
                                         "subrow_facet")
            
        if self.subcolumn_facet and not self.column_facet:
            raise util.CytoflowViewError('subcolumn_facet',
                                         "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',
                                         "Row facet {} not in the experiment, "
                                         "must be one of {}"
                                         .format(self.row_facet, experiment.conditions))        

        if self.row_facet and self.row_facet not in data.index.names:
            raise util.CytoflowViewError('row_facet',
                                         "Row facet {} not a statistic index; "
                                         "must be one of {}"
                                         .format(self.row_facet, data.index.names))  
            
        if self.subrow_facet and self.subrow_facet not in experiment.conditions:
            raise util.CytoflowViewError('subrow_facet',
                                         "Subrow facet {} not in the experiment, "
                                         "must be one of {}"
                                         .format(self.subrow_facet, experiment.conditions))  
            
        if self.subrow_facet and self.subrow_facet not in data.index.names:
            raise util.CytoflowViewError('subrow_facet',
                                         "Subrow facet {} not a statistic index; "
                                         "must be one of {}"
                                         .format(self.subrow_facet, data.index.names))  
            
        if self.column_facet and self.column_facet not in experiment.conditions:
            raise util.CytoflowViewError('column_facet',
                                         "Column facet {} not in the experiment, "
                                         "must be one of {}"
                                         .format(self.column_facet, experiment.conditions))  
            
        if self.column_facet and self.column_facet not in data.index.names:
            raise util.CytoflowViewError('column_facet',
                                         "Column facet {} not a statistic index; "
                                         "must be one of {}"
                                         .format(self.column_facet, data.index.names)) 
            
        if self.subcolumn_facet and self.subcolumn_facet not in experiment.conditions:
            raise util.CytoflowViewError('subcolumn_facet',
                                         "Subcolumn facet {} not in the experiment, "
                                         "must be one of {}"
                                         .format(self.subcolumn_facet, experiment.conditions))  
            
        if self.subcolumn_facet and self.subcolumn_facet not in data.index.names:
            raise util.CytoflowViewError('subcolumn_facet',
                                         "Subcolumn facet {} not a statistic index; "
                                         "must be one of {}"
                                         .format(self.subcolumn_facet, data.index.names))  

        facets = [x for x in [self.row_facet, self.subrow_facet, 
                                      self.column_facet, self.subcolumn_facet] if x]
        if len(facets) != len(set(facets)):
            raise util.CytoflowViewError(None, 
                                         "Can't reuse facets")
        
        if set(facets) != set(data.index.names):
            raise util.CytoflowViewError(None,
                                         "Must use all the statistic indices as variables or facets: {}"
                                         .format(data.index.names))
            
        row_groups = data.index.get_level_values(self.row_facet).unique() \
                     if self.row_facet else [None]
                     
        subrow_groups = data.index.get_level_values(self.subrow_facet).unique() \
                        if self.subrow_facet else [None] 
        
        col_groups = data.index.get_level_values(self.column_facet).unique() \
                     if self.column_facet else [None]
                     
        subcol_groups = data.index.get_level_values(self.subcolumn_facet).unique() \
                        if self.subcolumn_facet else [None]

        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.values():
            sp.set_color('w')
            sp.set_zorder(0)
        
        loc = 'upper left'
        bbox = None
        
        t = Table(ax, loc, bbox, **kwargs)
        t.auto_set_font_size(False)
        for c in range(num_cols):
            t.auto_set_column_width(c)

        width = [0.2] * 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
                        
                        # this is not pythonic, but i'm tired
                        agg_idx = []
                        for data_idx in data.index.names:
                            if data_idx == self.row_facet:
                                agg_idx.append(r)
                            elif data_idx == self.subrow_facet:
                                agg_idx.append(rr)
                            elif data_idx == self.column_facet:
                                agg_idx.append(c)
                            elif data_idx == self.subcolumn_facet:
                                agg_idx.append(cc)
                        
                        agg_idx = tuple(agg_idx)
                        if len(agg_idx) == 1:
                            agg_idx = agg_idx[0]
                            
                        try:
                            text = "{:g}".format(data.loc[agg_idx][stat.name])
                        except ValueError:
                            text = data.loc[agg_idx][stat.name]
                        t.add_cell(row_idx, 
                                   col_idx,
                                   width = width[col_idx],
                                   height = height,
                                   text = text)
                        
        # row headers
        if self.row_facet:
            for (ri, r) in enumerate(row_groups):
                row_idx = ri * len(subrow_groups) + row_offset
                try:
                    text = "{0} = {1:g}".format(self.row_facet, r)
                except ValueError:
                    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
                    try:
                        text = "{0} = {1:g}".format(self.subrow_facet, rr)
                    except ValueError:
                        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
                try:
                    text = "{0} = {1:g}".format(self.column_facet, c)
                except ValueError:
                    text = "{0} = {1}".format(self.column_facet, c)
                t.add_cell(0,
                           col_idx,
                           width = width[col_idx],
                           height = height,
                           text = text)

        # subcolumn 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
                    try:
                        text = "{0} = {1:g}".format(self.subcolumn_facet, cc)
                    except ValueError:
                        text = "{0} = {1}".format(self.subcolumn_facet, cc)
                    t.add_cell(1,
                               col_idx,
                               width = width[col_idx],
                               height = height,
                               text = text)                
                        
        ax.add_table(t)
Ejemplo n.º 10
0
def plotDefaultBoard(pilotRows, options):
    maxLength = 0
    for i in pilotRows:
        if len(i) > maxLength:
            maxLength = len(i)

    if maxLength < 17:
        maxLength = 17

    fig = plt.figure(dpi=150)
    ax = fig.add_subplot(1, 1, 1)
    frame1 = plt.gca()
    frame1.axes.get_xaxis().set_ticks([])
    frame1.axes.get_yaxis().set_ticks([])

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

    tb.auto_set_font_size(False)

    n_cols = maxLength + 2
    n_rows = len(pilots) + 1
    width, height = 100 / n_cols, 100.0 / n_rows
    anchor = '⚓'
    goldstar = '⭐'
    goldstar = '★'
    case3 = '•'
    case3 = '◉'
    case2 = '⊙'
    case2 = '○'
    #case2 = '○'
    #case2 = '∘'
    #unicorn='✈️'
    blankcell = '#1A392A'

    #colors=['red','orange','orange','yellow','lightgreen']  #078a21
    #colors=['#a00000','#835C3B','#d17a00','#b6c700','#0bab35','#057718','#057718']
    colors = [
        '#a00000', '#d17a00', '#d17a00', '#b6c700', '#0bab35', '#057718',
        '#057718'
    ]

    redcolor = '#a00000'
    browncolor = '#835C3B'
    orangecolor = '#d17a00'
    yellowcolor = '#b6c700'
    greencolor = '#0bab35'

    # try:
    #     minDate = data[-1]['ServerDate']
    #     maxDate = data[0]['ServerDate']
    # except:
    #     minDate =''
    #     maxDate = ''

    textcolor = '#FFFFF0'
    edgecolor = '#708090'
    cell = tb.add_cell(0,
                       0,
                       5 * width,
                       height,
                       text='Callsign',
                       loc='center',
                       facecolor=blankcell)  #edgecolor='none'
    cell.get_text().set_color(textcolor)
    cell.set_text_props(fontproperties=FontProperties(weight='bold', size=8))
    cell.set_edgecolor(edgecolor)

    #cell.set_fontsize(24)
    cell = tb.add_cell(0,
                       1,
                       width,
                       height,
                       text='',
                       loc='center',
                       facecolor=blankcell)  #edgecolor='none'
    cell.get_text().set_color(textcolor)
    cell.set_edgecolor(edgecolor)
    cell.set_text_props(fontproperties=FontProperties(weight='bold', size=8))
    cell.set_edgecolor(edgecolor)
    #cell.set_fontsize(24)

    currentMonth = datetime.now().month
    titlestr = ' JOINT OPS WING'  #+ str(currentMonth) + '/' + str(datetime.now().year)

    print(titlestr)
    count = 0
    for col_idx in range(2, maxLength + 2):

        text = ''

        if count < len(titlestr):
            text = titlestr[count]
            count = count + 1
        cell = tb.add_cell(0,
                           col_idx,
                           width,
                           height,
                           text=text,
                           loc='center',
                           facecolor=blankcell)
        cell.set_edgecolor(edgecolor)
        cell.get_text().set_color(textcolor)
        cell.set_text_props(
            fontproperties=FontProperties(weight='bold', size=8))
        cell.set_edgecolor(edgecolor)

    #cell.set_text_props(family='')

#    titlestr = 'JOW Greenie Board ' + minDate + ' to ' + maxDate

    minRows = len(pilots)

    if minRows < 12:
        minRows = 12

    #for p_idx in range(0,len(pilots)):
    for p_idx in range(0, minRows):
        row_idx = p_idx + 1

        rd = []
        name = ''
        scoreText = ''

        if p_idx < len(pilots):
            name = pilots[p_idx]
            rd = pilotRows[name]
            #avg = statistics.mean(rd)
            avg = CalculateAverageScore(rd)
            scoreText = round(avg, 1)
            if name.lower() == 'eese':
                name = "SippyCup"

        cell = tb.add_cell(row_idx,
                           0,
                           5 * width,
                           height,
                           text=name,
                           loc='center',
                           facecolor=blankcell,
                           edgecolor='blue')  #edgecolor='none'
        cell.get_text().set_color(textcolor)
        cell.set_text_props(
            fontproperties=FontProperties(weight='bold', size="7.5"))
        cell.set_edgecolor(edgecolor)
        #    name = pilots[p_idx];

        cell = tb.add_cell(row_idx,
                           1,
                           width,
                           height,
                           text=scoreText,
                           loc='center',
                           facecolor=blankcell)
        cell.get_text().set_color(textcolor)
        cell.set_text_props(
            fontproperties=FontProperties(weight='bold', size="7.4"))
        cell.set_edgecolor(edgecolor)
        col_idx = 2

        for g in rd:
            color = g['bg']
            text = ''

            if '3' in g['icon'] and '5' in g['icon']:
                text = goldstar
            elif '3' in g['icon']:
                text = case3
            elif '5' in g['icon']:
                text = anchor
            elif '2' in g['icon']:
                text = case2

            cell = tb.add_cell(row_idx,
                               col_idx,
                               width,
                               height,
                               text=text,
                               loc='center',
                               facecolor=color)  #edgecolor='none'
            cell.get_text().set_color('#333412')
            # cell.auto_set_font_size()
            cell.set_text_props(
                fontproperties=FontProperties(weight='bold', size="14"))
            cell.set_edgecolor(edgecolor)
            col_idx = col_idx + 1

        color = blankcell
        text = ''

        # add the remaining cells to the end
        for f in range(col_idx, maxLength + 2):
            cell = tb.add_cell(row_idx,
                               f,
                               width,
                               height,
                               text=text,
                               loc='center',
                               facecolor=color)  #edgecolor='none'
            cell.set_edgecolor(edgecolor)

    #tb.set_fontsize(7)
    ax.add_table(tb)
    ax.set_axis_off()
    ax.axis('off')
    plt.box(False)
    ax.get_xaxis().set_ticks([])
    ax.get_yaxis().set_ticks([])
    #plt.title(titlestr,color='w')

    plt.savefig('board.png',
                transparent=False,
                bbox_inches='tight',
                pad_inches=0)
Ejemplo n.º 11
0
def plotSquadron(pilotRows, options):
    #print('PlotSquadron')
    maxLength = 0
    for i in pilotRows:
        if len(i) > maxLength:
            maxLength = len(i)
    if maxLength < options['maxRows']:
        maxLength = options['maxRows']

    fig = plt.figure(figsize=(6, 3), dpi=250)
    ax = fig.add_subplot(1, 1, 1)
    frame1 = plt.gca()
    frame1.axes.get_xaxis().set_ticks([])
    frame1.axes.get_yaxis().set_ticks([])

    tb = Table(ax, bbox=[0, 0, 1, 1])
    #tb.scale(0.25, 1)
    tb.auto_set_font_size(False)
    n_cols = maxLength + 2
    n_rows = len(pilots) + 1
    width, height = 100 / n_cols, 100.0 / n_rows
    #height = height/10
    anchor = '⚓'
    goldstar = '⭐'
    goldstar = '★'
    #unicorn='✈️'
    #case3 = '⚸'
    case3 = '•'
    case2 = '⊙'
    blankcell = '#FFFFFF'
    #colors=['red','orange','orange','yellow','lightgreen']  #078a21
    #colors=['#a00000','#835C3B','#d17a00','#b6c700','#0bab35','#057718','#057718']
    colors = [
        '#a00000', '#d17a00', '#d17a00', '#b6c700', '#0bab35', '#057718',
        '#057718'
    ]

    # redcolor = '#a00000'
    # browncolor = '#835C3B'
    # orangecolor = '#d17a00'
    # yellowcolor = '#b6c700'
    # greencolor = '#0bab35'
    # bluecolor = '#01A2EA'

    try:
        minDate = data[-1]['ServerDate']
        maxDate = data[0]['ServerDate']
    except:
        minDate = ''
        maxDate = ''

    textcolor = '#000000'
    edgecolor = '#708090'
    cell = tb.add_cell(0,
                       0,
                       10 * width,
                       height,
                       text='Callsign',
                       loc='center',
                       facecolor=blankcell)  #edgecolor='none'
    cell.get_text().set_color(textcolor)
    cell.set_text_props(fontproperties=FontProperties(weight='bold', size=8))
    cell.set_edgecolor(edgecolor)
    cell.set_linewidth(0.5)
    #cell.set_fontsize(24)
    cell = tb.add_cell(0,
                       1,
                       width,
                       height,
                       text='',
                       loc='center',
                       facecolor=blankcell)  #edgecolor='none'
    cell.get_text().set_color(textcolor)
    cell.set_edgecolor(edgecolor)
    cell.set_linewidth(0.5)
    cell.set_text_props(fontproperties=FontProperties(weight='bold', size=8))
    cell.set_edgecolor(edgecolor)
    #cell.set_fontsize(24)
    titlestr = ' ' + options['squadron']
    count = 0
    for col_idx in range(2, options['maxCols'] + 2):

        text = ''

        if count < len(titlestr):
            text = titlestr[count]
            count = count + 1
        cell = tb.add_cell(0,
                           col_idx,
                           width,
                           height,
                           text=text.upper(),
                           loc='center',
                           facecolor=blankcell)
        cell.set_linewidth(0.5)
        cell.set_edgecolor(edgecolor)
        cell.get_text().set_color(textcolor)
        cell.set_text_props(
            fontproperties=FontProperties(weight='bold', size=8))
        cell.set_edgecolor(edgecolor)

    #cell.set_text_props(family='')

    #titlestr = 'JOW Greenie Board ' + minDate + ' to ' + maxDate

    minRows = len(pilots)

    if minRows < options['maxRows']:
        minRows = options['maxRows']

    #for p_idx in range(0,len(pilots)):
    for p_idx in range(0, minRows):
        row_idx = p_idx + 1

        rd = []
        name = ''
        scoreText = ''

        if p_idx < len(pilots):
            name = pilots[p_idx]
            rd = pilotRows[name]
            #            avg = statistics.mean(rd)
            avg = CalculateAverageScore(rd)
            scoreText = round(avg, 1)

        cell = tb.add_cell(row_idx,
                           0,
                           10 * width,
                           height,
                           text=name,
                           loc='center',
                           facecolor=blankcell,
                           edgecolor='blue')  #edgecolor='none'
        cell.get_text().set_color(textcolor)
        cell.set_text_props(
            fontproperties=FontProperties(weight='bold', size="7"))
        cell.set_edgecolor(edgecolor)
        cell.set_linewidth(0.5)
        #    name = pilots[p_idx];

        cell = tb.add_cell(row_idx,
                           1,
                           width,
                           height,
                           text=scoreText,
                           loc='center',
                           facecolor=blankcell)
        cell.get_text().set_color(textcolor)
        cell.set_text_props(fontproperties=FontProperties(size="6.0"))
        cell.set_edgecolor(edgecolor)
        cell.set_linewidth(0.5)
        col_idx = 2

        for ij in rd:

            color = ij['bg']

            if not color:
                color = blankcell

            text = ''

            if '3' in ij['icon']:
                text = case3
            elif '2' in ij['icon']:
                text = case2

            cell = tb.add_cell(row_idx,
                               col_idx,
                               width,
                               height,
                               text=text,
                               loc='center',
                               facecolor=color)  #edgecolor='none'
            cell.get_text().set_color('#333412')
            cell.set_linewidth(0.5)
            # cell.auto_set_font_size()
            cell.set_text_props(
                fontproperties=FontProperties(weight='bold', size="14"))
            cell.set_edgecolor(edgecolor)
            col_idx = col_idx + 1

        color = blankcell
        text = ''

        # add the remaining cells to the end
        for f in range(col_idx, options['maxCols'] + 2):
            cell = tb.add_cell(row_idx,
                               f,
                               width,
                               height,
                               text=text,
                               loc='center',
                               facecolor=color)  #edgecolor='none'
            cell.set_linewidth(0.5)
            cell.set_edgecolor(edgecolor)

    #
    #tb.set_fontsize(7)
    ax.add_table(tb)
    ax.set_axis_off()
    ax.axis('off')
    plt.box(False)
    ax.get_xaxis().set_ticks([])
    ax.get_yaxis().set_ticks([])
    #plt.title(titlestr,color='w')

    plt.savefig('board.png',
                transparent=False,
                bbox_inches='tight',
                pad_inches=0)
Ejemplo n.º 12
0
class TableAxis(object):
    def __init__(self, ax, df, colors):
        self._ax = ax
        self._df = df
        self._colors = colors

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

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

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

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

    def _add_cells(self):
        raise NotImplementedError()

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

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

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

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

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

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

    # end of def

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

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

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

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

    # end of def

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

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

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

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

        if experiment is None:
            raise util.CytoflowViewError('experiment',
                                         "No experiment specified")

        if self.subset:
            try:
                experiment = experiment.query(self.subset)
            except Exception as e:
                raise util.CytoflowViewError(
                    'subset', "Subset string '{0}' isn't valid".format(
                        self.subset)) from e

            if len(experiment) == 0:
                raise util.CytoflowViewError(
                    'subset', "Subset string '{0}' returned no values".format(
                        self.subset))

        # if path is set, actually do an export. this isn't terribly elegant,
        # but this is the only place we have an experiment! ExportFCS.export()
        # raises CytoflowViewErrors, so it should be compatible with the
        # existing error reporting stuff.
        if self.path:
            self.export(experiment)
            return

        # otherwise, make a table showing what will be exported
        num_cols = len(self.by) + 2

        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.values():
            sp.set_color('w')
            sp.set_zorder(0)

        loc = 'upper left'
        bbox = None

        t = Table(ax, loc, bbox)
        t.auto_set_font_size(False)
        for c in range(num_cols):
            t.auto_set_column_width(c)

        width = [0.2] * num_cols

        height = t._approx_text_height() * 1.8

        t.add_cell(0, 0, width=width[0], height=height, text="#")
        for ci, c in enumerate(self.by):
            ci = ci + 1
            t.add_cell(0, ci, width=width[ci], height=height, text=c)

        ci = len(self.by) + 1
        t.add_cell(0, ci, width=width[ci], height=height, text="Filename")

        #         ci = len(self.by) + 2
        #         t.add_cell(0, ci, width = width[ci], height = height, text = "Events")

        for ri, row in enumerate(self.enum_conditions_and_files(experiment)):
            t.add_cell(ri + 1,
                       0,
                       width=width[0],
                       height=height,
                       text="{:g}".format(ri + 1))
            for ci, col in enumerate(row):
                t.add_cell(ri + 1,
                           ci + 1,
                           width=width[ci + 1],
                           height=height,
                           text=col)

        ax.add_table(t)