我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用matplotlib.pyplot.close()。
def plot_sent_trajectories(sents, decode_plot): font = {'family' : 'normal', 'size' : 14} matplotlib.rc('font', **font) i = 0 l = ["Portuguese","Catalan"] axes = plt.gca() #axes.set_xlim([xmin,xmax]) axes.set_ylim([-1,1]) for sent, enc in zip(sents, decode_plot): if i==2: continue i += 1 #times = np.arange(len(enc)) times = np.linspace(0,1,len(enc)) plt.plot(times, enc, label=l[i-1]) plt.title("Hidden Node Trajectories") plt.xlabel('timestep') plt.ylabel('trajectories') plt.legend(loc='best') plt.savefig("final_tests/cr_por_cat_hidden_cell_trajectories", bbox_inches="tight") plt.close()
def saveHintonPlot(self, matrix, num_tests, max_weight=None, ax=None): """Draw Hinton diagram for visualizing a weight matrix.""" fig,ax = plt.subplots(1,1) if not max_weight: max_weight = 2**np.ceil(np.log(np.abs(matrix).max())/np.log(2)) ax.patch.set_facecolor('gray') ax.set_aspect('equal', 'box') ax.xaxis.set_major_locator(plt.NullLocator()) ax.yaxis.set_major_locator(plt.NullLocator()) for (x, y), w in np.ndenumerate(matrix): color = 'white' if w > 0 else 'black' size = np.sqrt(np.abs(0.5*w/num_tests)) # Need to scale so that it is between 0 and 0.5 rect = plt.Rectangle([x - size / 2, y - size / 2], size, size, facecolor=color, edgecolor=color) ax.add_patch(rect) ax.autoscale_view() ax.invert_yaxis() plt.savefig(self.figures_path + self.save_prefix + '-Hinton.eps') plt.close()
def after_run(self, _run_context, run_values): fetches_batch = run_values.results for fetches in unbatch_dict(fetches_batch): # Convert to unicode fetches["predicted_tokens"] = np.char.decode( fetches["predicted_tokens"].astype("S"), "utf-8") fetches["features.source_tokens"] = np.char.decode( fetches["features.source_tokens"].astype("S"), "utf-8") if self.params["dump_plots"]: output_path = os.path.join(self.params["output_dir"], "{:05d}.png".format(self._idx)) _create_figure(fetches) plt.savefig(output_path) plt.close() tf.logging.info("Wrote %s", output_path) self._idx += 1 self._attention_scores_accum.append(_get_scores(fetches))
def write_stage_alerts(stage, path, alerts_file="alerts.list"): alerts = load_alerts() out_file = os.path.join(path, alerts_file) if not os.path.exists(path): os.makedirs(path) out_handle = open(out_file, "w") keys = ["metric", "threshold", "compare", "action", "message"] if not alerts.has_key(stage): martian.throw("No alerts found for stage %s" % stage) for alert in alerts[stage]: out_handle.write("#\n") out_handle.write(alert["metric"]+"\n") out_handle.write(str(alert["threshold"])+"\n") out_handle.write(alert["compare"]+"\n") out_handle.write(alert["action"]+"\n") out_handle.write(alert["message"]+"\n") out_handle.close()
def make_python_fig(self, code: str, exts: Tuple[str, ...]=('pdf', 'svg'), tight_layout=True) -> str: hashsum = hashlib.md5(code.encode('utf8')).hexdigest() prefix = hashsum[:2] path = os.path.join(self.figures_dir, prefix, hashsum) needfigure = False for ext in exts: if not os.path.isfile(os.path.join( path, self.default_figname + "." + ext)): needfigure = True break if needfigure: make_sure_path_exists(path) gl = self.pythonfigure_globals plt.close() exec(code, gl) if tight_layout: plt.tight_layout() for ext in exts: plt.savefig(os.path.join( path, self.default_figname + "." + ext)) return os.path.join(prefix, hashsum)
def QuASAR_rep_wrapper(outdir,parameters,samplename1,samplename2,running_mode): script_comparison_file=outdir+'/scripts/QuASAR-Rep/'+samplename1+'.vs.'+samplename2+'/'+samplename1+'.vs.'+samplename2+'.QuASAR-Rep.sh' subp.check_output(['bash','-c','mkdir -p '+os.path.dirname(script_comparison_file)]) script_comparison=open(script_comparison_file,'w') script_comparison.write("#!/bin/sh"+'\n') script_comparison.write('. '+bashrc_file+'\n') outpath=outdir+'/results/reproducibility/'+samplename1+'.vs.'+samplename2+'/QuASAR-Rep/'+samplename1+'.vs.'+samplename2+'.QuASAR-Rep.scores.txt' subp.check_output(['bash','-c','mkdir -p '+os.path.dirname(outpath)]) quasar_data=outdir+'/data/forQuASAR' quasar_transform1=quasar_data+'/'+samplename1+'.quasar_transform' quasar_transform2=quasar_data+'/'+samplename2+'.quasar_transform' script_comparison.write('${mypython} '+os.path.dirname(os.path.dirname(os.path.abspath(os.path.dirname(os.path.realpath(__file__)))))+"/hifive/bin/find_quasar_replicate_score"+' '+quasar_transform1+' '+quasar_transform2+' '+outpath+'\n') script_comparison.write('${mypython} '+os.path.abspath(os.path.dirname(os.path.realpath(__file__)))+"/plot_quasar_scatter.py"+' '+quasar_transform1+' '+quasar_transform2+' '+outpath+'\n') #split the scores by chromosomes script_comparison.write('${mypython} '+os.path.abspath(os.path.dirname(os.path.realpath(__file__)))+"/quasar_split_by_chromosomes.py"+' '+outpath+'\n') script_comparison.close() run_script(script_comparison_file,running_mode)
def GenomeDISCO_wrapper(outdir,parameters,concise_analysis,samplename1,samplename2,chromo,running_mode,f1,f2,nodefile): script_comparison_file=outdir+'/scripts/GenomeDISCO/'+samplename1+'.'+samplename2+'/'+chromo+'.'+samplename1+'.'+samplename2+'.sh' subp.check_output(['bash','-c','mkdir -p '+os.path.dirname(script_comparison_file)]) script_comparison=open(script_comparison_file,'w') script_comparison.write("#!/bin/sh"+'\n') script_comparison.write('. '+bashrc_file+'\n') if os.path.isfile(f1) and os.path.getsize(f1)>20: if os.path.isfile(f2) and os.path.getsize(f2)>20: concise_analysis_text='' if concise_analysis: concise_analysis_text=' --concise_analysis' #get the sample that goes for subsampling subsampling=parameters['GenomeDISCO']['subsampling'] if parameters['GenomeDISCO']['subsampling']!='NA' and parameters['GenomeDISCO']['subsampling']!='lowest': subsampling_sample=parameters['GenomeDISCO']['subsampling'] subsampling=outdir+'/data/edges/'+subsampling_sample+'/'+subsampling_sample+'.'+chromo+'.gz' outpath=outdir+'/results/reproducibility/'+samplename1+'.vs.'+samplename2+'/GenomeDISCO/' subp.check_output(['bash','-c','mkdir -p '+outpath]) script_comparison.write("$mypython -W ignore "+os.path.abspath(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))+"/genomedisco/compute_reproducibility.py")+" --m1 "+f1+" --m2 "+f2+" --m1name "+samplename1+" --m2name "+samplename2+" --node_file "+nodefile+" --outdir "+outpath+" --outpref "+chromo+" --m_subsample "+subsampling+" --approximation 10000000 --norm "+parameters['GenomeDISCO']['norm']+" --method RandomWalks "+" --tmin "+parameters['GenomeDISCO']['tmin']+" --tmax "+parameters['GenomeDISCO']['tmax']+concise_analysis_text+'\n') script_comparison.close() run_script(script_comparison_file,running_mode)
def fill_hdf5_with_sparse_by_chunk(mym1,mym2,fname,chunksize): start1=0 end1=0 n=mym1.shape[0] f=h5py.File(fname,'w') m1hdf5=f.create_dataset('m1',shape=(n,n),dtype='float') m2hdf5=f.create_dataset('m2',shape=(n,n),dtype='float') while end1<n: end1=np.min([n,(start1+chunksize)]) print 'start1: '+str(start1) if (end1-start1)==1: m1hdf5[start1,:]=mym1[start1,:].toarray() m2hdf5[start1,:]=mym2[start1,:].toarray() else: m1hdf5[start1:end1,:]=mym1[start1:end1,:].toarray() m2hdf5[start1:end1,:]=mym2[start1:end1,:].toarray() start1=end1 print 'sum of 1' print m1hdf5[:,:].sum() print m2hdf5[:,:].sum() f.close()
def plot_traing_info(x, ylist, path): """ Loads log file and plot x and y values as provided by input. Saves as <path>/train_log.png """ file_name = os.path.join(path, __train_log_file_name) try: with open(file_name, "rb") as f: log = pickle.load(f) except IOError: # first time warnings.warn("There is no {} file here!!!".format(file_name)) return plt.figure() x_vals = log[x] for y in ylist: y_vals = log[y] if len(y_vals) != len(x_vals): warning.warn("One of y's: {} does not have the same length as x:{}".format(y, x)) plt.plot(x_vals, y_vals, label=y) # assert len(y_vals) == len(x_vals), "not the same len" plt.xlabel(x) plt.legend() #plt.show() plt.savefig(file_name[:-3]+'png', bbox_inches='tight') plt.close('all')
def isotropic_mean_shift(self): """normalized last mean shift, under random selection N(0,I) distributed. Caveat: while it is finite and close to sqrt(n) under random selection, the length of the normalized mean shift under *systematic* selection (e.g. on a linear function) tends to infinity for mueff -> infty. Hence it must be used with great care for large mueff. """ z = self.sm.transform_inverse((self.mean - self.mean_old) / self.sigma_vec.scaling) # works unless a re-parametrisation has been done # assert Mh.vequals_approximately(z, np.dot(es.B, (1. / es.D) * # np.dot(es.B.T, (es.mean - es.mean_old) / es.sigma_vec))) z /= self.sigma * self.sp.cmean z *= self.sp.weights.mueff**0.5 return z
def plotValResults(self, save_path=None, label=None): if label is not None: accs = self.training_val_results['acc'][label] aucs = self.training_val_results['auc'][label] else: accs = self.training_val_results['acc'] aucs = self.training_val_results['auc'] plt.figure() plt.plot([i * ACCURACY_LOGGED_EVERY_N_STEPS for i in range(len(accs))], accs) plt.plot([i * ACCURACY_LOGGED_EVERY_N_STEPS for i in range(len(aucs))], aucs) plt.xlabel('Training step') plt.ylabel('Validation accuracy') plt.legend(['Accuracy','AUC']) if save_path is None: plt.show() else: plt.savefig(save_path) plt.close()
def save_ims(filename, ims, dpi=100, scale=0.5): n, c, h, w = ims.shape rows = int(math.ceil(math.sqrt(n))) cols = int(round(math.sqrt(n))) fig, axes = plt.subplots(rows, cols, figsize=(w*cols/dpi*scale, h*rows/dpi*scale), dpi=dpi) for i, ax in enumerate(axes.flat): if i < n: ax.imshow(ims[i].transpose((1, 2, 0))) ax.set_xticks([]) ax.set_yticks([]) ax.axis('off') plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0.1, hspace=0.1) plt.savefig(filename, dpi=dpi, bbox_inces='tight', transparent=True) plt.clf() plt.close()
def plot_slice_3d_3axis(input, pid, img_dir=None, idx=None): # to convert cuda arrays to numpy array input = np.asarray(input) fig, ax = plt.subplots(2, 2, figsize=[8, 8]) fig.canvas.set_window_title(pid) ax[0, 0].imshow(input[idx[0], :, :], cmap=plt.cm.gray) ax[1, 0].imshow(input[:, idx[1], :], cmap=plt.cm.gray) ax[0, 1].imshow(input[:, :, idx[2]], cmap=plt.cm.gray) if img_dir is not None: fig.savefig(img_dir + '/%s.png' % (pid), bbox_inches='tight') else: plt.show() fig.clf() plt.close('all')
def plot_all_slices(input, pid, img_dir=None): # to convert cuda arrays to numpy array input = np.asarray(input) for idx in range(0, input.shape[0]-3, 4): fig, ax = plt.subplots(2, 2, figsize=[8, 8]) fig.canvas.set_window_title(pid) ax[0, 0].imshow(input[idx, :, :], cmap=plt.cm.gray) ax[1, 0].imshow(input[idx+1, :, :], cmap=plt.cm.gray) ax[0, 1].imshow(input[idx+2, :, :], cmap=plt.cm.gray) ax[1, 1].imshow(input[idx+3, :, :], cmap=plt.cm.gray) if img_dir is not None: fig.savefig(img_dir + '_' + str(pid) + '_' + str(idx) + '.png' , bbox_inches='tight') else: plt.show() fig.clf() plt.close('all')
def plot_all_slices(ct_scan, mask, pid, img_dir=None): # to convert cuda arrays to numpy array ct_scan = np.asarray(ct_scan) mask = np.asarray(mask) for idx in range(0, mask.shape[0]-3, 2): fig, ax = plt.subplots(2, 2, figsize=[8, 8]) fig.canvas.set_window_title(pid) ax[0, 0].imshow(mask[idx, :, :], cmap=plt.cm.gray) ax[1, 0].imshow(ct_scan[idx+1, :, :], cmap=plt.cm.gray) ax[0, 1].imshow(mask[idx+2, :, :], cmap=plt.cm.gray) ax[1, 1].imshow(ct_scan[idx+3, :, :], cmap=plt.cm.gray) if img_dir is not None: fig.savefig(img_dir + '_' + str(pid) + '_' + str(idx) + '.png' , bbox_inches='tight') else: plt.show() fig.clf() plt.close('all')
def plot_4_slices(input, pid, img_dir=None, idx=None): # to convert cuda arrays to numpy array input = np.asarray(input) fig, ax = plt.subplots(2, 2, figsize=[8, 8]) fig.canvas.set_window_title(pid) ax[0, 0].imshow(input[idx[0], :, :], cmap=plt.cm.gray) ax[1, 0].imshow(input[:, idx[1], :], cmap=plt.cm.gray) ax[0, 1].imshow(input[:, :, idx[2]], cmap=plt.cm.gray) ax[1, 1].imshow(input[:, :, idx[2]], cmap=plt.cm.gray) if img_dir is not None: fig.savefig(img_dir + '/%s.png' % (pid), bbox_inches='tight') else: plt.show() fig.clf() plt.close('all')
def draw_results(self): metrics_log, cost_log = {}, {} for key, value in sorted(self._logs.items()): metrics_log[key], cost_log[key] = value[:-1], value[-1] for i, name in enumerate(sorted(self._metric_names)): plt.figure() plt.title("Metric Type: {}".format(name)) for key, log in sorted(metrics_log.items()): xs = np.arange(len(log[i])) + 1 plt.plot(xs, log[i], label="Data Type: {}".format(key)) plt.legend(loc=4) plt.show() plt.close() plt.figure() plt.title("Cost") for key, loss in sorted(cost_log.items()): xs = np.arange(len(loss)) + 1 plt.plot(xs, loss, label="Data Type: {}".format(key)) plt.legend() plt.show()
def get_graphs_from_logs(): with open("Results/logs.dat", "rb") as file: logs = pickle.load(file) for (hus, ep, bt), log in logs.items(): hus = list(map(lambda _c: str(_c), hus)) title = "hus: {} ep: {} bt: {}".format( "- " + " -> ".join(hus) + " -", ep, bt ) fb_log, acc_log = log["fb_log"], log["acc_log"] xs = np.arange(len(fb_log)) + 1 plt.figure() plt.title(title) plt.plot(xs, fb_log) plt.plot(xs, acc_log, c="g") plt.savefig("Results/img/" + "{}_{}_{}".format( "-".join(hus), ep, bt )) plt.close()
def make_comment_plot(data,p_id): """ ???????? :param datas: :return: """ if data: temps = "".join(data).replace(" ", "").replace("\r\n", "") values = re.findall(r'(\d+)', temps) c_values = [int(value) for value in values] c_keys = re.findall('[\u4e00-\u9fa5]+', temps) print(c_keys) s = pd.Series(c_values, index=c_keys,name='???') s = s[3:6] s_sum = s.sum() s = s.apply(lambda x: x / s_sum) s.plot.pie(autopct='%0.2f%%', fontsize=8, colors=['g', 'y', 'r']) plt.savefig("static/upload/%s_c.png" % p_id,dpi=90) plt.close() return file_hepler.get_image_path("%s_c.png" % p_id) else: return file_hepler.get_image_path("no_good_comments.png")
def make_overview_plot(data,p_id): """ ???? :param datas: :return: """ if data: temps = "".join(data) values = re.findall(r'(\d+)', temps) c_values = [int(value) for value in values] c_keys = re.findall('[\u4e00-\u9fa5]+', temps) s = pd.Series(c_values, index=c_keys) s.plot.bar(figsize=(6, 8), fontsize=8) plt.savefig("static/upload/%s_o.png" % p_id,dpi=90) plt.close() return file_hepler.get_image_path("%s_o.png" % p_id) else: return file_hepler.get_image_path("no_overview.png")
def debug_plot_over_img(self, img, x, y, bb_d, bb_gt): """Plot the landmarks over the image with the bbox.""" plt.close("all") fig = plt.figure() # , figsize=(15, 10.8), dpi=200 ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() ax.imshow(img, aspect="auto", cmap='Greys_r') ax.scatter(x, y, s=10, color='r') rect1 = patches.Rectangle( (bb_d[0], bb_d[1]), bb_d[2]-bb_d[0], bb_d[3]-bb_d[1], linewidth=1, edgecolor='r', facecolor='none') ax.add_patch(rect1) rect2 = patches.Rectangle( (bb_gt[0], bb_gt[1]), bb_gt[2]-bb_gt[0], bb_gt[3]-bb_gt[1], linewidth=1, edgecolor='b', facecolor='none') ax.add_patch(rect2) fig.add_axes(ax) return fig
def plot_over_img(self, img, x, y, x_pr, y_pr, bb_gt): """Plot the landmarks over the image with the bbox.""" plt.close("all") fig = plt.figure(frameon=False) # , figsize=(15, 10.8), dpi=200 ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() ax.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB), aspect="auto") ax.scatter(x, y, s=10, color='r') ax.scatter(x_pr, y_pr, s=10, color='g') rect = patches.Rectangle( (bb_gt[0], bb_gt[1]), bb_gt[2]-bb_gt[0], bb_gt[3]-bb_gt[1], linewidth=1, edgecolor='b', facecolor='none') ax.add_patch(rect) fig.add_axes(ax) return fig
def plot_cdf_model_and_meansh(self, cdfs, tag, cdf0_1s, aucs, bx, dx): plt.close("all") x = np.arange(0, bx, dx) fig, ax = plt.subplots(nrows=1, ncols=1) ax.plot(x, cdfs[0], label="CDF model") ax.plot(x, cdfs[1], label="CDF mean shape") ax.grid(True) plt.xlabel("NRMSE") plt.ylabel("Data proportion") plt.legend(loc=4, prop={'size': 8}, fancybox=True, shadow=True) plt.title( "CDF curve: " + tag + ". Model: CDF0.1: " + str(prec2 % cdf0_1s[0]) + " . AUC:" + str(prec2 % aucs[0]) + ".\n" + ". MSh: CDF0.1: " + str(prec2 % cdf0_1s[1]) + " . AUC:" + str(prec2 % aucs[1]) + ".\n") return fig
def load_tr_vl_ts(self, path,nlabels, task, share=True): """load mnist dataset for classification. """ f = gzip.open(path, 'rb') train_set, valid_set, test_set = pickle.load(f) f.close() # share the data train_set_x, train_set_y = self.shared_dataset_xy(train_set, nlabels = nlabels, train=True, task=task) valid_set_x, valid_set_y = self.shared_dataset_xy(valid_set) test_set_x, test_set_y = self.shared_dataset_xy(test_set) if share: reval = [(train_set_x, train_set_y), (valid_set_x, valid_set_y), (test_set_x, test_set_y)] else: if task=='cls': train_set = (train_set[0], self.labels(train_set[1], nlabels)) # train_y reval = [train_set, valid_set, test_set] return reval
def gpu_status(self,av_type_list): for t in av_type_list: cmd='nvidia-smi -q --display='+t #print('\nCMD:',cmd,'\n') r=os.popen(cmd) info=r.readlines() r.close() content = " ".join(info) #print('\ncontent:',content,'\n') index=content.find('Attached GPUs') s=content[index:].replace(' ','').rstrip('\n') self.t_send(s) time.sleep(.5) #th.exit() #============================================================================== # #==============================================================================
def save_fft(fil,audio_in): samples = len(audio_in) fft_size = 2**int(floor(log(samples)/log(2.0))) freq = fft(audio_in[0:fft_size]) s_data = numpy.zeros(fft_size/2) x_data = numpy.zeros(fft_size/2) peak = 0; for j in xrange(fft_size/2): if (abs(freq[j]) > peak): peak = abs(freq[j]) for j in xrange(fft_size/2): x_data[j] = log(2.0*(j+1.0)/fft_size); if (x_data[j] < -10): x_data[j] = -10 s_data[j] = 10.0*log(abs(freq[j])/peak)/log(10.0) plt.ylim([-50,0]) plt.plot(x_data,s_data) plt.title('fft log power') plt.grid() fields = fil.split('.') plt.savefig(fields[0]+'_fft.png', bbox_inches="tight") plt.clf() plt.close()
def __plot_canvas(self, show, save): if self.x is None: raise Exception("Please run fit() method first") else: plt.close() plt.plot(self.x.real, self.x.imag, '-', color='blue') plt.xlim((0, self.canvas)) plt.ylim((0, self.canvas)) if show and save: plt.savefig(self.path_to_save) plt.show() elif save: if self.path_to_save is None: raise Exception('Please create Trajectory instance with path_to_save') plt.savefig(self.path_to_save) elif show: plt.show()
def __plot_canvas(self, show, save): if len(self.PSFs) == 0: raise Exception("Please run fit() method first.") else: plt.close() fig, axes = plt.subplots(1, self.PSFnumber, figsize=(10, 10)) for i in range(self.PSFnumber): axes[i].imshow(self.PSFs[i], cmap='gray') if show and save: if self.path_to_save is None: raise Exception('Please create Trajectory instance with path_to_save') plt.savefig(self.path_to_save) plt.show() elif save: if self.path_to_save is None: raise Exception('Please create Trajectory instance with path_to_save') plt.savefig(self.path_to_save) elif show: plt.show()
def __plot_canvas(self, show, save): if len(self.result) == 0: raise Exception('Please run blur_image() method first.') else: plt.close() plt.axis('off') fig, axes = plt.subplots(1, len(self.result), figsize=(10, 10)) if len(self.result) > 1: for i in range(len(self.result)): axes[i].imshow(self.result[i]) else: plt.axis('off') plt.imshow(self.result[0]) if show and save: if self.path_to_save is None: raise Exception('Please create Trajectory instance with path_to_save') cv2.imwrite(os.path.join(self.path_to_save, self.image_path.split('/')[-1]), self.result[0] * 255) plt.show() elif save: if self.path_to_save is None: raise Exception('Please create Trajectory instance with path_to_save') cv2.imwrite(os.path.join(self.path_to_save, self.image_path.split('/')[-1]), self.result[0] * 255) elif show: plt.show()
def boxplot_metrics(df, eval_dir): """ Create summary boxplots of all geometric measures. :param df: :param eval_dir: :return: """ boxplots_file = os.path.join(eval_dir, 'boxplots.eps') fig, axes = plt.subplots(3, 1) fig.set_figheight(14) fig.set_figwidth(7) sns.boxplot(x='struc', y='dice', hue='phase', data=df, palette="PRGn", ax=axes[0]) sns.boxplot(x='struc', y='hd', hue='phase', data=df, palette="PRGn", ax=axes[1]) sns.boxplot(x='struc', y='assd', hue='phase', data=df, palette="PRGn", ax=axes[2]) plt.savefig(boxplots_file) plt.close() return 0
def draw_test(self): """ Compare ggplot object to image determined by `right` Parameters ---------- self : ggplot ggplot object This function is meant to monkey patch ggplot.draw_test so that tests can draw and not care about cleaning up the MPL figure. """ try: figure = self.draw() except Exception as err: plt.close('all') raise err else: if figure: plt.close(figure)
def plot_joints_step(self, stamp): if self.plots == '': return mean_joints = self.get_mean_joints() std_joints = self.get_std_joints() f = plt.figure(facecolor="white", figsize=(16, 12)) ax = f.add_subplot(111) ax.set_title('Mean +- {}std'.format(self.std_factor)) color_id = 0 for joint_id, joint_mean in enumerate(mean_joints): ax.plot(self.x, joint_mean, label='Joint {}'.format(joint_id), color=self.colors[color_id], linestyle='dashed') plt.fill_between(self.x, joint_mean - self.std_factor*std_joints[joint_id], joint_mean + self.std_factor*std_joints[joint_id], alpha=0.1, color=self.colors[color_id]) color_id = (color_id + 1) % len(self.colors) plt.legend(loc='upper left') self._mk_dirs() filename = '_'.join(['joints', stamp]) plt.savefig(join(self.plots, filename) + '.svg', dpi=100, transparent=False) plt.close('all')
def plot_demos(self): if self.plots == '': return yt = self.Y.transpose(2, 0, 1) for joint_id, joint in enumerate(yt): f = plt.figure(facecolor="white", figsize=(16, 12)) ax = f.add_subplot(111) ax.set_title('Joint {}'.format(joint_id)) for demo_id, demo in enumerate(joint): ax.plot(self.x, demo, label='Demo {}'.format(demo_id)) plt.legend() # Save or show plots self._mk_dirs() filename = 'demos_of_joint_{}'.format(joint_id) plt.savefig(join(self.plots, filename) + '.svg', dpi=100, transparent=False) plt.close('all')
def plot_convergence(history, prefix='', prefix2=''): plt.figure(figsize=(8, 5)) ax = plt.subplot(111) ax.get_xaxis().tick_bottom() ax.get_yaxis().tick_left() plt.plot(history["TC"], '-', lw=2.5, color=tableau20[0]) x = len(history["TC"]) y = np.max(history["TC"]) plt.text(0.5 * x, 0.8 * y, "TC", fontsize=18, fontweight='bold', color=tableau20[0]) if history.has_key("additivity"): plt.plot(history["additivity"], '-', lw=2.5, color=tableau20[1]) plt.text(0.5 * x, 0.3 * y, "additivity", fontsize=18, fontweight='bold', color=tableau20[1]) plt.ylabel('TC', fontsize=12, fontweight='bold') plt.xlabel('# Iterations', fontsize=12, fontweight='bold') plt.suptitle('Convergence', fontsize=12) filename = '{}/summary/convergence{}.pdf'.format(prefix, prefix2) if not os.path.exists(os.path.dirname(filename)): os.makedirs(os.path.dirname(filename)) plt.savefig(filename, bbox_inches="tight") plt.close('all') return True
def plot_heatmaps(data, mis, column_label, cont, topk=30, prefix=''): cmap = sns.cubehelix_palette(as_cmap=True, light=.9) m, nv = mis.shape for j in range(m): inds = np.argsort(- mis[j, :])[:topk] if len(inds) >= 2: plt.clf() order = np.argsort(cont[:,j]) subdata = data[:, inds][order].T subdata -= np.nanmean(subdata, axis=1, keepdims=True) subdata /= np.nanstd(subdata, axis=1, keepdims=True) columns = [column_label[i] for i in inds] sns.heatmap(subdata, vmin=-3, vmax=3, cmap=cmap, yticklabels=columns, xticklabels=False, mask=np.isnan(subdata)) filename = '{}/heatmaps/group_num={}.png'.format(prefix, j) if not os.path.exists(os.path.dirname(filename)): os.makedirs(os.path.dirname(filename)) plt.title("Latent factor {}".format(j)) plt.yticks(rotation=0) plt.savefig(filename, bbox_inches='tight') plt.close('all') #plot_rels(data[:, inds], map(lambda q: column_label[q], inds), colors=cont[:, j], # outfile=prefix + '/relationships/group_num=' + str(j), latent=labels[:, j], alpha=0.1)
def plot_learning_curve(_, history, folder, debug=True): arr = np.asarray( map(lambda k: [k['epoch'], k['train_loss'], k['valid_loss']], history)) plt.figure() plt.plot(arr[:, 0], arr[:, 1], 'r', marker='o', label='Training loss', linewidth=2.0) plt.plot(arr[:, 0], arr[:, 2], 'b', marker='o', label='Validation loss', linewidth=2.0) plt.xlabel('Epochs') plt.ylabel('Loss') plt.ylim([0.0, np.max(arr[:, 1:]) * 1.3]) plt.title('Learning curve') plt.legend() if not debug: plt.savefig('%s/learning_curve.png' % folder, bbox_inches='tight') plt.close()
def plot_grid(images,w=10,path="plan.png",verbose=False): import matplotlib.pyplot as plt l = 0 images = fix_images(images) l = len(images) h = int(math.ceil(l/w)) plt.figure(figsize=(w*1.5, h*1.5)) for i,image in enumerate(images): ax = plt.subplot(h,w,i+1) try: plt.imshow(image,interpolation='nearest',cmap='gray',) except TypeError: TypeError("Invalid dimensions for image data: image={}".format(np.array(image).shape)) ax.get_xaxis().set_visible(False) ax.get_yaxis().set_visible(False) print(path) if verbose else None plt.tight_layout() plt.savefig(path) plt.close() # contiguous image
def t_lim(self): """Return a tuple containing the left and right t-limits for this plot.""" tmin = self.t_axis.min() tmax = self.t_axis.max() if self.plot_properties.has_key('xlim_left'): left = self.plot_properties['xlim_left'] # if the start is very close to zero, i.e. less than 2% of the full # timespan, round the left limit to zero elif float(tmin) / (tmax - tmin) < 2e-2: left = 0 else: left = tmin if self.plot_properties.has_key('xlim_right'): right = self.plot_properties['xlim_right'] else: right = self.t_axis.max() return (left, right)
def read_yield_sn1a_tables(self,sn1a_table,isotopes): f1=open(sn1a_table) lines=f1.readlines() f1.close() iso_1a=[] yield_1a=[] for line in lines: #for header if '#' in line: continue iso_1a.append(line.split()[0]) yield_1a.append(float(line.split()[1])) yields=[] #fill up the missing isotope yields with zero for iso in isotopes: if iso in iso_1a: idx=iso_1a.index(iso) yields.append(yield_1a[idx]) else: yields.append(0.) return yields
def set_plot_kipp_CO(self, startfirstTP=False,savefig=''): ''' plots kippenhahn diagrams with c/o ratio ''' if startfirstTP==True: t0_model=self.set_find_first_TP() else: t0_model=len(self.run_historydata)*[0] m=self.run_historydata i=0 for case in m: case.kippenhahn_CO(i,'model',t0_model=t0_model[i]) title(self.run_label[i]) if len(savefig)>0: plt.savefig(savefig+self.run_label[i]+'.png') plt.close() i += 1
def scoreHists(scoresFN,outFN,numBins,geneNames,scoreType): '''Read through a scores file, and separate into all pairwise comparisons. Then plot hist of each.''' # currently, this seems to require a display for interactive # plots. would be nice to make it run without that... pairD = readScorePairs(scoresFN,geneNames,scoreType) pyplot.ioff() # turn off interactive mode with PdfPages(outFN) as pdf: for key in pairD: fig = pyplot.figure() pyplot.hist(pairD[key],bins=numBins) pyplot.title('-'.join(key)) pdf.savefig() pyplot.close()
def heatmap(src_sent, tgt_sent, att_weights, idx): plt.figure(figsize=(8, 6), dpi=80) att_probs = np.stack(att_weights, axis=1) plt.imshow(att_weights, cmap='gray', interpolation='nearest') #src_sent = [ str(s) for s in src_sent] #tgt_sent = [ str(s) for s in tgt_sent] #plt.xticks(range(0, len(tgt_sent)), tgt_sent, rotation='vertical') #plt.yticks(range(0, len(src_sent)), src_sent) plt.xticks(range(0, len(tgt_sent)),"") plt.yticks(range(0, len(src_sent)),"") plt.axis('off') plt.savefig("att_matrix_"+str(idx), bbox_inches='tight') plt.close()
def plot_trajectories(src_sent, src_encoding, idx): # encoding is (time_steps, hidden_dim) #pca = PCA(n_components=1) #pca_result = pca.fit_transform(src_encoding) times = np.arange(src_encoding.shape[0]) plt.plot(times, src_encoding) plt.title(" ".join(src_sent)) plt.xlabel('timestep') plt.ylabel('trajectories') plt.savefig("misc_hidden_cell_trajectories_"+str(idx), bbox_inches="tight") plt.close()
def length_histogram(fqin, name): ''' Create a histogram, and return the bin edges of the bin containing the most reads ''' logging.info("Creating length histogram to find bin with most reads.") lengths = get_lengths(fqin) plt.hist(lengths, bins='auto') plt.savefig(name, format='png', dpi=100) plt.close("all") hist, bin_edges = np.histogram(lengths, bins='auto') maxindex = np.argmax(hist) return (bin_edges[maxindex], bin_edges[maxindex + 1])
def password_strength(): # different length x = [6, 7, 8, 9] y = [] for _x in x: _y = [] for c in range(1, 5): _y.append(enumeration(c, _x, _x)) y.append(tuple(_y)) plt.xlabel('Number of digits') plt.ylabel('Number of guesses needed to crack') plt.title('Password strength based on password length') plt.plot(x, y) plt.savefig('variable_len.png') plt.close() # different combinations c = range(5) y = [] for _c in c: _y = [] for l in range(6, 10): _y.append(enumeration(_c, l, l)) y.append(tuple(_y)) plt.xlabel('Number of character sets contained') plt.ylabel('Number of guesses needed to crack') plt.title('Password strength based on character sets') plt.plot(c, y) plt.savefig('variable_con.png') plt.close()
def plot_clustermap(sequences, title, plotpath, size=300, dpi=200): """ Plot a clustermap of the given sequences size -- Downsample to this many sequences title -- plot title Return the number of clusters. """ logger.info('Clustering %d sequences (downsampled to at most %d)', len(sequences), size) sequences = downsampled(sequences, size) df, linkage, clusters = cluster_sequences(sequences) palette = sns.color_palette([(0.15, 0.15, 0.15)]) palette += sns.color_palette('Spectral', n_colors=max(clusters), desat=0.9) row_colors = [ palette[cluster_id] for cluster_id in clusters ] cm = sns.clustermap(df, row_linkage=linkage, col_linkage=linkage, row_colors=row_colors, linewidths=None, linecolor='none', figsize=(210/25.4, 210/25.4), cmap='Blues', xticklabels=False, yticklabels=False ) if title is not None: cm.fig.suptitle(title) cm.savefig(plotpath, dpi=dpi) # free the memory used by the plot import matplotlib.pyplot as plt plt.close('all') return len(set(clusters))
def quasar_makePartition(outdir,nodes,resolution,restriction_fragment_level,subset_chromosomes,running_mode): quasar_data=outdir+'/data/forQuASAR' subp.check_output(['bash','-c','mkdir -p '+quasar_data]) nodes_partition=quasar_data+'/nodes.partition' partition_script_file=outdir+'/scripts/forQuASAR/QuASARpartition.sh' subp.check_output(['bash','-c','mkdir -p '+os.path.dirname(partition_script_file)]) partition_script=open(partition_script_file,'w') partition_script.write("#!/bin/sh"+'\n') partition_script.write('. '+bashrc_file+'\n') partition_script.write('${mypython} '+os.path.dirname(os.path.realpath(__file__))+"/make_partition_from_bedfile.py --nodes "+nodes+' --partition '+nodes_partition+' --subset_chromosomes '+subset_chromosomes+' --resolution '+resolution+'\n') partition_script.close() run_script(partition_script_file,running_mode)
def quasar_qc_wrapper(outdir,parameters,samplename,running_mode): script_comparison_file=outdir+'/scripts/QuASAR-QC/'+samplename+'/'+samplename+'.QuASAR-QC.sh' subp.check_output(['bash','-c','mkdir -p '+os.path.dirname(script_comparison_file)]) script_comparison=open(script_comparison_file,'w') script_comparison.write("#!/bin/sh"+'\n') script_comparison.write('. '+bashrc_file+'\n') outpath=outdir+'/results/qc/'+samplename+'/QuASAR-QC/'+samplename+'QuASAR-QC.scores.txt' quasar_data=outdir+'/data/forQuASAR' quasar_transform=quasar_data+'/'+samplename+'.quasar_transform' subp.check_output(['bash','-c','mkdir -p '+os.path.dirname(outpath)]) script_comparison.write('${mypython} '+os.path.dirname(os.path.abspath(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))))+"/hifive/bin/find_quasar_quality_score"+' '+quasar_transform+' '+outpath+'\n') script_comparison.write('${mypython} '+os.path.abspath(os.path.dirname(os.path.realpath(__file__)))+"/quasar_split_by_chromosomes_qc.py"+' '+outpath+' '+samplename+'\n') script_comparison.close() run_script(script_comparison_file,running_mode)
def HiCRep_wrapper(outdir,parameters,concise_analysis,samplename1,samplename2,chromo,running_mode,f1,f2,nodefile,resolution): script_comparison_file=outdir+'/scripts/HiCRep/'+samplename1+'.'+samplename2+'/'+chromo+'.'+samplename1+'.vs.'+samplename2+'.sh' subp.check_output(['bash','-c','mkdir -p '+os.path.dirname(script_comparison_file)]) script_comparison=open(script_comparison_file,'w') script_comparison.write("#!/bin/sh"+'\n') script_comparison.write('. '+bashrc_file+'\n') if os.path.isfile(f1) and os.path.getsize(f1)>20: if os.path.isfile(f2) and os.path.getsize(f2)>20: outpath=outdir+'/results/reproducibility/'+samplename1+'.vs.'+samplename2+'/HiCRep/'+chromo+'.'+samplename1+'.vs.'+samplename2+'.scores.txt' subp.check_output(['bash','-c','mkdir -p '+os.path.dirname(outpath)]) hicrepcode=os.path.abspath(os.path.dirname(os.path.realpath(__file__))+"/HiCRep_wrapper.R") script_comparison.write("Rscript "+hicrepcode+' '+f1+' '+f2+' '+outpath+' '+parameters['HiCRep']['maxdist']+' '+str(resolution)+' '+nodefile+' '+parameters['HiCRep']['h']+' '+samplename1+' '+samplename2+'\n') script_comparison.close() run_script(script_comparison_file,running_mode)
def compute_reproducibility(datatype,metadata_pairs,outdir,norm,tmin,tmax,running_mode,concise_analysis): outdir=os.path.abspath(outdir) metadata_pairs=os.path.abspath(metadata_pairs) for chromo_line in gzip.open(outdir+'/data/metadata/chromosomes.gz','r').readlines(): chromo=chromo_line.strip() if chromo not in ['chr1']: continue for line in open(metadata_pairs,'r').readlines(): items=line.strip().split() samplename1,samplename2=items[0],items[1] print 'GenomeDISCO | '+strftime("%c")+' | Computing reproducibility for '+samplename1+'.vs.'+samplename2+' '+chromo script_comparison_file=outdir+'/scripts/reproducibility/'+samplename1+'.vs.'+samplename2+'/'+chromo+'.'+samplename1+'.vs.'+samplename2+'.genomedisco.sh' subp.check_output(['bash','-c','mkdir -p '+os.path.dirname(script_comparison_file)]) script_comparison=open(script_comparison_file,'w') script_comparison.write("#!/bin/sh"+'\n') script_comparison.write('source '+bashrc_file+'\n') f1=outdir+'/data/edges/'+samplename1+'/'+samplename1+'.'+chromo+'.gz' f2=outdir+'/data/edges/'+samplename2+'/'+samplename2+'.'+chromo+'.gz' nodefile=outdir+'/data/nodes/nodes.'+chromo+'.gz' if os.path.isfile(f1) and os.path.getsize(f1)>20: if os.path.isfile(f2) and os.path.getsize(f2)>20: concise_analysis_text='' if concise_analysis: concise_analysis_text=' --concise_analysis' outpath=outdir+'/results/genomedisco/'+samplename1+'.vs.'+samplename2 subp.check_output(['bash','-c','mkdir -p '+outpath]) #todo: remove hardcoded blacklist blacklist='/home/oursu/blacklist.gz' script_comparison.write("$mypython -W ignore "+os.path.abspath("/srv/gsfs0/projects/snyder/oursu/software/git/public_genomedisco/genomedisco/genomedisco/compute_reproducibility.py")+" --m1 "+f1+" --m2 "+f2+" --m1name "+samplename1+" --m2name "+samplename2+" --node_file "+nodefile+" --outdir "+outpath+" --outpref "+chromo+" --m_subsample lowest --approximation 10000000 --norm "+norm+" --method RandomWalks "+" --tmin "+str(tmin)+" --tmax "+str(tmax)+" --transition --blacklist "+blacklist+concise_analysis_text+'\n') script_comparison.close() run_script(script_comparison_file,running_mode) print 'GenomeDISCO | '+strftime("%c")+' | ============================='