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
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 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 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)
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
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
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("---------------")
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)