def compplotfreqresps(jsonfilelist, fignum=444, figname="freqfigdiff", compress=1): """ plot the errors in the freqresp for various configurations Parameters: ----------- jsonfilelist : list of json files as produced by `btu.compare_freqresp` """ import matplotlib.cm as cm fig = plt.figure(fignum) ax1 = fig.add_subplot(111) collin = np.linspace(0.2, 0.7, len(jsonfilelist)) for k, jsfstr in enumerate(jsonfilelist): jsf = dou.load_json_dicts(jsfstr) tmesh = jsf["tmesh"] redinds = range(0, len(tmesh), compress) redina = np.array(redinds) outsig = np.array(jsf["diffsysfr"]) curline, = ax1.plot( np.array(tmesh)[redina], outsig[redina], c=cm.CMRmap(collin[k]), linewidth=2.0, label="{0}".format(k) ) handles, labels = ax1.get_legend_handles_labels() ax1.legend(handles, labels, loc="lower left") tikz_save(figname + "{0}".format(fignum) + ".tikz", figureheight="\\figureheight", figurewidth="\\figurewidth") print "saved to " + figname + "{0}".format(fignum) + ".tikz" ax1.semilogx() ax1.semilogy() fig.show()
def compplot_deviations(jsonfilelist, fignum=333, figname="figdiff", compress=10): """ compute the deviations of the measured output from the stable state output """ import matplotlib.cm as cm fig = plt.figure(fignum) ax1 = fig.add_subplot(111) diffnormlist = [] collin = np.linspace(0.2, 0.7, len(jsonfilelist)) for k, jsfstr in enumerate(jsonfilelist): jsf = dou.load_json_dicts(jsfstr) tmesh = jsf["tmesh"] redinds = range(0, len(tmesh), compress) redina = np.array(redinds) outsig = np.array(jsf["outsig"]) # two norm at the differences outsigdiff = np.sqrt(((outsig - outsig[0, :]) * (outsig - outsig[0, :])).sum(axis=1)) diffnormlist.append((tmesh[-1] - tmesh[0]) / len(tmesh) * outsigdiff.sum()) curline, = ax1.plot( np.array(tmesh)[redina], outsigdiff[redina], c=cm.CMRmap(collin[k]), linewidth=2.0, label="{0}".format(k) ) handles, labels = ax1.get_legend_handles_labels() ax1.legend(handles, labels, loc="lower right") tikz_save(figname + "{0}".format(fignum) + ".tikz", figureheight="\\figureheight", figurewidth="\\figurewidth") print "saved to " + figname + "{0}".format(fignum) + ".tikz" fig.show() print diffnormlist print len(tmesh)
def saveTikzPng(filename, watermark=None, thesis=False, show=False): if watermark is not None: plt.gcf().text(0.125, 0.9, watermark, fontsize=8) filename_png = filename + '.png' filename_pdf = filename + '.pdf' fig = plt.gcf() # plt.plot() d = os.getcwd() figure_folder = os.path.join(d, 'figures') tex_folder = os.path.join(d, 'tex') if not os.path.exists(tex_folder): os.makedirs(tex_folder) if not os.path.exists(figure_folder): os.makedirs(figure_folder) tikz_save( tex_folder + "/" + filename + '.tex', figureheight='\\figureheight', figurewidth='\\figurewidth' ) if thesis == False: fig.savefig(figure_folder + "/" + filename_png, format='png', dpi=600, bbox_inches='tight') else: fig.savefig(figure_folder + "/" + filename_pdf, format='pdf', dpi=600, bbox_inches='tight') fig.savefig(figure_folder + "/" + filename_png, format='png', dpi=600, bbox_inches='tight') if show == True: plt.show()
def perf_profile(): erreur_abs=[0,2,5,10,15,20,25] #erreur relative! wpp1=[91.8,91.8,95.9,100,100,100,100] wpp2=[95.9,95.9,97.9,100,100,100,100] #wpp3=[] #dsatur1=[93.1,93.1,93.1,96.5,96.5,100,100] dsatur2=[97.9,97.9,97.9,100,100,100,100] #szekeres=[89.6,89.6,93.1,96.5,96.5,100,100] #rlf1=[93.1,93.1,93.1,96.5,96.5,100,100] rlf2=[97.9,97.9,97.9,100,100,100,100] plt.xlim(-0.2,15) plt.ylim(87,102) plt.xlabel("Relative error compared to optimal solution") plt.ylabel("Proportion of tests solved") plt.title("Performance profile, |V|=25") plot1,=plt.plot(erreur_abs,wpp1,'^-',color='0.3') plot2,=plt.plot(erreur_abs,wpp2,'s-',color='0.3') #plot3,=plt.plot(erreur_abs,dsatur1,'o--',color='g') plot4,=plt.plot(erreur_abs,dsatur2,'v-',color='0.3') #plot5,=plt.plot(erreur_abs,szekeres,'v--',color='y') #plot6,=plt.plot(erreur_abs,rlf1,'<--',color='c') plot7,=plt.plot(erreur_abs,rlf2,'s-',color='0.3') plt.legend([plot1,plot2,plot4,plot7], ["WP1","WP2","DSAT","RLF"],loc="lower right") tikz_save('/Users/romainmontagne/Desktop/Projet/article/article v3/perf_profile2.tikz', figureheight = '\\figureheight', figurewidth = '\\figurewidth')
def save_records_plot(file_path, ls_monitors, name, n_train_batches, legend_loc="upper right"): """ Save a plot of a list of monitors' history. Args: file_path (string): the folder path where to save the plot ls_monitors: the list of statistics to plot name: name of file to be saved n_train_batches: the total number of training batches """ lines = ["--", "-", "-.", ":"] linecycler = cycle(lines) plt.figure() for m in ls_monitors: X = [i / float(n_train_batches) for i in m.history_minibatch] Y = m.history_value a, b = zip(*sorted(zip(X, Y))) plt.plot(a, b, next(linecycler), label=m.name) plt.xlabel('Training epoch') plt.ylabel(ls_monitors[0].type) plt.legend(loc=legend_loc) plt.locator_params(axis='y', nbins=7) plt.locator_params(axis='x', nbins=10) plt.savefig(file_path + name + ".png") tikz_save(file_path + name + ".tikz", figureheight='\\figureheighttik', figurewidth='\\figurewidthtik')
def roc_curve_per_phone(far, frr, inv_phn_map, out_file=None): far_p = far * 100 frr_p = frr * 100 fig, ax = plt.subplots() ax.get_xaxis().set_major_formatter(mpl.ticker.PercentFormatter()) ax.get_yaxis().set_major_formatter(mpl.ticker.PercentFormatter()) plt.xlabel('FRR') plt.ylabel('FAR') line = np.linspace(0, 100, num=len(far)) plt.plot(line, line) legends = [] for i in range(len(far)): if np.any(np.isnan(far[i])): continue legend, = plt.plot(frr_p[i], far_p[i], label=inv_phn_map[i]) legends.append(legend) plt.legend(ncol=2) # plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0., ncol=2) # plt.legend(legends) if out_file: print("Saving plot %s" % out_file) tikz_save(out_file + ".tex") plt.savefig(out_file + ".png") plt.close(fig) else: plt.show()
def plot(tikz,datafiles,save_figures): key = 'symmetric_3_nodes_sib_101010' # ----------------------------------------------------------------------------------------------------------------------------------------------------------------- # plot I(x;z) versus aib iterations after optimizing every node # load results with open(path_results + key + os.sep + 'Results', 'rb') as f: tmp = pickle.load(f) print('Results loaded') f.close() results = tmp.get('results') parameters = tmp.get('params') fig0 = plt.figure(figsize=(7, 5)) ax0 = fig0.add_subplot(111) #do whatever plot you like ;) ... if tikz: tikz_save(path_plots + "....tex") if datafiles: np.savetxt(path_plots + '....rst', list(zip([x_values], [y_values])), delimiter='\t') if save_figures: fig0.savefig(path_plots + '....pdf', bbox_inches='tight', dpi=300, format='pdf')
def save_movie(self, signal, name='movie', path='movies/', **kwargs): from matplotlib2tikz import save as tikz_save directory = path + name if not os.path.isdir(directory): os.makedirs(directory) t = self.vehicles[0].signals['time'] if ('number_of_frames' in kwargs and kwargs['number_of_frames'] <= (t.shape[1]-1)): number_of_frames = kwargs['number_of_frames'] else: number_of_frames = t.shape[1]-1 root = kwargs['root'] if 'root' in kwargs else None figurewidth = kwargs['figurewidth'] if 'figurewidth' in kwargs else '8cm' figureheight = kwargs['figureheight'] if 'figureheight' in kwargs else None subsample = (t.shape[1]-2)/(number_of_frames-1) kwargs['no_update'] = True plot = self.show(signal, **kwargs) cnt = 0 for k in range(0, t.shape[1]-1, subsample): self.update(k, plots=plot) if signal == 'scene': plt.axis('off') path = directory+'/'+name+'_'+str(cnt)+'.tikz' if figureheight is None: tikz_save(path, figurewidth=figurewidth) else: tikz_save(path, figurewidth=figurewidth, figureheight=figureheight) self._cleanup_rubbish(path, root) cnt += 1
def prox_comparison(): import matplotlib.pyplot as plt import StochProxGrad as spg import StochProxMeth as spm import ProxMeth as pm import ProxGrad as pg from matplotlib2tikz import save as tikz_save fval_pm = pm.compute_0sr1(fn, gfn, x0, l_reg = l, tau = 1 / L, batch_size = batch_size) fval_pg = pg.proximal_gradient(fn, gfn, x0, 1 / L, l_reg = l, batch_size = batch_size) fval_spm = spm.compute_0sr1(f, gf, x0, X, y, l_reg = l, tau = 1 / L, batch_size = batch_size) fval_spg = spg.proximal_gradient(f, gf, x0, 1 / L, X, y, l_reg = l, batch_size = batch_size) fval_pm.insert(0, f(x0, X, y)) fval_pg.insert(0, f(x0, X, y)) fval_spm.insert(0, f(x0, X, y)) fval_spg.insert(0, f(x0, X, y)) line1, = plt.plot(range(len(fval_pm)), fval_pm, 'r', label = '0SR1', lw = 2) line2, = plt.plot(range(len(fval_pg)), fval_pg, 'b', label = 'PG', lw = 2) line3, = plt.plot(range(len(fval_spm)), fval_spm, 'g', label = 'S0SR1', lw = 2) line4, = plt.plot(range(len(fval_spg)), fval_spg, 'k', label = 'SPG', lw = 2) #plt.xlim([0, 55]) plt.yscale('log') #plt.ylim([1e1, 1e13]) plt.ylabel('Function Value') plt.xlabel('Number of Iterations') plt.legend(handles = [line1, line2, line3, line4]) tikz_save( 'StochProx_150.tikz' ); return
def save_tex(filename, **kwargs): """ Save figure created with script 'filename' to a tex file using matplotlib2tikz. Output directory is figures/. You can specify a subdirectory using the 'subdir' kwarg. Valid kwargs: addFigureDims and anything passed to matplotlib2tikz.save(). figureheight and -width variables will be added if addFigureDims is true. Pass a 'suffix' if you generate multiple plots from one script. :param filename | __file__ of the plotting script addFigureDims | bool """ from matplotlib2tikz import save as tikz_save import os.path addFigureDims = kwargs.pop("addFigureDims", False) kwargs["figurewidth"] = '\\figurewidth' if addFigureDims else None kwargs["figureheight"] = '\\figureheight' if addFigureDims else None suffix = kwargs.pop("suffix", "") subdir = kwargs.pop("subdir", "") kwargs["tex_relative_path_to_data"] = os.path.join("figures", subdir) if len(subdir): subdir += os.path.sep tikz_save( '../figures/{}{}{}.tex'.format( subdir, os.path.basename(filename).split('.')[0], suffix), **kwargs)
def trainFullPromp(time, Q, Qdot=None, plot_likelihoods=True, **args): args.setdefault('print_lowerbound', plot_likelihoods) args.setdefault('print_inner_lb', False) args.setdefault('max_iter', 10) if 'init_promp' in args: robot_promp = promp.FullProMP.load(args['init_promp']) else: robot_promp = promp.FullProMP(basis=args['new_kernel']) if Qdot is not None: train_summary = robot_promp.train(time, q=Q, qd=Qdot, **args) else: train_summary = robot_promp.train(time, q=Q, **args) np.set_printoptions(precision=4, linewidth=200) print "Mean Weights:\n", robot_promp.mu_w print "Stdev Weights:\n", np.sqrt(np.diag(robot_promp.Sigma_w)) print "Noise stdev:\n", np.sqrt(np.diag(robot_promp.Sigma_y)) print "Basis function params: ", robot_promp.get_basis_pars() if plot_likelihoods: lhoods = train_summary['likelihoods'] #lhoods -= lhoods[0] #Plot improvement from first iteration plt.plot(lhoods) plt.xlabel('Iterations') plt.ylabel('Log-Likelihood') if args['save_lh_plot']: tikz_save(args['save_lh_plot'], figureheight='\\figureheight', figurewidth='\\figurewidth') plt.show() stream = robot_promp.to_stream() fout = file(args['model_fname'], 'w') json.dump(stream, fout) return robot_promp
def train_log_results(): batch_size = 24 a_val = load_tf_log("Final_results/validation/dotprod_shallow.csv") b_val = load_tf_log("Final_results/validation/pyramid.csv") plt.style.use('ggplot') trim = min(a_val[1].shape[0], b_val[1].shape[0]) print(b_val[2]) a_dat = a_val[2] / batch_size b_dat = b_val[2] / batch_size train_loss_a, = plt.plot(a_val[1][:trim], a_dat[:trim], label='Single Dot Product') train_loss_b, = plt.plot(b_val[1][:trim], b_dat[:trim], label='Cosine Similarity Pyramid') plt.xlabel('Epochs') plt.ylabel('Sum of Squared Differences (SSD)') plt.legend(handles=[train_loss_a, train_loss_b]) plt.title('Effect of Cosine Similarity Pyramid (Shallow Network)') tikz_save('../dissertation/pyramid_comparison.tex', figureheight='10cm', figurewidth='14cm') plt.clf()
def save_records_plot(file_path, stats, names, legend_loc="upper right"): """ Save a plot of a list of monitors' history. Args: file_path (string): the folder path where to save the plot ls_monitors: the list of statistics to plot name: name of file to be saved n_train_batches: the total number of training batches """ lines = ["--", "-", "-.", ":"] linecycler = cycle(lines) plt.figure() for i, s in enumerate(stats): X = range(1, len(s) + 1) Y = s a, b = zip(*sorted(zip(X, Y))) plt.plot(a, b, next(linecycler), label=names[i]) plt.xlabel('Training epoch') plt.ylabel(names[len(names) - 1]) plt.legend(loc=legend_loc) plt.locator_params(axis='y', nbins=7) plt.locator_params(axis='x', nbins=10) plt.savefig(file_path + names[len(names) - 1] + ".png") tikz_save(file_path + names[len(names) - 1] + ".tikz", figureheight='\\figureheighttik', figurewidth='\\figurewidthtik')
def save_plot(self, argument=None, name='plot', path='images/', **kwargs): from matplotlib2tikz import save as tikz_save directory = path if not os.path.isdir(directory): os.makedirs(directory) plot = self.plot(argument, **kwargs) info = plot['info'] proj_3d = False for k, _ in enumerate(info): for l, _ in enumerate(info[0]): if ('projection' in info[k][l] and info[k][l]['projection'] == '3d'): proj_3d = True if proj_3d: warnings.warn('3D plotting is not supported by matplotlib2tikz. ' + 'Saving to pdf instead.') path = directory+'/'+name+'.pdf' plt.savefig(path, bbox_inches='tight', pad_inches=0) else: figurewidth = kwargs[ 'figurewidth'] if 'figurewidth' in kwargs else '8cm' figureheight = kwargs[ 'figureheight'] if 'figureheight' in kwargs else None path = directory+'/'+name+'.tikz' if figureheight is None: tikz_save(path, figurewidth=figurewidth) else: tikz_save( path, figurewidth=figurewidth, figureheight=figureheight) _cleanup_rubbish(path, info)
def plt_input_par(data_par, opt=1, I=1): # Create objective space CrSp = createCrSp() # Unpack data par = unpackdatax(data_par) # Open figure fig = plt.figure(I, figsize=(20, 20)) ax = fig.add_subplot(111) # Scatter plot the objective space ax.scatter(CrSp[0], CrSp[1], s=10) # Scatter plot of received data ax.scatter(par[0], par[1], s=40, color='red') # ax.scatter(par[0], par[1], s=30, color='green') # Plot settings plt.xlabel('$x_1$', fontsize=20) plt.ylabel('$x_2$', fontsize=20) plt.title('Crateria space', fontsize=20) if opt == 1: plt.show(block=I) elif opt == 2: fig.savefig('TestImg/plot_input_par_' + str(I) + '.png') plt.close(fig) elif opt == 3: from matplotlib2tikz import save as tikz_save tikz_save('TikzImg/plot_input_par_' + str(I) + '.tikz', figureheight='\\figureheight', figurewidth='\\figurewidth') else: print('No plot option is given.')
def PlotTikZ(filename, plot2save, scale=None): try: from matplotlib2tikz import save as tikz_save import matplotlib except: return if not isinstance(plot2save, matplotlib.figure.Figure): plot2save = plot2save.gcf() try: tikz_save(filename, figure=plot2save, show_info=False, float_format='%.6g') except: tikz_save(filename, figure=plot2save, show_info=False) texfile = open(filename, 'rU' if sys.version_info.major < 3 else 'r') lines = [] for line in texfile: line = line.replace('\xe2\x88\x92', '-') if not scale is None: line = line.replace('begin{tikzpicture}', 'begin{tikzpicture}[scale=' + str(scale) + ']') lines.append(str(line)) texfile.close() texfile = open(filename, 'w') for line in lines: texfile.write(line) texfile.close()
def f_decorated(*args, **kwargs): filename = kwargs.pop('filename', None) if filename: makedirs(os.path.dirname(filename)) ext = os.path.splitext(filename)[1][1:] if filename else None if ext in ('pdf', 'pgf'): # setup fonts using Latin Modern mpl.rcParams.update({ "font.family": ["serif"], "font.serif": ["Latin Modern Roman"], "font.sans-serif": ["Latin Modern Sans"], "font.monospace": ["Latin Modern Mono"] }) elif ext == 'png': mpl.rcParams.update({"savefig.dpi": 240}) f(*args, **kwargs) if filename: if ext == "tikz": from matplotlib2tikz import save as tikz_save tikz_save(filename, figureheight='\\figureheight', figurewidth='\\figurewidth') else: plt.savefig(filename, bbox_inches='tight')
def plot_prs_outp(str_to_json=None, tmeshkey='tmesh', sigkey='outsig', outsig=None, tmesh=None, fignum=222, reference=None, compress=5, tikzfile=None, tikzonly=False): import matplotlib.pyplot as plt if str_to_json is not None: jsdict = load_json_dicts(str_to_json) tmesh = jsdict[tmeshkey] outsig = jsdict[sigkey] else: str_to_json = 'notspecified' redinds = range(1, len(tmesh), compress) redina = np.array(redinds) fig = plt.figure(fignum) ax1 = fig.add_subplot(111) ax1.plot(np.array(tmesh)[redina], np.array(outsig)[redina], color='r', linewidth=2.0) if tikzfile is not None: from matplotlib2tikz import save as tikz_save tikz_save(tikzfile + '.tikz', figureheight='\\figureheight', figurewidth='\\figurewidth' ) print 'tikz saved to ' + tikzfile + '.tikz' if tikzonly: return else: fig.show() return
def save_plot(self, argument=None, name='plot', path='images/', **kwargs): from matplotlib2tikz import save as tikz_save directory = path if not os.path.isdir(directory): os.makedirs(directory) plot = self.plot(argument, **kwargs) info = plot['info'] proj_3d = False for k, _ in enumerate(info): for l, _ in enumerate(info[0]): if ('projection' in info[k][l] and info[k][l]['projection'] == '3d'): proj_3d = True if proj_3d: warnings.warn('3D plotting is not supported by matplotlib2tikz. ' + 'Saving to pdf instead.') path = directory + '/' + name + '.pdf' plt.savefig(path, bbox_inches='tight', pad_inches=0) else: figurewidth = kwargs[ 'figurewidth'] if 'figurewidth' in kwargs else '8cm' figureheight = kwargs[ 'figureheight'] if 'figureheight' in kwargs else None path = directory + '/' + name + '.tikz' if figureheight is None: tikz_save(path, figurewidth=figurewidth) else: tikz_save(path, figurewidth=figurewidth, figureheight=figureheight) _cleanup_rubbish(path, info)
def plot_param_hist(sample, name, prior, bins=30, xlim=None, groundtruth=None, filename=None): plt.cla() plt.ticklabel_format(axis='x', style='plain') plt.axes().get_yaxis().set_ticks([]) if xlim is None: xlim = [np.min(sample), np.max(sample)] binwidth = (xlim[1] - xlim[0]) / bins x = np.arange(xlim[0], xlim[1], binwidth) posterior = np.histogram(sample, x)[0] / (binwidth * sample.shape[0]) plt.plot(0.5 * x[:-1] + 0.5 * x[1:], posterior, 'k.-') plt.plot(x, prior(x), 'k--') plt.xlabel(name) if groundtruth is not None: plt.plot(groundtruth, 0, 'r.') plt.legend(['Posterior', 'Prior', 'Ground truth']) else: plt.legend(['Posterior', 'Prior']) if filename is not None: tikz_save(filename, figureheight='\\figureheight', figurewidth='\\figurewidth')
def plot_collection(values_list, values_names, title="", save_tikz=False, tikz_path=""): plt.style.use('ggplot') worst = np.max(values_list) db = lambda v: 10 * np.log(v / worst) fig, ax = plt.subplots() i = 0 for v in values_list: ax.plot(db(v), label=values_names[i]) i += 1 ax.legend() #ax.title = title plt.xlabel('Iterations') plt.ylabel('Cost Function (log scaled)') plt.show() plt.grid(True) if save_tikz: tikz_save(tikz_path + title + '.tex')
def save_records_plot(file_path, ls_monitors, name, n_train_batches, legend_loc="upper right"): """ Save a plot of a list of monitors' history. Args: file_path (string): the folder path where to save the plot ls_monitors: the list of statistics to plot name: name of file to be saved n_train_batches: the total number of training batches """ lines = ["--", "-", "-.",":"] linecycler = cycle(lines) plt.figure() for m in ls_monitors: X = [i/float(n_train_batches) for i in m.history_minibatch] Y = m.history_value a, b = zip(*sorted(zip(X, Y))) plt.plot(a, b, next(linecycler), label=m.name) plt.xlabel('Training epoch') plt.ylabel(ls_monitors[0].type) plt.legend(loc=legend_loc) plt.locator_params(axis='y', nbins=7) plt.locator_params(axis='x', nbins=10) plt.savefig(file_path + name + ".png") tikz_save(file_path + name + ".tikz", figureheight = '\\figureheighttik', figurewidth = '\\figurewidthtik')
def f_conv_plot(fval_0sr1, fval_prox_grad): """ """ import matplotlib.pyplot as plt from matplotlib2tikz import save as tikz_save fval_0sr1.insert(0, f(x0)) fval_prox_grad.insert(0, f(x0)) fval_l_bfgs_b.insert(0, f_l_bfgs_b(x0_l_bfgs_b)) fval_l_bfgs_b.insert(0, f_l_bfgs_b(x0_l_bfgs_b)) line1, = plt.plot(range(len(fval_0sr1)), fval_0sr1, 'r', label = '0SR1', lw = 2) line2, = plt.plot(range(len(fval_prox_grad)), fval_prox_grad, 'b', label = 'ProxGrad', lw = 2) line3, = plt.plot(range(len(fval_l_bfgs_b)), fval_l_bfgs_b, 'g', label = 'L-BFGS-B', lw = 2) #plt.xscale('log') #plt.xlim([0, 1e2]) plt.yscale('log') #plt.ylim([0, 1e5]) plt.ylabel('Function Value') plt.xlabel('Number of Iterations') plt.legend(handles = [line1, line2, line3]) tikz_save( 'ProxPDE.tikz' ); plt.show() return
def plot_TPR_TNR_ACC(x_axis, TPR, TNR, ACC, xlabel="", ylim=None, log_scale=False): fig = plt.figure(xlabel + " TPR, TNR, AAC") if log_scale: fig.gca().set_xscale("log", nonposx='clip') plt.plot(x_axis, TPR, label="TPR") plt.plot(x_axis, TNR, label="TNR") plt.plot(x_axis, ACC, label="ACC") plt.xlabel(xlabel) plt.ylabel("P") plt.ylim(ylim) plt.legend() block_print() tikz_save("figures/" + xlabel[0:6] + '_TPR_TNR_ACC.tikz') enable_print()
def roc_curve(far, frr, out_file=None): """Plot DET curve from given FAR and FRR rates The FAR rates are expected to be increasing while the FRR rates are expected to be decreasing. """ far_p = far * 100 frr_p = frr * 100 fig, ax = plt.subplots() ax.get_xaxis().set_major_formatter(mpl.ticker.PercentFormatter()) ax.get_yaxis().set_major_formatter(mpl.ticker.PercentFormatter()) plt.xlabel('FRR') plt.ylabel('FAR') line = np.linspace(0, 100, num=len(far)) plt.plot(line, line) plt.plot(frr_p, far_p) if out_file: print("Saving plot %s" % out_file) tikz_save(out_file + ".tex") plt.savefig(out_file + ".png") plt.close(fig) else: plt.show()
def plot_regions(regions, xlim, ylim, tikz=False): """ :param regions: dictionary with name: polytope :param xlim: x axis limits :param ylim: y axis limits :param tikz: generate tikz tex code :return: figure """ fig = plt.figure() ax = fig.add_subplot(111) for name in regions.keys(): patch = matplotlib.patches.Polygon(pc.extreme(regions[name])) lx, ux = pc.bounding_box(regions[name]) # lower and upperbounds over all dimensions #patch = patch_ellips(Meps, pos=None, number=number) ax.add_patch(patch) plt.text(ux[0], ux[1], name) #return #ax.add_patch(patch) plt.xlim(xlim) plt.ylim(ylim) if tikz: from matplotlib2tikz import save as tikz_save tikz_save('regions.tex', figureheight='\\figureheight', figurewidth='\\figurewidth') # plt.tight_layout() plt.show()
def draw_difference_pianoroll(original, predicted, name_1='Original', name_2='Predicted', show=False, save_path=''): if original.shape!=predicted.shape: print("Shape mismatch. Not drawing a plot.") return draw_matrix = original + 2 * predicted cm = colors.ListedColormap(['white', 'blue', 'red', 'black']) bounds=[0,1,2,3,4] n = colors.BoundaryNorm(bounds, cm.N) original_color = cm(1/3) predicted_color = cm(2/3) both_color = cm(1.0) original_patch = mpatches.Patch(color=original_color, label=name_1) predicted_patch = mpatches.Patch(color=predicted_color, label=name_2) both_patch = mpatches.Patch(color=both_color, label='Notes in both songs') plt.figure(figsize=(20.0, 10.0)) plt.title('Difference-Pitch-plot of ' + name_1 + ' and ' + name_2, fontsize=10) plt.legend(handles=[original_patch, predicted_patch, both_patch], loc='upper right', prop={'size': 8}) plt.pcolor(draw_matrix, cmap=cm, vmin=0, vmax=3, norm=n) if show: plt.show() if len(save_path) > 0: plt.savefig(save_path) tikz_save(save_path + ".tex", encoding='utf-8', show_info=False) plt.close()
def visualize_classifier_results(training_ids, test_id, dl, show_classifier=True): if show_classifier: X_train, y_train = dl.load(training_ids, iid=True) X_test, y_test = dl.load([test_id], iid=False) clf = xgb.XGBClassifier(learning_rate=0.1, n_estimators=101, max_depth=3, min_child_weight=3, gamma=0.3, subsample=0.9, colsample_bytree=0.6, scale_pos_weight=1, reg_alpha=0.01, objective='binary:logistic', nthread=data.N_JOBS, random_state=42) clf.fit(X_train, y_train) y_pred = clf.predict(X_test) else: y_pred = None wrist_oxygen, wrist_oxygen_clean, true_oxygen = dl.load_oxygen( test_id, y_pred=y_pred, iid=False) wrist_oxygen = wrist_oxygen[::5] wrist_oxygen_clean = wrist_oxygen_clean[::5] true_oxygen = true_oxygen[::5] if show_classifier: graph_df = pd.concat([wrist_oxygen, true_oxygen, wrist_oxygen_clean], axis=1, sort=True) else: graph_df = pd.concat([wrist_oxygen, true_oxygen], axis=1, sort=True) assert (wrist_oxygen.shape == true_oxygen.shape) assert (graph_df.shape[0] == wrist_oxygen.shape[0]) # plt.figure(figsize=(4 * 1.2, 3 * 1.2)) graph_df.plot.line(figsize=(4 * 1.2, 2 * 1.2)) plt.xlabel("Time (Milliseconds)") plt.ylabel("SpO2 (%)") plt.ylim() plt.legend(loc='lower left') if show_classifier: plt.savefig(data.GRAPH_CACHE + 'classifier-{}-{}.pdf'.format(test_id, str(dl))) tikz_save(data.LTX_CACHE + 'classifier-{}-{}.tex'.format(test_id, str(dl))) else: plt.savefig(data.GRAPH_CACHE + 'algos-{}-{}.pdf'.format(test_id, str(dl)))
def BarPlot( figName, fun0, funOpt, funLabel0, funLabelOpt, xLabel, yLabel, ResultsFolder, OptName, figType=FileTypeRendered, Color0="#FAA43A", ColorOpt="#5DA5DA", figsizex=6, figsizey=3, width=0.5, xspacing=0.25, dpi=200, xtick=True, usetex=False, Tikz=False, ): plt.rc("text", usetex=usetex) Plot = plt.figure(figsize=(figsizex, figsizey), dpi=dpi) ax = Plot.add_subplot(111) nf = np.size(fun0) ind = np.arange(nf) rects1 = ax.bar(ind + xspacing * 2.5, fun0, width, color=Color0) rects2 = ax.bar(ind + xspacing * 2.5 + width / 2, funOpt, width, color=ColorOpt) lgd = ax.legend( (rects1[0], rects2[0]), (funLabel0, funLabelOpt), frameon=False, prop=fontP, bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.0, ) ax.spines["right"].set_visible(False) ax.spines["top"].set_visible(False) ax.yaxis.set_ticks_position("left") ax.xaxis.set_ticks_position("bottom") ax.xaxis.set_major_locator(ticker.MaxNLocator(integer=True)) plt.xlim(xmin=xspacing * 2, xmax=nf + width / 2 + xspacing) plt.ylim(ymin=np.min((np.min(fun0), np.min(funOpt), 0.0)), ymax=np.max((np.max(fun0), np.max(funOpt)))) if xtick == False: plt.tick_params(axis="x", which="both", bottom="off", labelbottom="off") plt.xlabel(xLabel) plt.ylabel(yLabel) plt.tight_layout() for ii in range(np.size(figType)): plt.savefig( ResultsFolder + OptName + "_" + figName + "." + figType[ii], bbox_extra_artists=(lgd,), bbox_inches="tight" ) if Tikz == True: tikz_save(ResultsFolder + OptName + "_" + figName + ".tikz") plt.close() fail = 0 return fail
def plot_outp_sig(str_to_json=None, tmeshkey='tmesh', sigkey='outsig', outsig=None, tmesh=None, fignum=222, reference=None, tikzstr=None, compress=5): import matplotlib.pyplot as plt if str_to_json is not None: jsdict = load_json_dicts(str_to_json) tmesh = jsdict[tmeshkey] outsig = jsdict[sigkey] else: str_to_json = 'notspecified' redinds = list(range(1, len(tmesh), compress)) redina = np.array(redinds) NY = np.int(len(outsig[0]) / 2) fig = plt.figure(fignum) ax1 = fig.add_subplot(111) ax1.plot(np.array(tmesh)[redina], np.array(outsig)[redina, :NY], color='b', linewidth=2.0) ax1.plot(np.array(tmesh)[redina], np.array(outsig)[redina, NY:], color='r', linewidth=2.0) try: from matplotlib2tikz import save as tikz_save if tikzstr is None: tikzstr = str_to_json + '{0}'.format(fignum) tikz_save(tikzstr + '.tikz', figureheight='\\figureheight', figurewidth='\\figurewidth') print('tikz saved to ' + tikzstr + '.tikz') haztikz = True except ImportError: haztikz = False print('cannot save to tikz -- no matplotlib2tikz found') fig.show() if reference is not None: fig = plt.figure(fignum + 1) ax1 = fig.add_subplot(111) ax1.plot(tmesh, np.array(outsig) - reference) if haztikz: tikz_save(str_to_json + '{0}'.format(fignum) + '_difftoref.tikz', figureheight='\\figureheight', figurewidth='\\figurewidth') fig.show()
def save_or_show_plot(name1, name2='', force_show=False, export_tikz=False): if not visualize and not force_show: return filename = JOB_DIR + '/' + name1 + '_id' + str(task_id) + name2 plt.savefig(filename + '.png') if export_tikz: tikz_save(filename + '.tex') plt.close()
def plot_data(df, dof, t, name): group = df.groupby(0) mean_df = group.mean() std_df = group.std(ddof=1) err_df = t * (std_df / math.sqrt(dof)) mean_df.plot(yerr=err_df, capsize=1) #plt.show() tikz_save(name + ".tex")
def EstabilidadeLongitudinal(): # Estabilidade da asa CL_alpha_w = Cl_alpha_w / ( 1 + Cl_alpha_w / (np.pi * AR_w)) # [rad^-1] inclinação da curva CL x alpha na asa CL_0_w = CL_alpha_w * abs( alpha_0) # coeficiente de sustentação com ângulo de ataque zero Cm_0_w = Cm_ac_w + CL_0_w * (x_cg / c_w - x_ac_w / c_w) # [rad^-1] Cm_alpha_w = CL_alpha_w * ( x_cg / c_w - x_ac_w / c_w ) # [rad^-1] inclinação da curva Cm x alpha na asa # Estabilidade da cauda eta = 0.9 # razão de pressões dinâmicas na cauda e na asa E_0 = 2 * CL_0_w / (np.pi * AR_w) # [rad] ângulo de downwash downwash_slope = 2 * CL_alpha_w / ( np.pi * AR_w) # [rad^-1] inclinação do termo de downwash x alpha Cm_0_t = eta * VH * CL_alpha_t * (E_0 + i_w - i_t) # [rad^-1] Cm_alpha_t = -eta * VH * CL_alpha_t * ( 1 - downwash_slope) # [rad^-1] inclinação de Cm x alpha na cauda # Estabilidade total Cm_alpha_total = Cm_alpha_w + Cm_alpha_t Cm_0_total = Cm_0_w + Cm_0_t alpha = np.linspace(0, np.pi / 8.0, 2) y_w = Cm_alpha_w * alpha + Cm_0_w y_t = Cm_alpha_t * alpha + Cm_0_t y_total = Cm_alpha_total * alpha + Cm_0_total print "Cm_alpha ASA:\t%+.3f\nCm_alpha CAUDA:\t%+.3f\nCm_alpha TOTAL:\t%+.3f\t\n" % ( Cm_alpha_w, Cm_alpha_t, Cm_alpha_total) print "Cm_0 ASA:\t%+.3f\nCm_0 CAUDA:\t%+.3f\nCm_0 TOTAL:\t%+.3f\t\n" % ( Cm_0_w, Cm_0_t, Cm_0_total) # PLOT Cm x alpha plt.axhline(0, color='k') plt.plot(alpha * 180.0 / np.pi, y_w, label='wing') plt.plot(alpha * 180.0 / np.pi, y_t, label='tail') plt.plot(alpha * 180.0 / np.pi, y_total, label='total') plt.legend() plt.xlabel("alpha") plt.ylabel("Cm") plt.grid() tikz_save("p2.tex") plt.show() if (Cm_alpha_total < 0): print "Aeronave Estável!!" return Cm_alpha_total else: print "Aeronave Instável :(" return 0
def export_plot_tikz(self): filename = QFileDialog.getSaveFileName(self, 'Save Plot as Tikzpicture', '.', '*tex') fileextension = filename[1].split('*')[1] filename = filename[0].split('.')[0] filename = filename + '.' + fileextension if not len(filename) == 0: tikz_save(filename, self.plotAreaWidget.fig)
def scatter_points(x, y, labels): # We create a scatter plot. df = pandas.DataFrame({ 'x': x[:, 0], 'y': x[:, 1], 'words': y[:], 'labels': labels }) df.to_csv("tsne_data.csv", sep=" ", columns=["x", "y", "words", "labels"], index=False) df_win1 = points_from_window(df, xmin=5, xmax=10, ymin=5, ymax=10) df_win2 = points_from_window(df, xmin=-15, xmax=-10, ymin=-20, ymax=-15) df_win1.to_csv("win1.csv", sep=" ", columns=["x", "y", "words", "labels"], index=False) df_win2.to_csv("win2.csv", sep=" ", columns=["x", "y", "words", "labels"], index=False) f = plt.figure(figsize=(8, 8)) plt.axes().set_aspect('equal') oov_i = [i for i in range(len(labels)) if labels[i] == "OOV"] not_oov_i = [i for i in range(len(labels)) if labels[i] == "Not OOV"] plt.scatter(x[oov_i, 0], x[oov_i, 1], y[oov_i], lw=0, s=4, c='red', label="OOV") plt.scatter(x[not_oov_i, 0], x[not_oov_i, 1], y[not_oov_i], lw=0, s=4, c='blue', label="Not OOV") plt.xlim(-25, 25) plt.ylim(-25, 25) plt.axis('on') plt.axis('tight') plt.legend(labels=["OOV", "Not OOV"]) # for i, txt in enumerate(y): # ax.annotate(txt[0], (x[i, 0], x[i, 1])) from matplotlib2tikz import save as tikz_save tikz_save('test.tex', figure=f) save_file = os.path.join(cfg.VIS_SAVE_DIR, 'tsne_file.png') plt.savefig(save_file, dpi=120) return f
def helper_save(plt_file_name): if plt_file_name is None: plt.show() else: plt.tight_layout() plt.savefig(plt_file_name+'.pdf', format='pdf', dpi=1000) from matplotlib2tikz import save as tikz_save # tikz_save('../report/ex1/plots/test.tex', figureheight='4cm', figurewidth='6cm') tikz_save(plt_file_name + ".tikz", figurewidth="\\matplotlibTotikzfigurewidth", figureheight="\\matplotlibTotikzfigureheight",strict=False)
def plot_tensorboard_scalar( eventlogpath, value, # Error, Accuracy, Cost export=False): """plotting a scalar from tensorboard :param eventlogpath path to event log file (include '/' at the end) :param value: specify the value to be printed: 'Error', 'Accuracy' or 'Cost' :param export: enable tikz export :type eventlogpath str :type value str :type export: bool """ path_train = eventlogpath + '/graph/train/' path_val = eventlogpath + '/graph/val/' ea_train = event_accumulator.EventAccumulator(path_train) ea_val = event_accumulator.EventAccumulator(path_val) ea_train.Reload() ea_val.Reload() if value == 'Error': scalar = 'CNN_Model/Accuracy/Error' elif value == 'Accuracy': scalar = 'CNN_Model/Accuracy/Accuracy' elif value == 'Cost': scalar = 'CNN_Model/Cost' else: raise ValueError('specified value %s not defined', value) train_scalar = [(s.step, s.value) for s in ea_train.Scalars(scalar)] val_scalar = [(s.step, s.value) for s in ea_val.Scalars(scalar)] train_scalar_x = [x[0] for x in train_scalar] train_scalar_y = [x[1] for x in train_scalar] val_scalar_x = [x[0] for x in val_scalar] val_scalar_y = [x[1] for x in val_scalar] plt.plot(train_scalar_x, train_scalar_y, label='Training', color=TUMgray1, linestyle='--', linewidth=1.5) plt.plot(val_scalar_x, val_scalar_y, label='Validierung ', color=TUMblack, linestyle='-', linewidth=1.5) plt.xlabel('Iterationen') plt.ylabel('Klassifikationsfehler' if value == 'Error' else 'Kosten') plt.grid(True) plt.legend() plt.savefig(eventlogpath + '/plot_' + value + '.pdf') if export: tikz_save(eventlogpath + '/plot_' + value + '.tikz', encoding='utf8') plt.close()
def plot_re_rect_occlusion(eval_args, eval_dir, scene_ids, all_test_visibs, bins = 10): obj_id = eval_args.getint('DATA','obj_id') top_n_eval = eval_args.getint('EVALUATION','TOP_N_EVAL') top_n = eval_args.getint('METRIC','TOP_N') # if top_n_eval < 1: # return all_angle_errs = [] for scene_id in scene_ids: if not os.path.exists(os.path.join(eval_dir,'error=re_ntop=%s' % top_n,'errors_{:02d}.yml'.format(scene_id))): print 'WARNING: ' + os.path.join(eval_dir,'error=re_ntop=%s' % top_n,'errors_{:02d}.yml'.format(scene_id)) + ' not found' continue angle_errs_dict = inout.load_yaml(os.path.join(eval_dir,'error=re_ntop=%s' % top_n,'errors_{:02d}.yml'.format(scene_id))) all_angle_errs += [angle_e['errors'].values()[0] for angle_e in angle_errs_dict] if len(all_angle_errs) == 0: return all_angle_errs = np.array(all_angle_errs) # print all_vsd_errs fig = plt.figure() plt.grid() plt.ylabel('rot err [deg]') plt.xlabel('visibility [percent]') # plt.axis((-0.1, 1.1, -0.1, 1.1)) # plt.xlim((0.0, 1.0)) # plt.ylim((0.0, 1.0)) total_views = len(all_angle_errs)/top_n angle_errs_rect = np.empty((total_views,)) for view in xrange(total_views): top_n_errors = all_angle_errs[view*top_n:(view+1)*top_n] angle_errs_rect[view] = np.min([top_n_errors[0], 180-top_n_errors[0]]) bounds = np.linspace(0,1,bins+1) bin_angle_errs = [] bin_count = [] for idx in xrange(bins): bin_idcs = np.where((all_test_visibs>bounds[idx]) & (all_test_visibs<bounds[idx+1])) # median_angle_err[idx] = np.median(angle_errs_rect[bin_idcs]) bin_angle_errs.append(angle_errs_rect[bin_idcs]) bin_count.append(len(bin_idcs[0])) middle_bin_vis = bounds[:-1] + (bounds[1]-bounds[0])/2. # plt.bar(middle_bin_vis,median_angle_err,0.5/bins) plt.boxplot(bin_angle_errs, positions = middle_bin_vis, widths=0.5/bins, sym='+') # count_str = 'bin count ' + bins * '%s ' # count_str = count_str % tuple(bin_count) plt.title('Visibility vs Median Rectified Rotation Error' + str(bin_count)) plt.savefig(os.path.join(eval_dir,'figures','R_err_occlusion_{:02d}.png'.format(obj_id)), dpi=300) tikz_save(os.path.join(eval_dir,'latex','R_err_occlusion.tex'), figurewidth ='0.45\\textheight', figureheight='0.45\\textheight', show_info=False)
def SingleConvPlot( figName, data, dataLabel, xLabel, yLabel, ResultsFolder, OptName, figType=FileTypeRendered, figsizex=6, figsizey=3, width=0.5, xspacing=0.25, dpi=200, xtick=True, usetex=False, Tikz=False, labelSubscripts=True, ): plt.rc("text", usetex=usetex) Plot = plt.figure(figsize=(figsizex, figsizey), dpi=dpi) ax = Plot.add_subplot(111) jet = plt.get_cmap("jet") cNorm = colors.Normalize(vmin=0, vmax=len(data[0])) scalarMap = cm.ScalarMappable(norm=cNorm, cmap=jet) for n in range(np.size(data[0])): if labelSubscripts == True: if usetex == True: ax.plot(data[:, n], color=scalarMap.to_rgba(n), label=dataLabel % str(n + 1)) else: ax.plot(data[:, n], color=scalarMap.to_rgba(n), label=dataLabel % str(n + 1)) else: ax.plot(data[:, n], color=scalarMap.to_rgba(n), label=dataLabel) plt.xlabel(xLabel) plt.ylabel(yLabel) plt.xlim(xmin=0, xmax=len(data) - 1) ax.spines["right"].set_visible(False) ax.spines["top"].set_visible(False) ax.yaxis.set_ticks_position("left") ax.xaxis.set_ticks_position("bottom") ax.xaxis.set_major_locator(ticker.MaxNLocator(integer=True)) numColx = (np.size(data[0]) / 12) + 1 if numColx > 3: numColx = 3 plt.yticks(size=10 + (numColx - 1) * 4) lgd = ax.legend(bbox_to_anchor=[1.05, 1], loc=2, ncol=numColx, frameon=False, prop=fontPP) plt.tight_layout() for ii in range(np.size(figType)): plt.savefig( ResultsFolder + OptName + "_" + figName + "." + figType[ii], bbox_extra_artists=(lgd,), bbox_inches="tight" ) if Tikz == True: tikz_save(ResultsFolder + OptName + "_" + figName + ".tikz") plt.close() fail = 0 return fail
def main(): parser = argparse.ArgumentParser(description='Radiomics results') parser.add_argument('-svm', '--svm', metavar='svm', nargs='+', dest='svm', type=str, required=True, help='SVM file (HDF)') parser.add_argument('-pinfo', '--pinfo', metavar='pinfo', nargs='+', dest='pinfo', type=str, required=True, help='Patient Info File (txt)') args = parser.parse_args() if type(args.svm) is list: args.svm = ''.join(args.svm) if type(args.pinfo) is list: args.pinfo = ''.join(args.pinfo) prediction = pd.read_hdf(args.svm) n_class = 1 label_type = prediction.keys()[0] #NOTE: Assume we want to have the first key N_1 = len(prediction[label_type].Y_train[0]) N_2 = len(prediction[label_type].Y_test[0]) _, predictions = plot_multi_SVM(prediction, args.pinfo, label_type, show_plots=False, key=None, n_classifiers=[n_class], alpha=0.95) y_score = predictions[str(n_class)]['y_score'] y_test = predictions[str(n_class)]['y_test'] plot = 'default' print(len(y_test), len(y_score)) # y_score = np.asarray(y_score) # y_test = np.asarray(y_test) plot = 'default' f, fpr, tpr = plot_ROC_CIc(y_tests, y_scores, N_1, N_2) if plot == 'default': plot = '_' + str(n_class) output = os.path.join(args.svm, 'roc' + plot + '.png') f.savefig(output) print(("ROC saved as {} !").format(output)) output = os.path.join(args.svm, 'roc' + plot + '.tex') tikz_save(output) # Save ROC values as JSON output = os.path.join(args.svm, 'roc' + plot + '.csv') with open(output, 'wb') as csv_file: writer = csv.writer(csv_file) writer.writerow(['FPR', 'TPR']) for i in range(0, len(fpr)): data = [str(fpr[i]), str(tpr[i])] writer.writerow(data) print(("ROC saved as {} !").format(output))
def conv_singular_values(): """Get singular values.""" with tf.Graph().as_default() as g: saver = tf.train.import_meta_graph(FLAGS.checkpoint_dir + FLAGS.graph, clear_devices=True) with tf.Session().as_default() as sess: saver.restore(sess, tf.train.latest_checkpoint(FLAGS.checkpoint_dir)) svd_list = list() for op in g.get_operations(): if op.type == 'Conv2D': print '---' print op.name if len(op.inputs) == 2: feature_map, kernel = op.inputs print feature_map.shape.as_list() batch_size, num_channels, height, width = feature_map.shape.as_list( ) print kernel.shape.as_list() kernel_size_height, kernel_size_width, input_channels, output_channels = kernel.shape.as_list( ) if ((FLAGS.filter_one_by_one == False) or (kernel_size_height > 1) or (kernel_size_width > 1)): kernel_np = sess.run(kernel) tf_np = convsv.SVD_Conv_Tensor_NP( kernel_np, [height, width]) this_layers_svds = np.flip( np.sort(tf_np.flatten()), 0) svd_list.append([op.name, this_layers_svds]) sys.stdout.flush() n = float(len(svd_list)) for i in range(len(svd_list)): name, svds = svd_list[i] normalized_layer_number = (0.1 + get_layer_number(name)) / ( 0.2 + MAX_LAYER_NUMBER) this_color = (1 - normalized_layer_number, normalized_layer_number, 0.1) short_name = name.replace('resnet_model/', '') short_name = short_name.replace('/Conv2D', '') plt.plot(range(len(svds)), svds, label=short_name, color=this_color) axes = plt.gca() plt.legend(fontsize='xx-small', ncol=3) axes.set_xlim([0, FLAGS.xlim]) plt.xlabel('Singular value rank', fontsize=20) plt.ylabel('Singular value', fontsize=20) png_output_name = FLAGS.plot_output_prefix + ".png" plot_directory = os.path.dirname(png_output_name) if not os.path.isdir(plot_directory): os.mkdir(plot_directory) f = open(png_output_name, 'w') plt.savefig(f, dpi=256) tikz_save(FLAGS.plot_output_prefix + '.tex')
def show(self, blocking=True): if blocking: self.plot_data() if self.tikz_export: tikz_save(self.tikz_file) plt.show() else: self.clean_axes() self.plot_data() plt.pause(0.1)
def graph(datamodel, target_list, selected_metrics, name_replace_list): xdata = [] ydata = [] for i, target in enumerate(target_list): # Read data and initialize data model f = open(target, 'r') target_data = datamodel(f.read()) if i == 0: # On first pass, create header list first = target_data if selected_metrics is None: metrics = target_data.get_all_titles() else: metrics = target_data.get_title_list(selected_metrics) else: # On subsequent passes, ensure they all have the same metrics and titles first.check_titles_match(target_data) # Perform find/replace on filename target_name = target for (fstr, rstr) in name_replace_list: target_name = target_name.replace(fstr, rstr) xdata.append(target_name) # Append all the data if selected_metrics is None: ydata.append(target_data.get_all_data()) else: ydata.append(target_data.get_data_list(selected_metrics)) ydata = transpose(ydata) # Create graph fig = plt.figure() x = range(len(xdata)) for i, metric in enumerate(metrics): plt.plot(x, ydata[i], 'o-', lw=4.0, label=metric) # Set temporary x-axis to text xdata plt.xticks(x, xdata) plt.legend(loc='lower right', bbox_to_anchor=(0.5, -0.05)) # Write to a temporary file, filename = "graph.tmp" tikz_save(filename) plt.close(fig) # get the string from that file, f = open(filename, 'r') graph_data = f.read() # remove the file, f.close() os.remove(filename) # then return the string return graph_data
def plot(name, qualities_mes, costs_mes, qualities_th, costs_th): fig, axes = plt.subplots(2,1) ax1= axes[0] texts_mes= [] for (i, (quality, cost)) in enumerate(zip(qualities_mes, costs_mes)): texts_mes.append(ax1.text(quality, cost, str(i), ha='center', va='center')) #print("Measured: ", q, c_cycle) color='tab:red' ax1.set_ylabel("cost per cycle (µs)") ax1.set_xlabel("quality") ax1.scatter(qualities_mes, costs_mes, label="Measured", color=color) ax1.tick_params(axis='y', labelcolor=color) ax1.grid(True) ax2 = axes[1] texts_th = [] for (i, (quality, cost)) in enumerate(zip(qualities_th, costs_th)): texts_th.append(ax2.text(quality, cost, str(i), ha='center', va='center')) color = 'tab:blue' ax2.set_ylabel("cost") ax2.set_xlabel("quality") ax2.scatter(qualities_th, costs_th, label="Model", color=color) ax2.tick_params(axis='y', labelcolor=color) ax2.grid(True) adjust_text(texts_mes, ax=ax1) adjust_text(texts_th, ax=ax2) kendalltau = GraphResults("Kendall's tau") kendalltau.costs = stats.kendalltau(costs_mes, costs_th, nan_policy='raise') kendalltau.quality = stats.kendalltau(qualities_mes, qualities_th, nan_policy='raise') spearmanr = GraphResults("Spearman's R") spearmanr.costs = stats.spearmanr(costs_mes, costs_th, nan_policy='raise') spearmanr.quality = stats.spearmanr(qualities_mes, qualities_th, nan_policy='raise') print(kendalltau.name, " Kendal's tau: cost=", kendalltau.costs, " and quality=", kendalltau.quality) print(spearmanr.name, " Spearman's r: cost=", spearmanr.costs, " and quality=", spearmanr.quality) fig.tight_layout() fig.legend() if args.tikz: tikz_save(name+".tex") plt.show()
def plot_outp_sig(str_to_json=None, tmeshkey='tmesh', sigkey='outsig', outsig=None, tmesh=None, fignum=222, reference=None, tikzstr=None, compress=5, notikz=False): import matplotlib.pyplot as plt if str_to_json is not None: jsdict = load_json_dicts(str_to_json) tmesh = jsdict[tmeshkey] outsig = jsdict[sigkey] else: str_to_json = 'notspecified' redinds = list(range(1, len(tmesh), compress)) redina = np.array(redinds) NY = np.int(len(outsig[0])/2) fig = plt.figure(fignum) ax1 = fig.add_subplot(111) ax1.plot(np.array(tmesh)[redina], np.array(outsig)[redina, :NY], color='b', linewidth=2.0) ax1.plot(np.array(tmesh)[redina], np.array(outsig)[redina, NY:], color='r', linewidth=2.0) if notikz: plt.show() return try: from matplotlib2tikz import save as tikz_save if tikzstr is None: tikzstr = str_to_json + '{0}'.format(fignum) tikz_save(tikzstr + '.tikz', figureheight='\\figureheight', figurewidth='\\figurewidth' ) print('tikz saved to ' + tikzstr + '.tikz') haztikz = True except ImportError: haztikz = False print('cannot save to tikz -- no matplotlib2tikz found') fig.show() if reference is not None: fig = plt.figure(fignum+1) ax1 = fig.add_subplot(111) ax1.plot(tmesh, np.array(outsig)-reference) if haztikz: tikz_save(str_to_json + '{0}'.format(fignum) + '_difftoref.tikz', figureheight='\\figureheight', figurewidth='\\figurewidth' ) fig.show()
def save(self, signal, name='plot', path='images/', **kwargs): from matplotlib2tikz import save as tikz_save directory = path if not os.path.isdir(directory): os.makedirs(directory) self.show(signal, **kwargs) if signal == 'scene': plt.axis('off') figurewidth = kwargs[ 'figurewidth'] if 'figurewidth' in kwargs else '8cm' path = directory+'/'+name+'.tikz' tikz_save(path, figurewidth=figurewidth) self._remove_rubbish(path)
def DoubleConvPlot( figName, data, dataLabel, xLabel, yLabel, Color, ResultsFolder, OptName, figType=FileTypeRendered, figsizex=6, figsizey=3, width=0.5, xspacing=0.25, dpi=200, xtick=True, usetex=False, Tikz=False, ): plt.rc("text", usetex=usetex) Plot = plt.figure(figsize=(figsizex, figsizey), dpi=dpi) ax1 = Plot.add_subplot(111) ax1.plot(data[0], Color[0], label=dataLabel[0]) plt.xlabel(xLabel) plt.ylabel(yLabel[0]) ax2 = ax1.twinx() ax2.plot(data[1], Color[1], label=dataLabel[1]) plt.ylabel(yLabel[1]) handles1, labels1 = ax1.get_legend_handles_labels() handles2, labels2 = ax2.get_legend_handles_labels() handles = handles1 + handles2 labels = labels1 + labels2 lgd = ax1.legend(handles, labels, bbox_to_anchor=[1.05, 1], loc=2, frameon=False, prop=fontPP) plt.xlim(xmin=0, xmax=len(data[0]) - 1) ax1.spines["right"].set_visible(False) ax1.spines["top"].set_visible(False) ax2.spines["top"].set_visible(False) ax1.yaxis.set_ticks_position("left") ax1.xaxis.set_ticks_position("bottom") ax1.xaxis.set_major_locator(ticker.MaxNLocator(integer=True)) plt.tight_layout() for ii in range(np.size(figType)): plt.savefig( ResultsFolder + OptName + "_" + figName + "." + figType[ii], bbox_extra_artists=(lgd,), bbox_inches="tight" ) if Tikz == True: tikz_save(ResultsFolder + OptName + "_" + figName + ".tikz") plt.close() fail = 0 return fail
def _gohome(tikzfile=None, showplot=True): if tikzfile is not None: try: from matplotlib2tikz import save as tikz_save tikz_save(tikzfile, figureheight='\\figureheight', figurewidth='\\figurewidth') print 'you may want to use this command\n\\input{' +\ tikzfile + '}\n' except ImportError: print 'matplotlib2tikz need to export tikz filez' if showplot: plt.show(block=False)
def outputplot(tmesh, ycomp, ystar=None, extra=None, fignum=111, fname="notspecified"): from matplotlib2tikz import save as tikz_save plt.figure(fignum) if ystar is not None: plt.plot(tmesh, ystar, color="b", linewidth=2.0) lines = plt.plot(tmesh, ycomp) plt.setp(lines, color="r", linewidth=2.0) plt.yticks([0.2, 0, -0.2]) # plt.xticks([0, 2]) tikz_save(fname + ".tikz", figureheight="\\figureheight", figurewidth="\\figurewidth", extra=extra) plt.show(block=False)
def plot_step_resp(str_to_json=None, tmesh=None, red_stp_rsp=None, ful_stp_rsp=None, inivout=None, compress=20): """ compress : real, optional factor of compressing for plot, defaults to 20 """ from matplotlib2tikz import save as tikz_save if str_to_json is not None: jsdict = dou.load_json_dicts(str_to_json) tmesh = np.array(jsdict['tmesh']) red_stp_rsp = jsdict['red_stp_rsp'] ful_stp_rsp = jsdict['ful_stp_rsp'] inivout = jsdict['inivout'] else: str_to_json = 'notspecified' redinds = list(range(0, len(tmesh), compress)) redina = np.array(redinds) for ccol in range(len(red_stp_rsp)): # [0, b_mat.shape[1]-1]: # range(2): # b_mat.shape[1]): fuloutp = np.array(ful_stp_rsp[ccol])-np.array(inivout).T redoutp = np.array(red_stp_rsp[ccol]) outdiff = fuloutp - redoutp NY = fuloutp.shape[1]/2 fig = plt.figure(200 + ccol) ax1 = fig.add_subplot(131) ax1.plot(tmesh[redina], redoutp[redina, :NY], color='b', linewidth=2.0) ax1.plot(tmesh[redina], redoutp[redina, NY:], color='r', linewidth=2.0) ax2 = fig.add_subplot(132) ax2.plot(tmesh[redina], fuloutp[redina, :NY], color='b', linewidth=2.0) ax2.plot(tmesh[redina], fuloutp[redina, NY:], color='r', linewidth=2.0) ax3 = fig.add_subplot(133) ax3.plot(tmesh[redina], outdiff[redina, :NY], color='b', linewidth=2.0) ax3.plot(tmesh[redina], outdiff[redina, NY:], color='r', linewidth=2.0) tikz_save(str_to_json + '{0}'.format(200+ccol) + '.tikz', figureheight='\\figureheight', figurewidth='\\figurewidth' ) print('saved to ' + str_to_json + '{0}'.format(200+ccol) + '.tikz') fig.show()
def plot_blocks_throughput(self, data, data_2): nblocks = data[6] nblocks_2 = data_2[6] # print "data 6 ", data[6] # print "data 7 ", data[7] # data[7] gives minimum # data[8] gives average # data[9] gives variance block_dict = data[8] block_dict_2 = data_2[8] self.blks_x = numpy.array(xrange(nblocks)) self.blks_x_2 = numpy.array(xrange(nblocks_2)) sorted_dict = sorted(block_dict.iteritems(), key=operator.itemgetter(0)) sorted_dict.reverse() self.blks_times = [s[1] for s in sorted_dict] self.blks_keys = [s[0] for s in sorted_dict] sorted_dict_2 = sorted(block_dict_2.iteritems(), key=operator.itemgetter(0)) sorted_dict_2.reverse() self.blks_times_2 = [s[1] for s in sorted_dict_2] self.blks_keys_2 = [s[0] for s in sorted_dict_2] self.fig100 = plt.figure(100 + self.fignum, figsize=(12, 10), facecolor="w") self.fig100.clf() self.sp101 = self.fig100.add_subplot(1, 1, 1) self.blks_times[:] = [x / self.nitems * 1000 for x in self.blks_times] print "SUMSUM: ", sum(self.blks_times) self.blks_times_2[:] = [x / self.nitems * 1000 for x in self.blks_times_2] print "self.blks_times ", self.blks_times self.sp101.barh(self.blks_x, self.blks_times, height=width, color="r", alpha=0.85, label="2.5 MHz") self.sp101.barh(self.blks_x_2 + width, self.blks_times_2, height=width, color="b", alpha=0.85, label="1 MHz") # print self.blks_times self.sp101.set_title(self.title, fontsize=22, fontweight="bold") self.sp101.set_xlabel("Execution time per OFDM symbol (us)", fontsize=16) self.sp101.set_yticks(self.blks_x + width) self.sp101.set_yticklabels(self.blks_keys) self.sp101.grid() self.sp101.legend() # self.sp101.set_color_cycle(['c', 'm', 'y', 'k']) plt.draw() tikz_save("myfile.tikz", figureheight="20cm", figurewidth="14cm")
def x_conv_plot(xval_0sr1, xval_prox_grad): """ """ import matplotlib.pyplot as plt from matplotlib2tikz import save as tikz_save d_0sr1, d_prox_grad, d_l_bfgs_b = [], [], [] for j in range(len(xval_0sr1)): d_0sr1.append(np.linalg.norm(xval_0sr1[j] - xval_0sr1[-1])) for j in range(len(xval_prox_grad)): d_prox_grad.append(np.linalg.norm(xval_prox_grad[j]-xval_prox_grad[-1])) for j in range(len(xval_l_bfgs_b)): d_l_bfgs_b.append(np.linalg.norm(xval_l_bfgs_b[j]-xval_l_bfgs_b[-1])) q_0sr1, q_prox_grad, q_l_bfgs_b = [], [], [] for i in range(len(d_0sr1) - 1): q_0sr1.append(d_0sr1[i+1] / d_0sr1[i]) for i in range(len(d_prox_grad) - 1): q_prox_grad.append(d_prox_grad[i+1] / d_prox_grad[i]) for i in range(len(d_l_bfgs_b) - 1): q_l_bfgs_b.append(d_l_bfgs_b[i+1] / d_l_bfgs_b[i]) line1, = plt.plot(range(len(q_0sr1)), q_0sr1, 'r', label = '0SR1', lw = 2) line2, = plt.plot(range(len(q_prox_grad)), q_prox_grad, 'b', label = 'ProxGrad', lw = 2) line3, = plt.plot(range(len(q_l_bfgs_b)), q_l_bfgs_b, 'g', label = 'L-BFGS-B', lw = 2) #plt.xscale('log') plt.xlim([0, 20]) #plt.yscale('log') #plt.ylim([0, 1e5]) plt.ylabel('Convergence Factor') plt.xlabel('Number of Iterations') plt.legend(handles = [line1, line2, line3]) tikz_save( 'convPDE.tikz' ); return
def plot_outp_sig(str_to_json=None, tmeshkey='tmesh', sigkey='outsig', outsig=None, tmesh=None, fignum=222, reference=None, compress=5): import matplotlib.pyplot as plt from matplotlib2tikz import save as tikz_save if str_to_json is not None: jsdict = load_json_dicts(str_to_json) tmesh = jsdict[tmeshkey] outsig = jsdict[sigkey] else: str_to_json = 'notspecified' redinds = range(1, len(tmesh), compress) redina = np.array(redinds) NY = len(outsig[0])/2 fig = plt.figure(fignum) ax1 = fig.add_subplot(111) ax1.plot(np.array(tmesh)[redina], np.array(outsig)[redina, :NY], color='b', linewidth=2.0) ax1.plot(np.array(tmesh)[redina], np.array(outsig)[redina, NY:], color='r', linewidth=2.0) tikz_save(str_to_json + '{0}'.format(fignum) + '.tikz', figureheight='\\figureheight', figurewidth='\\figurewidth' ) print 'tikz saved to ' + str_to_json + '{0}'.format(fignum) + '.tikz' fig.show() if reference is not None: fig = plt.figure(fignum+1) ax1 = fig.add_subplot(111) ax1.plot(tmesh, np.array(outsig)-reference) tikz_save(str_to_json + '{0}'.format(fignum) + '_difftoref.tikz', figureheight='\\figureheight', figurewidth='\\figurewidth' ) fig.show()
def affiche(a, b): pl.close('all') fig = pl.figure() ax = fig.add_subplot(111) ax.set_title('Taille du graphe:{} Échantillon:{} K={}, q=$\\frac' .format(graph_size,nb_gen,k)+'{'+str(b)+'}{'+str(a+b)+'}$') ax.set_ylabel("Proportion finale") ax.set_xlabel("Proportion initiale") pl.grid() pl.plot(X/100,X/100, '--', color="gray", label="Identité", lw=2.5) for i,(beta, name, label, color) in enumerate(corres): for x in X: cursor = conn.execute( "SELECT value FROM r_spreading_{}_".format(name)+ "{}_{}_{}_{}_{}_{}_{}_{}" .format(graph_size, beta, k, nb_gen, x, max_spread_step, a, b)) rows = cursor.fetchall() v = 0 n = len(rows) for row in rows: v += json.loads(row[0])['prop_spread'][-1] Y[i][x] = v/n v = 0 for row in rows: v += (Y[i][x] - json.loads(row[0])['prop_spread'][-1])**2 v = (v/n)**(1/2) Y_high[i][x] = Y[i][x] + v Y_low[i][x] = Y[i][x] - v pl.plot(X/100,Y[i][1:], label="{}".format(label), lw=2.5, color=color) # for i in range(3): # pl.plot(X, Y_high[i][1:], 'r--', lw=2) # pl.plot(X, Y_low[i][1:], 'r--', lw=2) # pl.axhline(0.5, xmin=0, xmax=100, c='orange', lw=2.5) pl.legend(loc="lower right") tikz_save("resultats/all_finale_f_initiale_q{}.tex" .format(int(b/(a+b)*100), beta), figurewidth="\\textwidth", figureheight=".33\\textheight")
def harry_plotter(sim): fig = plt.figure() ax = fig.add_subplot(111, autoscale_on=False) #ani = sim.animate(fig, ax) ax.axis('scaled') ax.set_xlim((-10, 160)) ax.set_ylim((-10, 160)) ax.set_xlabel('East [m]') ax.set_ylabel('North [m]') sim.draw(ax) # ax.grid() # plt.tight_layout() tikz_save('../../../latex/fig/astar-admissibility-2.tikz', figureheight='1.5\\textwidth', figurewidth='1.5\\textwidth') plt.show()
def plot(self): plt.clf() lines = plt.plot(range(1, self.i+1), self.training_measures[:self.i]) plt.legend(iter(lines), ('accuracy', 'recall', 'precision'), loc=4) plt.xlabel('Iteration') plt.ylabel('Measures') plt.axis([1, self.i+1, 0, 1]) plt.title('Training measures over time') plt.savefig('training_measures.png') tikz_save('training_measures.tikz', show_info=False, figurewidth='0.5\\textwidth') plt.clf() lines = plt.plot(range(1, self.i+1), self.dev_measures[:self.i]) plt.legend(iter(lines), ('accuracy', 'recall', 'precision'), loc=4) plt.xlabel('Iteration') plt.ylabel('Measures') plt.axis([1, self.i+1, 0, 1]) plt.title('Development measures over time') plt.savefig('dev_measures.png') tikz_save('dev_measures.tikz', show_info=False, figurewidth='0.5\\textwidth') plt.clf() lines = plt.plot(range(1, self.i+1), self.testing_measures[:self.i]) plt.legend(iter(lines), ('accuracy', 'recall', 'precision'), loc=4) plt.xlabel('Iteration') plt.ylabel('Measures') plt.axis([1, self.i+1, 0, 1]) plt.title('Testing measures over time') plt.savefig('testing_measures.png') tikz_save('testing_measures.tikz', show_info=False, figurewidth='0.5\\textwidth')
def on_epoch_end(self, epoch, logs={}): p = model.predict(X, verbose=1) #p = model.predict({'input': X}, verbose=1)['output'] train_acc = accuracy_score(Y[:t1], np.round(p[:t1])) dev_acc = accuracy_score(Y[t1:t2], np.round(p[t1:t2])) test_acc = accuracy_score(Y[t2:], np.round(p[t2:])) print('Accuracy | train:', train_acc, 'dev:', dev_acc, 'test:', test_acc) train_recall = (recall_score(Y[:t1], np.round(p[:t1])) + recall_score(Y[:t1], np.round(p[:t1]), pos_label=0)) / 2 dev_recall = (recall_score(Y[t1:t2], np.round(p[t1:t2])) + recall_score(Y[t1:t2], np.round(p[t1:t2]), pos_label=0)) / 2 test_recall = (recall_score(Y[t2:], np.round(p[t2:])) + recall_score(Y[t2:], np.round(p[t2:]), pos_label=0)) / 2 print('Recall | train:', train_recall, 'dev:', dev_recall, 'test:', test_recall) self.accuracy[epoch, :] = np.array([train_acc, dev_acc, test_acc]) self.recall[epoch, :] = np.array([train_recall, dev_recall, test_recall]) plt.clf() plt.subplot(211) lines = plt.plot(range(1, epoch+2), self.accuracy[:epoch+1]) plt.legend(iter(lines), ('train', 'dev', 'test'), loc=4) plt.xlabel('Epoch') plt.ylabel('Accuracy') plt.axis([1, epoch+2, 0, 1]) plt.subplot(212) lines = plt.plot(range(1, epoch+2), self.recall[:epoch+1]) plt.legend(iter(lines), ('train', 'dev', 'test'), loc=4) plt.xlabel('Epoch') plt.ylabel('Average recall') plt.axis([1, epoch+2, 0, 1]) plt.savefig('results.png') tikz_save('results.tikz', show_info=False, figurewidth='0.5\\textwidth') if dev_recall > self.bestrecall: self.bestrecall = dev_recall model.save_weights('weights.hdf5', overwrite=True)
def GeneratePlot(): getcontext().prec += 2 pn = Decimal(1) bn = Decimal(1) hn = Decimal(math.sqrt(pn**2 + bn ** 2)) f = Decimal(0.5) g = Decimal(1) s = 0 t = range(10) v = [] for i in t: An = Decimal(f * pn * bn) bn = Decimal(f * hn) pn = Decimal(g - Decimal(math.sqrt(g- bn ** 2))) hn = Decimal(math.sqrt(pn**2 + bn**2)) s = Decimal(s+( 2**i *An)) res = 4*s v.append(res) print(res) plt.xlabel(r'Iterations $[n]$') plt.ylabel('Value of $\pi$ ') plt.grid(True) plt.plot(t,v,'o') tikz_save('../Images/PISeriesPlot.tex',figurewidth="12cm",figureheight="7cm")
def main(): plt.ion() parser = add_argparser() args = parser.parse_args() data = pickle.load(open(args.file, "rb")) tests = data[1] results = data[2] # print results data_2 = pickle.load(open(args.file_two, "rb")) tests_2 = data_2[1] results_2 = data_2[2] nitems = args.nitems nfigs = 0 plots = [] for t in tests: nfigs += 1 plots.append(plotter(t, results[t["testname"]], results_2[t["testname"]], nfigs, nitems)) tikz_save("myfile.tikz", figureheight="20cm", figurewidth="14cm") plt.show(block=True)