def visualize_edges(X, A, Z, threshold, title = ""): '''Visualize the unweighted instance-anchor edges Example: tools.visualize_edges(X, A, Z, 1e-6, alg) ''' d = X.shape[1] assert d == 2 or d == 3, "only 2/3-D edges can be visualized" links = np.where(Z>threshold) # source and target vertices s = X[links[0],:] t = A[links[1],:] fig = pyplot.figure() color=cm.rainbow(np.linspace(0, 1, A.shape[0])) if d == 3: ax = fig.add_subplot(111, projection='3d') ax.view_init(10,-75) edge = lambda i:([s[i,0], t[i,0]], [s[i,1], t[i,1]], [s[i,2], t[i,2]]) if d == 2: ax = fig.add_subplot(111) edge = lambda i:([s[i,0], t[i,0]], [s[i,1], t[i,1]]) for i in xrange(s.shape[0]): ax.plot(*edge(i), c=color[links[1][i],:], alpha=0.6) ax.set_title(title) fig.show()
def plot_energy(): file_list = os.listdir('/home/pankaj/Max_of_convex_code_new/Code/output_logs/synthetic_experiment_logs/') max_len = 0 max_energy= 0 min_energy= 1000000 lines = ["", "--", "-.", ":"] color = iter(cm.rainbow(np.linspace(0, 1, len(file_list)))) for item in file_list: # item = 'linear_L10_0.txt' filename = os.path.join('/home/pankaj/Max_of_convex_code_new/Code/output_logs/synthetic_experiment_logs/', item) #filename = '/home/pankaj/Max_of_convex_code_new/Code/output_logs/synthetic_experiment_logs/linear_L10_7.txt' maxflow_time = [] iter_time = [] energy = [] extract_time(filename, maxflow_time, iter_time, energy) c = next(color) plot_list(energy[1:], c) if(len(energy) > max_len): max_len = len(energy) if(max(energy[1:]) > max_energy): max_energy = max(energy[1:]) if(min(energy) < min_energy): min_energy = min(energy) plt.axis([1, max_len + 1, 0.9*min_energy, 1.1*max_energy]) plt.legend() plt.xlabel('Number of iteration') plt.ylabel('Energy') plt.title('Linear static case: L = 10') plt.show()
def plot_time(): file_list = os.listdir('/home/pankaj/Max_of_convex_code_new/Code/output_logs/synthetic_experiment_logs/') max_len = 0 max_time = 0 lines = ["", "--", "-.", ":"] color = iter(cm.rainbow(np.linspace(0, 1, len(file_list)))) for item in file_list: filename = os.path.join('/home/pankaj/Max_of_convex_code_new/Code/output_logs/synthetic_experiment_logs/', item) maxflow_time = [] iter_time = [] energy = [] extract_time(filename, maxflow_time, iter_time, energy) c = next(color) plot_list(maxflow_time, c) if(len(maxflow_time) > max_len): max_len = len(maxflow_time) if(max(maxflow_time) > max_time): max_time = max(maxflow_time) plt.axis([1, max_len + 1, 0, 1.1*max_time]) plt.legend() plt.xlabel('Number of iteration') plt.ylabel('Time (in s)') plt.title('Linear static case: L = 10') plt.show()
def get_colours(self, ncolours): ''' Returns n colors from the matplotlib rainbow colormap. ''' from matplotlib.pyplot import cm colours = cm.rainbow(np.linspace(0,1,ncolours)) return colours
def plotdisptraj(s, P_UCS, E, E0, UCS, UC, diagnostics): # measured energy dependant offset at FOMS normalized to 0 for EbE0=1 xf1t = lambda EbE0: -.078269*EbE0 + .078269 # + .059449 xf2t = lambda EbE0: -.241473*EbE0 + .241473 # + .229314 xf6t = lambda EbE0: 1.174523*EbE0 - 1.174523 # - 1.196090 xf7t = lambda EbE0: .998679*EbE0 - .998679 # - 1.018895 xf8t = lambda EbE0: .769875*EbE0 - .769875 # - .787049 steps = 6 X = [empty([6, P_UCS+1]) for i in range(steps)] dEbE = linspace(-0.005, 0.005, steps) for deltaE, i in zip(dEbE, range(steps)): # R calculated for every energy (not necessary) gamma = (E+deltaE*E)/E0+1 R = UCS2R(P_UCS, UCS, gamma) X[i][:, 0] = array([0, 0, 0, 0, 0, deltaE]) X[i] = trackpart(X[i], R, P_UCS, P_UCS)*1e3 fig = Figure() ax = fig.add_subplot(1, 1, 1) drawlattice(ax, UC, diagnostics, X, 0) ax.set_xlabel(r'orbit position s / (m)') ax.set_ylabel(r'radial displacement / (mm)') x = [s[UCS[0, :] == 7][i] for i in [0, 1, 5, 6, 7]] color = iter(cm.rainbow(linspace(0, 1, steps))) for i in range(steps): c = next(color) EE0 = 1 + dEbE[i] y = array([xf1t(EE0), xf2t(EE0), xf6t(EE0), xf7t(EE0), xf8t(EE0)])*1e3 ax.plot(x, y, 'o', c=c) ax.plot(s, X[i][0, :], c=c, label=r'$\delta={:g}$\textperthousand'.format(dEbE[i]*1e3)) ax.plot([], [], 'ok', label=r'measured') #ax.get_xaxis().set_visible(False) #leg = ax.legend(fancybox=True, loc=0) #leg.get_frame().set_alpha(0.5) ax.set_xlim([0, nanmax(s)]) return fig
def plot_fcts(axis, x, ys, **plot_kargs): plot_kargs = check_matplot_arguments("linePlot",**plot_kargs) N = len(ys) if not plot_kargs['colors']: plot_kargs['colors']=cm.rainbow(np.linspace(0,1,N)) # matplotlib.rcParams['text.usetex'] = True font_style = {'weight' : 'normal', 'size': plot_kargs['ticks_size'],'family':'serif','serif':['Palatino']} matplotlib.rc('font',**font_style) for y, label, color, lineStyle, opacity in zip(ys,plot_kargs['labels'],plot_kargs['colors'],plot_kargs['lineStyles'],plot_kargs['opacities']): axis.plot(x,y,lineStyle,color=color,label=r'%s'%(label),alpha=opacity) if plot_kargs['grid']==True: axis.grid(True) axis.legend(loc=plot_kargs['legend']) if 'x' in plot_kargs['log']: if 'symx' in plot_kargs['log']: axis.set_xscale('symlog') else: axis.set_xscale('log') if 'symy' in plot_kargs['log']: axis.set_yscale('symlog') elif 'symx' in plot_kargs['log']: print "boh" elif 'y' in plot_kargs['log']: axis.set_yscale('log') if plot_kargs["xrange"]!=0: axis.set_xlim(plot_kargs["xrange"]) if plot_kargs["yrange"]!=0: axis.set_ylim(plot_kargs["yrange"]) axis.set_xlabel(r'%s' %(plot_kargs['xyLabels'][0]),fontsize=plot_kargs["label_size"]) axis.set_ylabel(r'%s' %(plot_kargs['xyLabels'][1]),fontsize=plot_kargs["label_size"]) return axis
def plot_yhat(yhat, data, model_name): ''' Args: yhat: an ndarray of the probability of each event for each class data: dictionary containing relevant data Returns: a plot of the probability that each event in a known classes is predicted to be in a specific class ''' y_test = data['y_test'] w_test = data['w_test'] matplotlib.rcParams.update({'font.size': 16}) bins = np.linspace(0, 1, 30) plt.clf() #find probability of each class for k in np.unique(y_test): fig = plt.figure(figsize=(11.69, 8.27), dpi=100) color = iter(cm.rainbow(np.linspace(0, 1, len(np.unique(y_test))))) #find the truth label for each class for j in np.unique(y_test): c = next(color) _ = plt.hist( yhat[:, k][y_test == j], bins=bins, histtype='step', normed=True, label=data['LabelEncoder'].inverse_transform(j), weights=w_test[y_test == j], color=c, linewidth=1 ) plt.xlabel('P(y == {})'.format(data['LabelEncoder'].inverse_transform(k))) plt.ylabel('Weighted Normalized Number of Events') plt.legend() fig.savefig('p(y=={})_'.format(data['LabelEncoder'].inverse_transform(k)) + model_name + '.pdf')
def class_wise_rocch(y_true_df, y_score_df): """ y_true_df: DataFrame, [samples x classes] y_score_df: DataFrame, [samples x classes] """ # calculate fpr/tpr per class fprs, tprs, aucs, eer_vals = [], [], [], [] for yc, pc in zip(y_true_df, y_score_df): y_true = y_true_df[yc].values y_score = y_score_df[pc].values fpr, tpr, _, y_calibr, p_calibr = sklearn_rocch(y_true, y_score) fprs.append(fpr) tprs.append(tpr) aucs.append(sk_metrics.auc(fpr, tpr)) eer_vals.append(eer(y_calibr, p_calibr)) # plot ROCCH curves fig = plt.figure() ax = fig.add_subplot(1, 1, 1, frameon=True) n_classes = len(y_true_df.columns) color = iter(cm.rainbow(np.linspace(0, 1, n_classes))) for c in range(n_classes): mfom_plt.view_roc_curve(ax, fprs[c], tprs[c], roc_auc=aucs[c], eer_val=eer_vals[c], color=next(color), title='ROC convex hull') fig.tight_layout() plt.show()
def single_genome( alignment_full, number=5): samples=random.sample(range(len(alignment_full)), number) ref=samples[0] rest=samples[1:] fig=plt.figure() fig = plt.figure(figsize=(18, 12)) fig.patch.set_facecolor('w') fig.add_axes=True color=iter(cm.rainbow(numpy.linspace(0,1,number))) i=1 for other in rest: c=next(color) align=[alignment_full[ref], alignment_full[other]] seg=generate_windows(align) x1=[rec[0] for rec in seg] y1=[rec[1] for rec in seg] mean_div=numpy.mean(y1) sub1=plt.subplot(2, 2, i) plt.plot(x1, y1, color=c) plt.axhline(y=mean_div, color='r', linestyle='-') plt.xlabel("Position in Core Genome (bp)") print ref print other plt.ylabel('Pairwise nucleotide diversity', fontsize=16) plt.xlim(0, max(x1)) i=i+1 fig.patch.set_facecolor('w') fig.add_axes=True fig.tight_layout() plt.savefig("pairwise_divergence_statistics.pdf", facecolor=fig.get_facecolor(), edgecolor='black', transparent=True) print "Reference is:" + str(ref) print "Rest are:" + str(rest)
def branch_plot(name, results): if not results: return for res in results: del res['Clock'] del res['Instruct'] del res['Core cyc'] import matplotlib.pyplot as plt from matplotlib.pyplot import cm import numpy as np fig, ax = plt.subplots() fig.canvas.set_window_title(name) num_samples = len(results) num_counters = len(results[0]) width = 1.0 / (num_counters + 1) rects = [] color = cm.rainbow(np.linspace(0, 1, num_counters)) for counter_index in range(num_counters): counter_name = results[0].keys()[counter_index] xs = np.arange(num_samples) + width * counter_index ys = [a[counter_name] for a in results] rects.append(ax.bar(xs, ys, width, color=color[counter_index])) ax.set_ylabel("Count") ax.set_xlabel("Run #") ax.set_title(name) ax.legend((x[0] for x in rects), results[0].keys())
def display_analyze_results(data): plt.ion() fig = plt.figure() ax = fig.add_subplot(111) fig_crvfrq = plt.figure() ax_crvfrqplt = fig_crvfrq.add_subplot(111) #prepare color tol_nr_sctn = np.sum([len(strk) for strk in data['sections']]) color_lettertraj=iter(cm.rainbow(np.linspace(0,1,tol_nr_sctn))) color_crvfrq=iter(cm.rainbow(np.linspace(0,1,tol_nr_sctn))) #plot letter sections in canvas letter_trajs = [] for strk in data['sections']: for sctn in strk: c = next(color_lettertraj) tmp_letter_traj, = ax.plot(np.array(sctn)[:, 0], -np.array(sctn)[:, 1], linewidth=2.0, color=c) letter_trajs+=[tmp_letter_traj] ax.hold(True) ax.hold(False) #frequency analysis for strk_crv, strk_vel, strk_ang in zip(data['crvfrq'], data['velfrq'], data['ang_sections']): for crvt_sctn, vel_sctn, ang_sctn in zip(strk_crv, strk_vel, strk_ang): freq_bins = fftfreq(n=len(ang_sctn), d=ang_sctn[1]-ang_sctn[0]) #cut to show only low frequency part n_freq = len(ang_sctn)/2+1 #<hyin/Sep-25th-2015> need more investigation to see the meaning of fftfreq #some threads on stackoverflow suggests the frequency should be normalized by the length of array #but the result seems weird... #power spectrum coefficient, see Huh et al, Spectrum of power laws for curved hand movements freq = np.abs(freq_bins[0:n_freq]*2*np.pi) beta = 2.0/3.0 * (1+freq**2/2.0)/(1+freq**2+freq**4/15.0) # print 'new section' # print freq # print beta # print np.abs(crvt_sctn[0:n_freq]) c = next(color_crvfrq) ax_crvfrqplt.plot(freq, np.abs(crvt_sctn[0:n_freq])*beta, color=c) ax_crvfrqplt.hold(True) ax_crvfrqplt.plot(freq, np.abs(vel_sctn[0:n_freq]), color=c, linestyle='dashed') ax_crvfrqplt.set_ylabel('Normed Amplitude') ax_crvfrqplt.set_xlabel('Frequency') #cut the xlim ax_crvfrqplt.set_xlim([0, 8]) ax_crvfrqplt.set_ylim([0.0, 1.0]) ax_crvfrqplt.hold(False) plt.draw() return
def plot_straight_tracks(event, labels=None): """ Generate plot of the event with its tracks and noise hits. :param event: pandas.DataFrame with one event. :param labels: numpy.array shape=[n_hits], labels of recognized tracks. :return: matplotlib.pyplot object. """ plt.figure(figsize=(10, 7)) tracks_id = numpy.unique(event.TrackID.values) event_id = event.EventID.values[0] color=cm.rainbow(numpy.linspace(0,1,len(tracks_id))) # Plot hits for num, track in enumerate(tracks_id): X = event[event.TrackID == track].X.values.reshape((-1, 1)) y = event[event.TrackID == track].y.values plt.scatter(X, y, color=color[num]) # Plot tracks if track != -1: lr = LinearRegression() lr.fit(X, y) plt.plot(X, lr.predict(X), label=str(track), color=color[num]) if labels != None: unique_labels = numpy.unique(labels) for lab in unique_labels: if lab != -1: X = event[labels == lab].X.values.reshape((-1, 1)) y = event[labels == lab].y.values lr = LinearRegression() lr.fit(X, y) X = event.X.values.reshape((-1, 1)) plt.plot(X, lr.predict(X), color='0', alpha=0.5) plt.xlabel('X') plt.ylabel('y') plt.legend(loc='best') plt.title('EventID is ' + str(event_id))
def plotGraph(self, blocks, Q, pos=None): numOfActions = len(self.actions) numOfBlocks = len(blocks) plt.figure(1) if not pos: pos = nx.spring_layout(Q) nodeColors = cm.rainbow(np.linspace(0,1,numOfBlocks)) edgeColors = cm.rainbow(np.linspace(0,1,numOfActions)) for i in xrange(len(blocks)): nx.draw_networkx_nodes(Q,pos,nodelist=blocks[i],node_color=nodeColors[i]) for i in xrange(numOfActions): acts = [] for edge in Q.edges(): if(Q.get_edge_data(*edge)["action"]==self.actions[i]): acts.append(edge) nx.draw_networkx_edges(Q,pos,edgelist=acts,edge_color=[edgeColors[i]]*len(acts)) plt.show()
def _get_color_dict(baseline_tagger, cFraction): from matplotlib.pyplot import cm color_dict = {} color=iter(cm.rainbow(np.linspace(0,1,len(cFraction)))) for c_fraction in cFraction: c=next(color) color_dict.update({"DL1c"+str(int(c_fraction*100.)): c,}) color_dict.update({baseline_tagger: "black"}) return color_dict
def plot_latent_variable(epoch): output = f_enc() plt.figure(figsize=(8,8)) color=cm.rainbow(numpy.linspace(0,1,10)) for l,c in zip(range(10),color): ix = numpy.where(dataset[1][1].get_value()==l)[0] plt.scatter(output[ix,0],output[ix,1],c=c,label=l,s=8,linewidth=0) plt.xlim([-5.0,5.0]) plt.ylim([-5.0,5.0]) plt.legend(fontsize=15) plt.savefig('z_epoch' + str(epoch) + '.pdf')
def plot_points_on_background(points, background, noise=False, base_size=200): plt.imshow(background, cmap='gray') colours = cm.rainbow(numpy.linspace(0, 1, len(points))) for colour, (x, y) in zip(colours, points): if noise: x += numpy.random.normal(scale=0.5) y += numpy.random.normal(scale=0.5) plt.scatter(x, y, marker='x', c=colour, s=base_size) plt.axis('off') plt.xlim((0, background.shape[0])) plt.ylim((0, background.shape[1]))
def plot_q_z(data, filename, n_label=10, xlim=None, ylim=None): plt.clf() fig, ax = plt.subplots(ncols=1, figsize=(8,8)) color = cm.rainbow(np.linspace(0,1,n_label)) for l, c in zip(range(10), color): ix = np.where(data[:,2]==l) ax.scatter(data[ix,0], data[ix, 1], c=c, label=l, s=8, linewidth=0) if xlim is not None: ax.set_xlim(xlim) if ylim is not None: ax.set_ylim(ylim) plt.savefig(filename) plt.close()
def plot_dat_variance(TE,TRE): fig, ax = plt.subplots() ax.minorticks_on() color=cm.rainbow(np.linspace(0,1.0,5)) for x in TE: plt.plot(range(1,21,2),[np.array(TE[x][i]).mean() for i in range(len(TE[x]))],linewidth=3,c=color[x-1],label='$2j='+str(x)+'$'+' test') plt.plot(range(1,21,2),[np.array(TRE[x][i]).mean() for i in range(len(TRE[x]))],'--',linewidth=3,c=color[x-1],label='$2j='+str(x)+'$'+' training') plt.xlabel('Number of Nearest Neighbors',fontsize=24) plt.ylabel('Prediction Accuracy', fontsize=24) plt.axis([1,19,0.6,1.0], fontsize=24) plt.legend(bbox_to_anchor=(1.1,-0.11),prop={'size':18},ncol=3) #plt.legend() plt.savefig('Variance.eps', edgecolor='none',bbox_inches='tight')
def plot_graph(time_stamp, HR, SBP, DBP, RR, SpO2): plot = [] plot.append(HR) plot.append(SBP) plot.append(DBP) plot.append(RR) plot.append(SpO2) nums = np.linspace(0,1,5) - 0.01 time_stamp = convert_to_float(time_stamp) min_x = time_stamp[0] max_x = time_stamp[-1] min_y = max_d(HR, SBP, DBP, RR, SpO2) max_y = min_d(HR, SBP, DBP, RR, SpO2) for i in range(5): plt.plot(time_stamp, plot[i], color=cm.rainbow(nums[i])) # fig = plt.figure(1) # ax = fig.add_subplot(111, autoscale_on=False, xlim=(min_x,max_x), ylim=(min_y,max_y)) plt.title("Physiological Data Log") plt.xlabel("Time") plt.ylabel("Value") # plt.text(50,80,"purple: HR") # plt.text(50,70,"blue: SBP") # plt.text(50,60,"green: DBP") # plt.text(50,50,"orange: RR") # plt.text(50,40,"red: SpO2") arrow_width = 6 arrow_shrink = 0.1 arrow_frac = 0.4 plt.annotate("HR", xy=(max_x*4/5,HR[len(time_stamp)*4/5-1]),xytext=(max_x*4/5 - 30,HR[len(time_stamp)*4/5-1] + 10), arrowprops=dict(facecolor='purple', shrink=arrow_shrink, width=arrow_width, frac=arrow_frac)) plt.annotate("SBP", xy=(max_x*2/5,SBP[len(time_stamp)*2/5-1]),xytext=(max_x*2/5 - 30,SBP[len(time_stamp)*2/5-1] + 10), arrowprops=dict(facecolor='blue', shrink=arrow_shrink, width=arrow_width, frac=arrow_frac)) plt.annotate("DBP", xy=(max_x*3/5,DBP[len(time_stamp)*3/5-1]),xytext=(max_x*3/5 - 30,DBP[len(time_stamp)*3/5-1] + 10), arrowprops=dict(facecolor='green', shrink=arrow_shrink, width=arrow_width, frac=arrow_frac)) plt.annotate("RR", xy=(max_x/5,RR[len(time_stamp)/5-1]),xytext=(max_x/5 - 30,RR[len(time_stamp)/5-1] + 10), arrowprops=dict(facecolor='orange', shrink=arrow_shrink, width=arrow_width, frac=arrow_frac)) plt.annotate("SpO2", xy=(max_x,SpO2[-1]),xytext=(max_x - 30,SpO2[len(time_stamp)-1] + 10), arrowprops=dict(facecolor='red', shrink=arrow_shrink, width=arrow_width, frac=arrow_frac)) plt.show()
def cluster_and_plot(list_of_lists, plot_full_file_name): """ the second stage of the plotting that clusters and plots the data TODO's: format graph :param list_of_lists: list of lists that has the pertinent plotting data :param plot_full_file_name: the file name of the plot to be saved """ logger = logging.getLogger() try: list_count = 1 # count for appending to file names (necessary for split plots) plot_file_name = plot_full_file_name[:-4] # strip .png off file name so adjustments can be made # iterate over lists -- needed if plot is split into multiple for list in list_of_lists: # add count for split plots plot_full_file_name = plot_file_name + '-{}.png'.format(list_count) rank_list, name_list, position_list, average_rank_list, standard_deviation_list, k_value = list[0], list[1], list[2], list[3], list[4], list[5] # empty list that will be converted into array average_rank_array = [] for n in range(len(average_rank_list)): # build list from item and append the list to the list of lists item_list = [average_rank_list[n]] average_rank_array.append(item_list) # convert the list of lists to an array X = np.array(average_rank_array) # initialize KMeans and fit over the array kmeans = KMeans(n_clusters=k_value) kmeans.fit(X) centroids = kmeans.cluster_centers_ # not used here # array of labels where a cluster value is assigned to each item labels = kmeans.labels_ # color list that will automatically generate based on number of clusters colors = [] color_cycle = iter(cm.rainbow(np.linspace(0, 5, len(labels)))) for i in range(len(labels)): c = next(color_cycle) colors.append(c) # iterate over array and plot values, standard deviation, and color by clusters for i in range(len(X)): plt.errorbar(X[i][0], rank_list[i], xerr=standard_deviation_list[i], marker='.', markersize=4, color=colors[labels[i]], ecolor=colors[labels[i]]) position = position_list[i][10:].upper() if len(position_list[i]) > 10 else position_list[i].upper() plt.text(X[i][0] + standard_deviation_list[i] + 1, rank_list[i], "{} {} ({})".format(name_list[i], position, rank_list[i]), size=6, color=colors[labels[i]], ha="left", va="center") plt.gca().invert_yaxis() # top-left of graph should start at 1 # plt.show() plt.savefig(plot_full_file_name, bbox_inches='tight') # save the png file plt.clf() # clear plot after use otherwise subsequent iterations list_count += 1 except Exception as e: logger.info("Clustering and plotting failed with: {}".format(e))
def replicator_trajectory(self, t_vector, population_fraction, **kwargs): soln = odeint(replicator_equation, population_fraction, t_vector, args=(self.number_of_players,)) orbits = [soln[:, i] for i in range(len(population_fraction))] # Plotting stuff plt.rc("lines", linewidth=2.0) plt.figure(figsize=(20, 4)) color = iter(cm.rainbow(np.linspace(0, 1, len(orbits)))) for i in range(len(orbits)): c = next(color) plt.plot(t_vector, orbits[i], c=c, label=self.network_game.strategy_names[i]) plt.rc("lines", linewidth=2.0) plt.legend() for i in range(len(orbits)): print(orbits[i][-1])
def plot_spikes(self,ax,start,end): '''plot spikes with hlines''' from matplotlib.pyplot import cm totclu = self.Clu.totClu locclu = self.Clu.localClu ncol = max(max(locclu),10) color=cm.rainbow(np.linspace(0,1,ncol)) spk_tic, spk_clu = self.get_spikes(start,end) spk_tim = self.tic_to_time(spk_tic) for clu in totclu: idx = clu-1 sel = spk_clu == clu pin = locclu[idx]-1 ax.plot(spk_tim[sel],spk_clu[sel],'|',markersize=4,color=color[pin]) ax.set_xlabel("time (s)") ax.set_ylabel("cluster ID")
def plot_regression(yhat, data, model_name): ''' Args: yhat: numpy array of dim [n_ev, n_classes] with the net predictions on the test data data: an OrderedDict containing all X, y, w ndarrays for all particles (both train and test), e.g.: data = { "X_jet_train" : X_jet_train, "X_jet_test" : X_jet_test, "X_photon_train" : X_photon_train, "X_photon_test" : X_photon_test, "y_train" : y_train, "y_test" : y_test, "w_train" : w_train, "w_test" : w_test } Saves: 'regression_test.pdf': a histogram plotting yhat containing the predicted masses ''' y_test = data['y_test'] w_test = data['w_test'] color = iter(cm.rainbow(np.linspace(0, 1, len(np.unique(y_test))))) matplotlib.rcParams.update({'font.size': 16}) plt.clf() fig = plt.figure(figsize=(11.69, 8.27), dpi=100) bins = np.linspace( min(min(yhat), min(y_test)), max(max(yhat), max(y_test)), 30) for k in np.unique(y_test): c = next(color) _ = plt.hist(yhat[y_test == k], bins=bins, histtype='step', normed=True, label=str(k), weights=w_test[y_test == k], color=c, linewidth=1) plt.ylabel('Weighted Events') plt.legend(prop={'size': 10}, fancybox=True, framealpha=0.5) fig.savefig('regression' + model_name + '.pdf')
def plot(self): if self.args.overlay: st = Stream() color = iter(cm.rainbow(np.linspace(0, 1, len(self.file_list)))) for input_file in self.file_list: for tr in read(input_file): c = next(color) times = [ (tr.stats.starttime + t).datetime for t in tr.times()] plt.plot(times, tr.data, linestyle="-", marker=None, color=c, label=tr.id) plt.grid() plt.legend() plt.show() else: st = Stream() for input_file in self.file_list: st += read(input_file) st.plot()
def plot_stuff(quantities, inputs, callable, labels=None, callable_args={}, **kwargs): from matplotlib.pyplot import cm if not isinstance(inputs, list): inputs = [inputs] if not isinstance(quantities, list): quantities = [quantities] # Check if I have a folder of models: tuning = False if len(inputs)==1: info_logs = [os.path.join(dirpath, f) for dirpath, dirnames, files in os.walk(inputs[0]) for f in files if f.startswith('info-tuning')] if len(info_logs)!=0: tuning = True inputs, labels = get_tuning_models(inputs[0], **kwargs) N, Q = len(inputs), len(quantities) if labels is None: labels = ['']*N colors = cm.rainbow(np.linspace(0,1,N)) lineStyles = ['-', '--', '--']*10 plot_kwargs = {} plot_kwargs['lineStyles'] = [] plot_kwargs['colors'] = [] plot_kwargs['labels'] = [] additional_kwargs = callable(inputs[0], quantities[0], **callable_args)[1] plot_kwargs['xyLabels'] = [additional_kwargs['xyLabels'][0], ''] xs, ys = [0.]*N*Q, [0.]*N*Q for i, input in enumerate(inputs): for q, quantity in enumerate(quantities): xs[q+i*Q], ys[q+i*Q] = callable(input, quantity, **callable_args)[0] plot_kwargs['colors'].append(colors[i]) plot_kwargs['lineStyles'].append(lineStyles[q]) plot_kwargs['labels'].append(labels[i] if q==0 else '') return xs, ys, plot_kwargs
def pl_param_chain( par_name, gs, min_max_p, cp_r, nwalkers, nsteps, nburn, m_accpt_fr, varIdxs, pars_chains): ''' Parameter sampler chain. ''' plot_dict = { 'metal': [8, 12, 0, 1, 0], 'age': [8, 12, 1, 2, 1], 'ext': [8, 12, 2, 3, 2], 'dist': [8, 12, 3, 4, 3], 'mass': [8, 12, 4, 5, 4], 'binar': [8, 12, 5, 6, 5] } labels = [r'$z$', r'$\log(age)$', r'$E_{{(B-V)}}$', r'$(m-M)_o$', r'$M\,(M_{{\odot}})$', r'$b_{{frac}}$'] gs_x1, gs_x2, gs_y1, gs_y2, cp = plot_dict[par_name] ax = plt.subplot(gs[gs_y1:gs_y2, gs_x1:gs_x2]) if cp == 0: plt.title("Chains (walkers): {} ; MAF: {:.3f}".format( nwalkers, m_accpt_fr)) if cp == 5: plt.xlabel("Steps") else: ax.tick_params(labelbottom=False) plt.ylabel(labels[cp]) ax.set_xlim(0, nburn + nsteps) if cp in varIdxs: c_model = varIdxs.index(cp) pre_bi, post_bi = pars_chains color = iter(cm.rainbow(np.linspace(0, 1, nwalkers))) for w1, w2 in zip(*[pre_bi[c_model].T, post_bi[c_model].T]): # Burn-in stage plt.plot(range(nburn), w1, c='grey', lw=.5, alpha=0.5) # Post burn-in. c = next(color) plt.plot(np.arange(nburn, nburn + nsteps), w2, c=c, lw=.5, alpha=0.5) plt.axhline(y=float(cp_r[cp]), color='k', lw=1.5, zorder=4) ymin, ymax = np.min(post_bi[c_model]), np.max(post_bi[c_model]) ax.set_ylim(ymin, ymax)
def plot_1d(X,Ys,Vs,D,labels): col=cm.rainbow(np.linspace(0,1,D)) fig1,ax1 = plt.subplots() w = 5 fig2,ax2 = plt.subplots() # plotting infered functions against true functions for d in range(1): Yd = Ys[d] Vd = Vs[d] o = np.argsort(X[:,d]) # ax1.plot(X[o,d],Fs[o,d],'--',linewidth=4,c=col[d]) ax1.plot(X[o,d],Yd[o],'-',c=col[d]) ax1.fill_between(X[o,d], y1=np.squeeze(Yd[o]+np.sqrt(Vd[o])), y2=np.squeeze(Yd[o]-np.sqrt(Vd[o])),facecolor=col[d],alpha=.5) for d in range(1,D): Yd = Ys[d] Vd = Vs[d] o = np.argsort(X[:,d]) # ax1.plot(X[o,d],Fs[o,d],'--',linewidth=4,c=col[d]) ax2.plot(X[o,d],Yd[o],'-',c=col[d]) ax2.fill_between(X[o,d], y1=np.squeeze(Yd[o]+np.sqrt(Vd[o])), y2=np.squeeze(Yd[o]-np.sqrt(Vd[o])),facecolor=col[d],alpha=.5) ax1.set_xlabel(labels[0][1],fontsize=20) ax1.set_ylabel(labels[0][2],fontsize=20) ax1.set_title(labels[0][0],fontsize=20) ax2.set_xlabel(labels[1][1],fontsize=20) ax2.set_ylabel(labels[1][2],fontsize=20) ax2.set_title(labels[1][0],fontsize=20) # plt.show() timestr = time.strftime("%Y%m%d-%H%M%S") plt.savefig(OUTPUT_PATH+timestr+'.svg') plt.close()
def barchart(learning_cost): plt.figure(figsize=(13, 7)) colors = cm.rainbow(np.linspace(0, 1, len(learning_cost.cost.keys()))) for model_name, color in zip(learning_cost.cost.keys(), colors): values = learning_cost.cost[model_name] plt.plot([idx for idx in range(0, len(values))], values, color=color, label=model_name) for idx in range(0, len(values)): plt.text(idx, values[idx], round(values[idx], 4)) plt.title('Log-loss of the different models in the different fold') plt.xlabel('No. of Fold') plt.ylabel('Log-loss') plt.grid(True) fontP = FontProperties() fontP.set_size('small') plt.legend(loc=8, ncol=3, fancybox=True, shadow=True, prop=fontP) plt.ylim((0.45, 0.52)) plt.show()
def plot_2d(X, n_func, f_indices, Ys,Vs,D,labels): col=cm.rainbow(np.linspace(0,1,3)) w = 5 # plotting infered functions against true functions for c in range(n_func): Yd = Ys[c] Vd = Vs[c] if len(f_indices[c])==1: fig1,ax1 = plt.subplots() d = f_indices[c][0] o = np.argsort(X[:,d]) ax1.plot(X[o,d],Yd[o],'-',c=col[d]) ax1.fill_between(X[o,d], y1=np.squeeze(Yd[o]+np.sqrt(Vd[o])), y2=np.squeeze(Yd[o]-np.sqrt(Vd[o])),facecolor=col[d],alpha=.5) ax1.set_xlabel('$x$ ',fontsize=20) ax1.set_ylabel('$\\alpha x$ ',fontsize=20) # plt.show() timestr = time.strftime("%Y%m%d-%H%M%S") plt.savefig(OUTPUT_PATH+timestr+'.svg') plt.close() elif len(f_indices[c])==2: fig1,ax1 = plt.subplots() ax1.scatter(X[o,f_indices[c][1]], X[o,f_indices[c][0]], c=Yd[o]) print Yd.shape ax1.set_xlabel(labels[1],fontsize=20) ax1.set_ylabel(labels[2],fontsize=20) ax1.set_title(labels[0],fontsize=20) # plt.show() timestr = time.strftime("%Y%m%d-%H%M%S") plt.savefig(OUTPUT_PATH+timestr+'.svg') plt.close()
def Main(): color=iter(cm.rainbow(np.linspace(0,1,len(T_baseList)))) plt.subplot(1,1,1) X = np.linspace(1, 12, 365, endpoint=True) for i in range(len(T_baseList)): c=next(color) plt.plot(X, gdd_Tbase(i),c=c,label ='T_base = '+str(T_baseList[i])) plt.legend(loc='upper left') ax = plt.gca() ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.spines['bottom'].set_position(('data',0)) ax.yaxis.set_ticks_position('left') ax.spines['left'].set_position(('data',0)) for label in ax.get_xticklabels() + ax.get_yticklabels(): label.set_fontsize(8) label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.65)) ax.set_xlabel('Months', color='black', fontsize=14) ax.set_ylabel('Cumulative GDD on different T_bases', color='black', fontsize=14) plt.title("Accumulated Growing Degree Days in St.John's", color="black", fontsize=14) plt.savefig("./Plots/Op3.png")
def plot_summary_2(vars_all, rwa, rwf, rwfg, time_unit=1.0e6): ''' Particle simulation overview plots. Inputs: vars (dictionary containing many quantities at the particle position, rwa: RW field amplitude rwf: RW starting frequency rwfg: RW frequency gradient ''' num_particles = len(vars_all) colors = cm.rainbow(np.linspace(0, 1, num_particles)) if time_unit == 1.0e6: time_label = 'time $[\mu s]$' else: time_label = 'time $[10^{%f} s]$' % (np.log10(1.0 / time_unit)) figg = plt.figure(figsize=(18, 10)) for nop in range(1, num_particles + 1): vars = vars_all['%s' % (str(nop))] # eliminate last 2 points to avoid visualization issues for 'dead' particles for i in range(len(vars)): vars[vars.keys()[i]] = vars[vars.keys()[i]][:-2] Emag = np.sqrt(vars['Ex']**2 + vars['Ey']**2) rot_angle = np.arccos(vars['xgc'] / vars['rgc']) # in radians dt_s = np.diff(vars['time'])[0] / time_unit rot_freq = np.abs(np.gradient(rot_angle, dt_s)) / (2 * np.pi) # in Hz # low-pass filter of rotation frequency to average over bouncing & gyration window_length = int(len(vars['time']) / 32.0) if np.mod(window_length, 2) == 0: window_length += 1 #window_length = 101 #must be odd f_ave = savgol_filter(rot_freq, window_length, 1) # Compute E_{theta} and E_r E_r = vars['Ex'] * np.cos(rot_angle) + vars['Ey'] * np.sin(rot_angle) E_theta = -vars['Ex'] * np.sin(rot_angle) + vars['Ey'] * np.cos( rot_angle) vExB_r = E_theta * vars['Bz'] vExB_tor = -E_r * vars['Bz'] #vpar=2.0*vars['Kpara']*qe/me #vperp=vpar=2.0*vars['Kperp']*qe/me # Summary plot (style #2): ax001 = plt.subplot(421) ax001.plot(vars['time'], vars['Psi_g'] * 1.0e4, c=colors[nop - 1]) ax001.set_ylabel(r'$\Psi_{gc}\times 10^4 [Tm^2]$') ax001.grid() ax002 = plt.subplot(422, sharex=ax001) ax002.plot(vars['time'], vars['mu'], c=colors[nop - 1]) ax002.set_ylabel(r'$\mu [Am^2]$') ax002.grid() ax003 = plt.subplot(423, sharex=ax001) ax003.plot(vars['time'], vars['Kpara'], c=colors[nop - 1]) ax003.set_ylabel(r'$K_{||} [eV]$') ax003.grid() ax004 = plt.subplot(424, sharex=ax001) ax004.plot(vars['time'], vars['Kperp'], c=colors[nop - 1]) ax004.set_ylabel(r'$K_{\perp} [eV]$') ax004.grid() ax005 = plt.subplot(425, sharex=ax001) ax005.plot(vars['time'], vars['rgc'], c=colors[nop - 1]) ax005.set_ylabel(r'$r_{gc} [m]$') ax005.grid() ax006 = plt.subplot(426, sharex=ax001) ax006.plot(vars['time'], vars['B'] * 1.0e3, c=colors[nop - 1]) ax006.set_ylabel(r'$B_{tot} [mT]$') ax006.grid() if num_particles == 1: ccc = 'r' else: ccc = colors[nop - 1] f_RW = rwf + rwfg * vars['time'] / time_unit ax007 = plt.subplot(427, sharex=ax001) ax007.set_xlabel(r'%s' % time_label) ax007.set_ylabel(r'$f_{tor} [kHz]$') ax007.plot(vars['time'], rot_freq / 1.0e3, c=colors[nop - 1]) ax007.plot(vars['time'], f_ave / 1.0e3, c=ccc, linewidth=3.0) if rwa != 0: ax007.plot(vars['time'], f_RW / 1.0e3, c='k', linewidth=4.0, label='$f_{RW}$') if nop == 1 and rwa != 0: plt.legend(loc='best').draggable() ax007.grid() ax008 = plt.subplot(428, sharex=ax001) ax008.set_xlabel(r'%s' % time_label) ax008.set_ylabel(r'$v_{E\times B,r} [m/s^{-1}]$') ax008.plot(vars['time'], vExB_r, c=colors[nop - 1]) ax008.grid()
def plot_datasets(data_handlers, inputs=None, predictions=None, labels=None, show=True, filename=None, figsize=(10, 6)): """Plot several datasets of this class in one plot. Args: data_handlers: A list of GaussianData objects. inputs (optional): A list of numpy arrays representing inputs for each dataset. predictions (optional): A list of numpy arrays containing the predicted output values for the given input values. labels (optional): A label for each dataset. show: Whether the plot should be shown. filename (optional): If provided, the figure will be stored under this filename. figsize: A tuple, determining the size of the figure in inches. """ n = len(data_handlers) assert ((inputs is None and predictions is None) or \ (inputs is not None and predictions is not None)) assert ((inputs is None or len(inputs) == n) and \ (predictions is None or len(predictions) == n) and \ (labels is None or len(labels) == n)) fig, ax = plt.subplots(figsize=figsize) # plt.figure(figsize=figsize) plt.title('GaussianMixture tasks', size=20) # We need to produce a heatmap that spans all tasks. min_x = np.zeros((2, n)) max_x = np.zeros((2, n)) for i in range(n): data = data_handlers[i] train_x = data.get_train_inputs() test_x = data.get_test_inputs() mu = data._mean # dx = np.abs(np.vstack([train_x, test_x]) - mu[None, :]).max(axis=0) dx = max( np.abs(train_x - mu[None, :]).max(), np.abs(test_x - mu[None, :]).max()) min_x[:, i] = mu - dx max_x[:, i] = mu + dx min_x = min_x.min(axis=1) max_x = max_x.max(axis=1) slack = (max_x - min_x) * 0.02 min_x -= slack max_x += slack grid_size = 1000 x1 = np.linspace(start=min_x[0], stop=max_x[0], num=grid_size) x2 = np.linspace(start=min_x[1], stop=max_x[1], num=grid_size) X1, X2 = np.meshgrid(x1, x2) X = np.vstack([X1.ravel(), X2.ravel()]).T # Problem: Now that we have the underlying X mesh, how do we compute the # heatmap. Since every Gaussian has full support, we can't draw a # heatmap that displays all tasks with their correct Y value. # One options would be to just add all heat maps. For small variances # this would look "almost" correct. # Another option is to compute Voronoi cells for all tasks and compute # at each mesh position the y value corresponding to the task with the # nearest mean. # We decide here to compute y based on the nearest neighor, as this # seems to be the "most correct" plotting option. means = [d._mean for d in data_handlers] # Plot Voronoi diagram for debugging. # from scipy.spatial import Voronoi, voronoi_plot_2d # vor = Voronoi(means) # voronoi_plot_2d(vor) vor_tree = cKDTree(means) _, minds = vor_tree.query(X) Y = np.empty(X.shape[0]) for i in range(n): mask = minds == i Y[mask] = data_handlers[i]._map(X[mask, :]).squeeze() Y = Y.reshape(X1.shape) f = plt.contourf(X1, X2, Y) plt.colorbar(f) colors = cm.rainbow(np.linspace(0, 1, n)) phandlers = [] plabels = [] for i, data in enumerate(data_handlers): if labels is not None: lbl = labels[i] else: lbl = 'Predictions %d' % i if inputs is not None: p = plt.scatter(inputs[i][:, 0], inputs[i][:, 1], edgecolors=colors[i], facecolor=f.cmap( f.norm(predictions[i].squeeze()))) phandlers.append(p) plabels.append(lbl) plt.legend(phandlers, plabels) plt.xlabel('x1') plt.ylabel('x2') if filename is not None: plt.savefig(filename, bbox_inches='tight') if show: plt.show() return fig
fig, axesb = plt.subplots(1,figsize=(10, 8)) for i in nhj.keys(): axesb.plot(nhj[i][0],nhj[i][1],"-") #axesb.axvline(nhj[i][0][0],0.0,nhj[i][1][0], color='k', linestyle='--') axesb.stem(xtj,ytj,linefmt='--', markerfmt=' ', basefmt=' ') #############cell 4################## xtj #############cell 5################ nX=['n0/','n1/','n2/','n3/','n4/','n5/','n6/','n7/','n8/'] fig, axesa = plt.subplots(1,figsize=(10, 8)) fig, axesb = plt.subplots(1,figsize=(10, 8)) color=iter(cm.rainbow(np.linspace(0,1,len(nX)))) u=0 #nx='n1/' for kj in nX: ltj={} nhj={} xtj=[] ytj=[] ztj=[] n=0 for j in xi: fin=pth+folder+subf+subf2+runsx+kj+'pts'+str(j)+'plotdata.p' #print fin f=open(fin,"rb") A=pickle.load(f)
def plot_bhp_slices(bhp_slices, bin_edges, bin_units='time', slice_range=None, new_fig=True, show_flag=True, log_flag=False): ''' Plot bhp_slices on same axes, normalized by integral Parameters ---------- bhp_slices : ndarray Array of bhp slices. Dimensions: # slices x len(dt_bin_centers) bin_edges : ndarray One-dimensional array of bin edges, time or energy bin_units : str, optional Units for labels. 'time' or 'energy' slice_range : ndarray Array of slice ranges. Dimensions: # slices x 2 (min, max) Either time or energy new_fig : bool, optional Option to start new figure show_flag : bool, optional Option to display Returns ------- legend_text : str String of legend text ''' if new_fig: plt.figure(figsize=(4, 3)) legend_text = [] color = iter(cm.rainbow(np.linspace( 0, 1, bhp_slices.shape[0]))) # Set up colors for plotting for i in range(bhp_slices.shape[0]): # Loop through slices c = next(color) plot_bhp_slice(bhp_slices[i, :], bin_edges, bin_units, slice_range[i, :], normalized='int', c=c, clear=False, new_fig=False, title=False) if slice_range is not None: legend_text.append('{:04.2f} to {:04.2f}'.format( np.min(slice_range[i, :]), np.max(slice_range[i, :]))) plt.legend(legend_text) plt.title('Slices normalized by integral') # Hack legend ax = plt.gca() leg = ax.get_legend() color = iter(cm.rainbow(np.linspace(0, 1, bhp_slices.shape[0]))) # Reset colors for i in range(bhp_slices.shape[0]): # Make legend c = next(color) leg.legendHandles[i].set_color(c) if show_flag: plt.show() return legend_text
def plot(self, mode: str = 'frequency', depth_bin_size: float = 5.0): """ Plot all outermost points binned in the depth dimension according to the provided size. Each plot is organized by the given mode, if mode is frequency will plot once per frequency, such that the colors let you know the extinction at each frequency. Parameters ---------- mode allowable plot mode, must be one of "frequency", "mode", "modetwo" depth_bin_size bin size in meters for the depth, size of 1 will produce one point for each meter of depth """ if self.depth is None: print( 'Data was not successfully loaded, PingPeriodTest must be recreated' ) return fig = plt.figure() totalmindepth = 9999 totalmaxdepth = 0 totalmaxperiod = 0 groups, comparison, lbl = self._build_groups(mode) colors = iter(cm.rainbow(np.linspace(0, 1, len(groups)))) for grp in groups: print('Building plot for {}={}'.format(mode, grp)) idx = comparison == grp dpth_by_idx = self.depth[idx] diff_by_idx = self.time_dif[idx] mindepth = np.int(np.min(dpth_by_idx)) maxdepth = np.ceil(np.max(dpth_by_idx)) totalmindepth = min(mindepth, totalmindepth) totalmaxdepth = max(maxdepth, totalmaxdepth) bins = np.linspace( mindepth, maxdepth, max(int((maxdepth - mindepth) / depth_bin_size), 5)) dpth_indices = np.digitize(dpth_by_idx, bins) - 1 diff_vals = np.array([ diff_by_idx[dpth_indices == i].mean() for i in range(len(bins) - 1) if i in dpth_indices ]) dpth_vals = np.array( [bins[i] for i in range(len(bins) - 1) if i in dpth_indices]) totalmaxperiod = max(totalmaxperiod, np.max(diff_vals)) c = next(colors) lbl, grp = self._translate_label(mode, grp, lbl) plt.plot(dpth_vals, diff_vals, c=c, label=lbl.format(grp)) # self._plot_depth_guidelines(totalmindepth, totalmaxdepth) plt.title('{} (SN{}): {} by {}'.format(self.sonartype, self.serialnum, self.name, mode)) plt.xlabel('Depth (meters, +down)') plt.ylabel('Period of Ping (seconds)') plt.ylim(0, totalmaxperiod * 2) plt.xlim(0, totalmaxdepth * 2) plt.legend() plt.show()
'" width="50%" /> \n') g.write('</div>\n') n_spec[kind] += 1 g.write('</div>\n') g.write('</div> \n') g.write('</body> \n') g.write('</html> \n') g.close() for fig in ["log", "linear"]: for spec in ["TT", "TE", "ET", "EE"]: plt.figure(figsize=(12, 12)) color = iter(cm.rainbow(np.linspace(0, 1, n_spec["cross"] + 1))) if fig == "log": plt.semilogy() exp_name = "" for id_sv1, sv1 in enumerate(surveys): arrays_1 = d["arrays_%s" % sv1] for id_ar1, ar1 in enumerate(arrays_1): for id_sv2, sv2 in enumerate(surveys): arrays_2 = d["arrays_%s" % sv2] for id_ar2, ar2 in enumerate(arrays_2): if (id_sv1 == id_sv2) & (id_ar1 > id_ar2): continue if (id_sv1 > id_sv2): continue c = next(color)
def plot_irc_data(axes, file, title, ntwl, cnstfile, saefile, dir, trained): Eact, xyz, typ, Rc = pyg.read_irc(file) Rc = Rc[:, 1] Rc = Rc[::-1] print(Eact.shape, Rc.shape, xyz.shape) # Shift reference to reactant #Eact = Eact[::-1] Eact = hdt.hatokcal * (Eact - Eact[-1]) # Plot reference results axes.scatter(Rc, Eact, color='black', linewidth=3) # Plot ANI results color = cm.rainbow(np.linspace(0, 1, len(ntwl))) terr = np.zeros(len(ntwl)) derr = np.zeros(len(ntwl)) berr = np.zeros(len(ntwl)) for i, (nt, c) in enumerate(zip(ntwl, color)): ncr = pync.conformers(dir + nt[0] + cnstfile, dir + nt[0] + saefile, rcdir + nt[0] + 'networks/', 0, True) # Set the conformers in NeuroChem ncr.setConformers(confs=xyz, types=list(typ)) # Compute Energies of Conformations E1 = ncr.energy() # Shift ANI E to reactant E1 = hdt.hatokcal * (E1 - E1[-1]) # Calculate error errn = hdt.calculaterootmeansqrerror(E1, Eact) terr[i] = errn derr[i] = np.abs( np.abs((E1[0] - E1[-1])) - np.abs((Eact[0] - Eact[-1]))) berr[i] = np.abs(E1.max() - Eact.max()) # Plot axes.plot(Rc, E1, 'r--', color=c, label="[" + str(i) + "]: " + "{:.1f}".format(berr[i]), linewidth=2) #axes.set_xlim([Rc.min(), Rc.max()]) #axes.set_ylim([-15, 70]) axes.legend(loc="upper left", fontsize=7) if trained: axes.set_title(title, color='green', fontdict={'weight': 'bold'}, x=0.83, y=0.70) else: axes.set_title(title, color='red', fontdict={'weight': 'bold'}, x=0.83, y=0.70) return terr, derr, berr
def coverage(params, map_struct, coverage_struct, catalog_struct=None,plot_sun_moon=False): unit='Gravitational-wave probability' cbar=False plotName = os.path.join(params["outputDir"],'mollview_coverage.pdf') plt.figure() hp.mollview(map_struct["prob"],title='',unit=unit,cbar=cbar,cmap=cmap) hp.projplot(coverage_struct["data"][:,0], coverage_struct["data"][:,1], 'wx', lonlat=True, coord='G') add_edges() plt.show() plt.savefig(plotName,dpi=200) plt.close('all') idx = np.isfinite(coverage_struct["data"][:,4]) if not idx.size: return min_time = np.min(coverage_struct["data"][idx,4]) max_time = np.max(coverage_struct["data"][idx,4]) plotName = os.path.join(params["outputDir"],'coverage.pdf') plt.figure(figsize=(10,8)) ax = plt.gca() for ii in range(len(coverage_struct["ipix"])): data = coverage_struct["data"][ii,:] filt = coverage_struct["filters"][ii] ipix = coverage_struct["ipix"][ii] patch = coverage_struct["patch"][ii] FOV = coverage_struct["FOV"][ii] if filt=="g": color = "g" elif filt=="r": color = "r" else: color = "k" plt.scatter(data[2],data[5],s=20,color=color) plt.xlabel("Time [MJD]") plt.ylabel("Tile Number") plt.show() plt.savefig(plotName,dpi=200) plt.close('all') plotName = os.path.join(params["outputDir"],'tiles_coverage.pdf') plt.figure() hp.mollview(map_struct["prob"],title='',unit=unit,cbar=cbar, cmap=cmap) add_edges() ax = plt.gca() for ii in range(len(coverage_struct["ipix"])): data = coverage_struct["data"][ii,:] filt = coverage_struct["filters"][ii] ipix = coverage_struct["ipix"][ii] patch = coverage_struct["patch"][ii] FOV = coverage_struct["FOV"][ii] #hp.visufunc.projplot(corners[:,0], corners[:,1], 'k', lonlat = True) if patch == []: continue patch_cpy = copy.copy(patch) patch_cpy.axes = None patch_cpy.figure = None patch_cpy.set_transform(ax.transData) hp.projaxes.HpxMollweideAxes.add_patch(ax,patch_cpy) #tiles.plot() if plot_sun_moon: #plot sun and moon position at the beginning of the observation start_time = params['gpstime'] start_time = Time(start_time, format='gps', scale='utc') sun_position = get_sun(start_time) moon_position = get_moon(start_time) hp.visufunc.projscatter(sun_position.ra, sun_position.dec,lonlat=True,color='yellow') hp.visufunc.projscatter(moon_position.ra, moon_position.dec,lonlat=True,color='grey') #also plot (in smaller scale) sun and moon position for the 7 following days #This allow to show the path of both sun and moon for the coming days dt = 21600 #1/4 day for i in range(1,29): #29 is 4*7 new_time = params['gpstime'] + (dt*i) new_time = Time(new_time, format='gps', scale='utc') new_moon_position = get_moon(new_time) hp.visufunc.projscatter(new_moon_position.ra, new_moon_position.dec,lonlat=True,color='black',marker='.',s=1) if not i % 8: #only plot point for the sun every two days in order to avoid overlap new_sun_position = get_sun(new_time) hp.visufunc.projscatter(new_sun_position.ra, new_sun_position.dec,lonlat=True,color='black',marker='.',s=1) plt.show() plt.savefig(plotName,dpi=200) plt.close('all') diffs = [] if params["tilesType"] == "galaxy": coverage_ras = coverage_struct["data"][:,0] coverage_decs = coverage_struct["data"][:,1] coverage_mjds = coverage_struct["data"][:,2] for ii in range(len(coverage_ras)-1): current_ra, current_dec = coverage_ras[ii], coverage_decs[ii] current_mjd = coverage_mjds[ii] dist = angular_distance(current_ra, current_dec, coverage_ras[ii+1:], coverage_decs[ii+1:]) idx = np.where(dist <= 1/3600.0)[0] if len(idx) > 0: jj = idx[0] diffs.append(np.abs(coverage_struct["data"][ii,2] - coverage_struct["data"][jj,2])) else: for ii in range(len(coverage_struct["ipix"])): ipix = coverage_struct["ipix"][ii] for jj in range(len(coverage_struct["ipix"])): if ii >= jj: continue if coverage_struct["telescope"][ii] == coverage_struct["telescope"][jj]: continue ipix2 = coverage_struct["ipix"][jj] overlap = np.intersect1d(ipix, ipix2) rat = np.array([float(len(overlap)) / float(len(ipix)), float(len(overlap)) / float(len(ipix2))]) if np.any(rat > 0.5): diffs.append(np.abs(coverage_struct["data"][ii,2] - coverage_struct["data"][jj,2])) filename = os.path.join(params["outputDir"],'tiles_coverage_hist.dat') fid = open(filename, 'w') for ii in range(len(diffs)): fid.write('%.10f\n' % diffs[ii]) fid.close() plotName = os.path.join(params["outputDir"],'tiles_coverage_hist.pdf') fig = plt.figure(figsize=(12, 8)) #hist, bin_edges = np.histogram(diffs, bins=20) bins = np.linspace(0.0, 24.0, 25) plt.hist(24.0*np.array(diffs), bins=bins) plt.xlabel('Difference Between Observations [hours]') plt.ylabel('Number of Observations') plt.show() plt.savefig(plotName,dpi=200) plt.close('all') gpstime = params["gpstime"] event_mjd = Time(gpstime, format='gps', scale='utc').mjd colors=cm.rainbow(np.linspace(0,1,len(params["telescopes"]))) plotName = os.path.join(params["outputDir"],'tiles_coverage_int.pdf') fig = plt.figure(figsize=(12, 8)) gs = fig.add_gridspec(4, 1) ax1 = fig.add_subplot(gs[0:3, 0], projection='astro hours mollweide') ax2 = fig.add_subplot(gs[3, 0]) ax3 = ax2.twinx() # mirror them plt.axes(ax1) hp.mollview(map_struct["prob"],title='',unit=unit,cbar=cbar, cmap=cmap, hold=True) add_edges() ax = plt.gca() data = {} if params["tilesType"] == "galaxy": for telescope, color in zip(params["telescopes"],colors): idx = np.where(coverage_struct["telescope"] == telescope)[0] hp.projscatter(coverage_struct["data"][idx,0], coverage_struct["data"][idx,1], lonlat=True, s=10, color=color) else: for ii in range(len(coverage_struct["ipix"])): data = coverage_struct["data"][ii,:] filt = coverage_struct["filters"][ii] ipix = coverage_struct["ipix"][ii] patch = coverage_struct["patch"][ii] FOV = coverage_struct["FOV"][ii] idx = params["telescopes"].index(coverage_struct["telescope"][ii]) if patch == []: continue #hp.visufunc.projplot(corners[:,0], corners[:,1], 'k', lonlat = True) patch_cpy = copy.copy(patch) patch_cpy.axes = None patch_cpy.figure = None patch_cpy.set_transform(ax.transData) patch_cpy.set_facecolor(colors[idx]) hp.projaxes.HpxMollweideAxes.add_patch(ax,patch_cpy) #tiles.plot() idxs = np.argsort(coverage_struct["data"][:,2]) plt.axes(ax2) for telescope, color in zip(params["telescopes"],colors): ipixs = np.empty((0,2)) cum_prob = 0.0 cum_area = 0.0 tts, cum_probs, cum_areas = [], [], [] if params["tilesType"] == "galaxy": cum_galaxies = [] for jj, ii in enumerate(idxs): if np.mod(jj, 100) == 0: print('%s: %d/%d' % (telescope, jj, len(idxs))) data = coverage_struct["data"][ii,:] filt = coverage_struct["filters"][ii] ipix = coverage_struct["ipix"][ii] patch = coverage_struct["patch"][ii] FOV = coverage_struct["FOV"][ii] area = coverage_struct["area"][ii] if params["tilesType"] == "galaxy": galaxies = coverage_struct["galaxies"][ii] if not telescope == coverage_struct["telescope"][ii]: continue if params["tilesType"] == "galaxy": overlap = np.setdiff1d(galaxies, cum_galaxies) if len(overlap) > 0: for galaxy in galaxies: if galaxy in cum_galaxies: continue if catalog_struct is None: continue if params["galaxy_grade"] == "Sloc": cum_prob = cum_prob + catalog_struct["Sloc"][galaxy] elif params["galaxy_grade"] == "S": cum_prob = cum_prob + catalog_struct["S"][galaxy] elif params["galaxy_grade"] == "Smass": cum_prob = cum_prob + catalog_struct["Smass"][galaxy] cum_galaxies = np.append(cum_galaxies,galaxies) cum_galaxies = np.unique(cum_galaxies).astype(int) cum_area = len(cum_galaxies) else: ipixs = np.append(ipixs,ipix) ipixs = np.unique(ipixs).astype(int) cum_prob = np.sum(map_struct["prob"][ipixs]) cum_area = len(ipixs) * map_struct["pixarea_deg2"] cum_probs.append(cum_prob) cum_areas.append(cum_area) tts.append(data[2]-event_mjd) ax2.plot(tts, cum_probs, color=color, linestyle='-', label=telescope) ax3.plot(tts, cum_areas, color=color, linestyle='--') ax2.set_xlabel('Time since event [days]') if params["tilesType"] == "galaxy": ax2.set_ylabel('Integrated Metric') else: ax2.set_ylabel('Integrated Probability') if params["tilesType"] == "galaxy": ax3.set_ylabel('Number of galaxies') else: ax3.set_ylabel('Sky area [sq. deg.]') ipixs = np.empty((0,2)) cum_prob = 0.0 cum_area = 0.0 tts, cum_probs, cum_areas = [], [], [] if params["tilesType"] == "galaxy": cum_galaxies = [] for jj, ii in enumerate(idxs): data = coverage_struct["data"][ii,:] filt = coverage_struct["filters"][ii] ipix = coverage_struct["ipix"][ii] patch = coverage_struct["patch"][ii] FOV = coverage_struct["FOV"][ii] area = coverage_struct["area"][ii] if params["tilesType"] == "galaxy": galaxies = coverage_struct["galaxies"][ii] if params["tilesType"] == "galaxy": overlap = np.setdiff1d(galaxies, cum_galaxies) if len(overlap) > 0: for galaxy in galaxies: if galaxy in cum_galaxies: continue if catalog_struct is None: continue if params["galaxy_grade"] == "Sloc": cum_prob = cum_prob + catalog_struct["Sloc"][galaxy] elif params["galaxy_grade"] == "S": cum_prob = cum_prob + catalog_struct["S"][galaxy] elif params["galaxy_grade"] == "Smass": cum_prob = cum_prob + catalog_struct["Smass"][galaxy] cum_galaxies = np.append(cum_galaxies,galaxies) cum_galaxies = np.unique(cum_galaxies).astype(int) cum_area = len(cum_galaxies) else: ipixs = np.append(ipixs,ipix) ipixs = np.unique(ipixs).astype(int) cum_prob = np.sum(map_struct["prob"][ipixs]) cum_area = len(ipixs) * map_struct["pixarea_deg2"] tts.append(data[2]-event_mjd) cum_probs.append(cum_prob) cum_areas.append(cum_area) ax2.plot(tts, cum_probs, color='k', linestyle='-', label='All') ax3.plot(tts, cum_areas, color='k', linestyle='--') if len(params["telescopes"]) > 3: ax2.legend(loc=1,ncol=3,fontsize=10) ax2.set_ylim([0,1]) ax3.set_ylim([0,10000]) elif "IRIS" in params["telescopes"]: ax2.set_ylim([0,1.0]) ax3.set_ylim([0,10000]) ax2.legend(loc=1) elif "ZTF" in params["telescopes"]: ax2.set_ylim([0,1.0]) ax3.set_ylim([0,10000]) ax2.legend(loc=1) elif "PS1" in params["telescopes"]: ax2.set_ylim([0,1.0]) ax3.set_ylim([0,10000]) ax2.legend(loc=1) else: ax2.legend(loc=1) if plot_sun_moon: #plot sun and moon position at the beginning of the observation start_time = params['gpstime'] start_time = Time(start_time, format='gps', scale='utc') sun_position = get_sun(start_time) moon_position = get_moon(start_time) hp.visufunc.projscatter(sun_position.ra, sun_position.dec,lonlat=True,color='yellow') hp.visufunc.projscatter(moon_position.ra, moon_position.dec,lonlat=True,color='grey') #also plot (in smaller scale) sun and moon position for the 7 following days #This allow to show the path of both sun and moon for the coming days dt = 21600 #1/4 day for i in range(1,29): #29 is 4*7 new_time = params['gpstime'] + (dt*i) new_time = Time(new_time, format='gps', scale='utc') new_moon_position = get_moon(new_time) hp.visufunc.projscatter(new_moon_position.ra, new_moon_position.dec,lonlat=True,color='black',marker='.',s=1) if not i % 8: #only plot point for the sun every two days in order to avoid overlap new_sun_position = get_sun(new_time) hp.visufunc.projscatter(new_sun_position.ra, new_sun_position.dec,lonlat=True,color='black',marker='.',s=1) plt.show() plt.savefig(plotName,dpi=200) plt.close('all') filename = os.path.join(params["outputDir"],'tiles_coverage_int.dat') fid = open(filename, 'w') for ii in range(len(tts)): fid.write('%.10f %.10e %.10f\n' % (tts[ii], cum_probs[ii], cum_areas[ii])) fid.close() print('Total Cumulative Probability, Area: %.5f, %.5f' % (cum_probs[-1], cum_areas[-1])) plotName = os.path.join(params["outputDir"],'tiles_coverage_scaled.pdf') plt.figure() hp.mollview(map_struct["prob"],title='',unit=unit,cbar=cbar,cmap=cmap) add_edges() ax = plt.gca() for ii in range(len(coverage_struct["ipix"])): data = coverage_struct["data"][ii,:] filt = coverage_struct["filters"][ii] ipix = coverage_struct["ipix"][ii] patch = coverage_struct["patch"][ii] FOV = coverage_struct["FOV"][ii] if patch == []: continue #hp.visufunc.projplot(corners[:,0], corners[:,1], 'k', lonlat = True) patch_cpy = copy.copy(patch) patch_cpy.axes = None patch_cpy.figure = None patch_cpy.set_transform(ax.transData) current_alpha = patch_cpy.get_alpha() if current_alpha > 0.0: alpha = data[4]/max_time if alpha > 1: alpha = 1.0 patch_cpy.set_alpha(alpha) hp.projaxes.HpxMollweideAxes.add_patch(ax,patch_cpy) #tiles.plot() if plot_sun_moon: #plot sun and moon position at the beginning of the observation start_time = params['gpstime'] start_time = Time(start_time, format='gps', scale='utc') sun_position = get_sun(start_time) moon_position = get_moon(start_time) hp.visufunc.projscatter(sun_position.ra, sun_position.dec,lonlat=True,color='yellow') hp.visufunc.projscatter(moon_position.ra, moon_position.dec,lonlat=True,color='grey') #also plot (in smaller scale) sun and moon position for the 7 following days #This allow to show the path of both sun and moon for the coming days dt = 21600 #1/4 day for i in range(1,29): #29 is 4*7 new_time = params['gpstime'] + (dt*i) new_time = Time(new_time, format='gps', scale='utc') new_moon_position = get_moon(new_time) hp.visufunc.projscatter(new_moon_position.ra, new_moon_position.dec,lonlat=True,color='black',marker='.',s=1) if not i % 8: #only plot point for the sun every two days in order to avoid overlap new_sun_position = get_sun(new_time) hp.visufunc.projscatter(new_sun_position.ra, new_sun_position.dec,lonlat=True,color='black',marker='.',s=1) plt.show() plt.savefig(plotName,dpi=200) plt.close('all') if params["doMovie"]: idx = np.isfinite(coverage_struct["data"][:,2]) mjd_min = np.min(coverage_struct["data"][idx,2]) mjd_max = np.max(coverage_struct["data"][idx,2]) mjd_N = 100 mjds = np.linspace(mjd_min,mjd_max,num=mjd_N) moviedir = os.path.join(params["outputDir"],'movie') if not os.path.isdir(moviedir): os.mkdir(moviedir) #for jj in range(len(coverage_struct["ipix"])): # mjd = coverage_struct["data"][jj,3] for jj in range(len(mjds)): mjd = mjds[jj] plotName = os.path.join(moviedir,'coverage-%04d.png'%jj) title = "Coverage Map: %.2f"%mjd plt.figure() hp.mollview(map_struct["prob"],title=title,unit=unit,cbar=cbar, cmap=cmap) add_edges() ax = plt.gca() idx = np.where(coverage_struct["data"][:,2]<=mjd)[0] #for ii in range(jj): for ii in idx: data = coverage_struct["data"][ii,:] filt = coverage_struct["filters"][ii] ipix = coverage_struct["ipix"][ii] patch = coverage_struct["patch"][ii] FOV = coverage_struct["FOV"][ii] if patch == []: continue #hp.visufunc.projplot(corners[:,0], corners[:,1], 'k', lonlat = True) patch_cpy = copy.copy(patch) patch_cpy.axes = None patch_cpy.figure = None patch_cpy.set_transform(ax.transData) #alpha = data[4]/max_time #if alpha > 1: # alpha = 1.0 #patch_cpy.set_alpha(alpha) hp.projaxes.HpxMollweideAxes.add_patch(ax,patch_cpy) #tiles.plot() plt.show() plt.savefig(plotName,dpi=200) plt.close('all') moviefiles = os.path.join(moviedir,"coverage-%04d.png") filename = os.path.join(params["outputDir"],"coverage.mpg") ffmpeg_command = 'ffmpeg -an -y -r 20 -i %s -b:v %s %s'%(moviefiles,'5000k',filename) os.system(ffmpeg_command) filename = os.path.join(params["outputDir"],"coverage.gif") ffmpeg_command = 'ffmpeg -an -y -r 20 -i %s -b:v %s %s'%(moviefiles,'5000k',filename) os.system(ffmpeg_command) rm_command = "rm %s/*.png"%(moviedir) os.system(rm_command)
def plot_results(mode): if mode == 'dadi': res = { 10: [0.002598285675048828, 0.0750267505645752, 1.0705108642578125], 20: [0.003746509552001953, 0.14794182777404785, 3.178598165512085], 30: [0.004683256149291992, 0.2380847930908203, 7.416461944580078], 40: [0.006814479827880859, 0.3744471073150635, 15.026614904403687], 50: [0.01135110855102539, 0.5303077697753906, 27.26491904258728], 60: [0.01256251335144043, 0.7062654495239258, 44.674824714660645], 70: [0.0161590576171875, 0.9219067096710205, 69.03412652015686], 80: [0.02075052261352539, 1.1637859344482422, 99.16849541664124] } elif mode == 'moments': res = { 10: [ 0.0015158653259277344, 0.015314579010009766, 0.11319804191589355, 1.2347056865692139, 23.203108072280884 ], 20: [ 0.0013666152954101562, 0.029877901077270508, 0.3729233741760254, 8.827671527862549, 355.97147393226624 ], 30: [ 0.001438140869140625, 0.05322885513305664, 0.8257763385772705, 31.57155466079712, 1374.6368079185486 ], 40: [ 0.0017266273498535156, 0.08972859382629395, 1.9885749816894531, 82.23191094398499, 4356.353564023972 ], 50: [ 0.0017697811126708984, 0.12981605529785156, 2.639880657196045, 179.8065574169159 ], 60: [ 0.0026514530181884766, 0.24073171615600586, 4.396363019943237, 318.94581270217896 ], 70: [ 0.0019762516021728516, 0.25220417976379395, 6.0970799922943115, 533.2001190185547 ], 80: [ 0.002245187759399414, 0.3430655002593994, 8.255565881729126, 969.6083562374115 ] } elif mode == 'momi': res = { 10: [ 0.040425777435302734, 0.2841489315032959, 0.5000772476196289, 0.7996480464935303, 1.1076393127441406, 1.4341752529144287, 1.835172414779663, 2.177875280380249, 2.4498701095581055 ], 20: [ 0.07772159576416016, 0.449718713760376, 0.8464815616607666, 1.3791558742523193, 2.0268752574920654, 2.699354410171509, 3.6816837787628174, 4.350857734680176, 4.817714214324951 ], 30: [ 0.05660057067871094, 0.5898139476776123, 1.2340788841247559, 2.057643413543701, 3.2617156505584717, 5.307035207748413, 5.32308292388916, 6.768655061721802, 7.576956033706665 ], 40: [ 0.07962346076965332, 0.8049225807189941, 1.8476529121398926, 2.7939248085021973, 3.954272508621216, 5.470911264419556, 6.991794586181641, 8.649635553359985, 9.764487028121948 ], 50: [ 0.09171724319458008, 1.1149280071258545, 2.055758476257324, 3.2204484939575195, 4.768917798995972, 6.351742506027222, 8.505664587020874, 9.884680032730103, 12.169224500656128 ], 60: [ 0.09985589981079102, 1.248504400253296, 2.584294080734253, 4.832667350769043, 6.384091854095459, 8.91451621055603, 10.56020736694336, 13.327739953994751, 14.690232038497925 ], 70: [ 0.12362122535705566, 1.304567575454712, 2.782144546508789, 4.662824630737305, 6.881324529647827, 8.63783073425293, 11.383946418762207, 13.8502197265625, 18.288761377334595 ], 80: [ 0.1479353904724121, 1.61826491355896, 3.353036403656006, 5.353995323181152, 7.967868089675903, 10.720394134521484, 14.592302560806274, 18.05605435371399, 22.071446180343628 ] } plt.figure(figsize=(7, 6)) res_keys = sorted(res) col_list = iter(cm.rainbow(np.linspace(0, 1, 8))) for ns, col in zip(res_keys, col_list): times = res[ns] n_pop_pos = range(1, len(times) + 1) plt.plot(n_pop_pos, times, c=col, label=str(ns) + ' samples per population') if mode == 'dadi': n_pop_pos = range(1, 4) elif mode == 'moments': n_pop_pos = range(1, 6) elif mode == 'momi': n_pop_pos = range(1, 10) plt.xticks(n_pop_pos, n_pop_pos) plt.xlabel('Number of populations') if mode == 'momi': plt.ylabel('Time of VCF simulation (sec)') else: plt.ylabel('Time of AFS simulation (sec)') plt.yscale('log') # plt.title('Time complexity for %s simulations for different number of populations' % mode) plt.legend(loc=0) print('DONE') plt.savefig('1.png')
def run(mat, model_type, model_config): mat = filter_static_points(mat) start = mat[0].copy() end = mat[-1].copy() list_of_random_startend = [] for i in range(10): start = mat[0].copy() end = mat[-1].copy() end[2] += i*0.01 list_of_random_startend.append(( start, end, )) dmp_instance = util.get_dmp_model(mat, model_type) model_list = [] model_generator = model_config_generation.get_model_config_generator(model_type, model_config) for now_model_config in model_generator: print print '-'*20 print ' working on config:', now_model_config model = { 'dmp_instance': dmp_instance, 'gen_ay': now_model_config['gen_ay'], } score, debug_var = model_score.score(model, mat, list_of_random_startend) if score == None: print "scorer says to skip this model, will do" continue tmp_d = { "model": model, "now_model_config": now_model_config, "score": score, } if DEBUG_MODE: tmp_d['debug_var'] = debug_var model_list.append(tmp_d) print 'score:', score print '='*20 print model_config_generation.update_now_score(score) sorted_model_list = sorted(model_list, key=lambda x:x['score']) if len(sorted_model_list) == 0: print "ERORR: empty sorted_model_list." return None if DEBUG_MODE: for d in sorted_model_list: debug_var = d['debug_var'] score = d['score'] import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = fig.add_subplot(111, projection='3d') for tup in list_of_random_startend: start, end = tup ax.scatter(start[0], start[1], start[2], color='red') ax.scatter(end[0], end[1], end[2], color='green') ax.plot(mat[:, 0], mat[:, 1], mat[:, 2], color='black', label='orig') from matplotlib.pyplot import cm import numpy as np color=iter(cm.rainbow(np.linspace(0, 1, len(debug_var)))) for tup in debug_var: gen_mat = tup[0] dist = tup[1] ax.plot(gen_mat[:, 0], gen_mat[:, 1], gen_mat[:, 2], color='blue', label=dist) ax.set_title(str(score)+" "+str(d['now_model_config'])) ax.set_xlim3d(0, 2) ax.set_ylim3d(-2, 2) ax.set_zlim3d(-2, 2) fig.show() raw_input() return sorted_model_list
for c_value in nX: for time_gap in [pth1, pth2, pth3, pth4, pth5]: fig, axesa = plt.subplots(1, figsize=(16, 8)) if time_gap == pth1: jumps = 40 elif time_gap == pth2: jumps = 20 elif time_gap == pth3: jumps = 13 elif time_gap == pth4: jumps = 10 elif time_gap == pth5: jumps = 10 color = iter(cm.rainbow(np.linspace(0, 1, jumps))) labels = [] line2d = [] if time_gap != pth5: for run in diz_pths[time_gap][1]: j = 1 fin = time_gap + run + c_value + 'pts' + str(j) + 'plotdata.p' while os.path.exists(fin): print fin f = open(fin, "rb") A = pickle.load(f) f.close() telen = A[6] j += 1 fin = time_gap + run + c_value + 'pts' + str(
# 학습이 완료되었으므로, trainX를 한 개씩 입력하면서 clust를 결정한다. clust = [] for k in range(n): dx = inputXY[:, k] dx = dx.reshape([nInput, 1]) cluster = sess.run(winOut, feed_dict={x: dx}) clust.append(cluster) # 학습이 완료된 weight = centroid centXY = sess.run(Wo) sess.close() # 분류 결과를 표시한다 clust = np.array(clust) dataXY = inputXY.T color = cm.rainbow(np.linspace(0, 1, nOutput)) plt.figure(figsize=(8, 6)) for i, c in zip(range(nOutput), color): plt.scatter(dataXY[clust == i, 0], dataXY[clust == i, 1], s=20, c=c, marker='o', alpha=0.5, label='cluster ' + str(i)) plt.scatter(centXY[:, 0], centXY[:, 1], s=250, marker='*', c='black', label='centroids')
def generate_1d_model(): modelname = "flow_1d" model_ws = r"model_dataset" if model_ws in os.listdir(os.getcwd()): shutil.rmtree(os.path.join(os.getcwd(), model_ws)) os.mkdir(model_ws) exe = r"..\bin\win\mfnwt.exe" shutil.copy(src=exe, dst=os.path.join(model_ws, os.path.basename(exe))) mf = flopy.modflow.Modflow(modelname, model_ws=model_ws, exe_name=os.path.abspath(exe), version='mfnwt') # --- Dis file Lx = 2000.0 Ly = 1.0 ztop = 0.0 zbot = -50.0 nlay = 1 nrow = 1 ncol = 100 delr = Lx / ncol delc = Ly / nrow delv = (ztop - zbot) / nlay botm = np.linspace(ztop, zbot, nlay + 1) nper = 24 # two years perlen = nper * [30] nstp = nper * [30] steady = [True] + (nper - 1) * [False] dis = flopy.modflow.ModflowDis(mf, nlay, nrow, ncol, delr=delr, delc=delc, top=ztop, botm=botm[1:], nper=nper, perlen=perlen, nstp=nstp, steady=steady) df_dis = pd.DataFrame(columns=['parname', 'parval']) df_dis['parname'] = ['start_sp', 'end_sp'] df_dis['parval'] = [0, 23] df_dis.to_csv(os.path.join(model_ws, "input_dis.csv"), index=False) temporal_param = pd.DataFrame(columns=[]) temporal_param['stress_period'] = range(mf.dis.nper) temporal_param['perlen'] = mf.dis.perlen.array temporal_param['nstp'] = mf.dis.nstp.array # --- bas file ibound = np.ones((nlay, nrow, ncol), dtype=np.int32) strt = np.ones((nlay, nrow, ncol), dtype=np.float32) strt[:, :, :] = -10.0 bas = flopy.modflow.ModflowBas(mf, ibound=ibound, strt=strt) # --- upw laytyp = np.ones(nlay) laywet = np.zeros(nlay) hk = np.zeros_like(bas.strt.array) + 1.6 sy = 0.18 ss = 1e-06 flopy.modflow.mfupw.ModflowUpw(mf, laytyp=laytyp, layavg=0, chani=1.0, layvka=0, laywet=laywet, hdry=-1e+30, iphdry=0, hk=hk, hani=1.0, vka=hk, ss=ss, sy=sy, vkcb=0.0, noparcheck=False, ipakcb=55) # --- GHB ghb_stress_per = {} w = 2.0 * np.pi * 20 t = np.linspace(0, mf.dis.nper) sinPart = 2 * np.sin(w * t) for sp in range(mf.dis.nper): ghb_data = [] # [lay, row, col,head,cond] ghb_data.append([0, 0, 0, -10, 0.1]) ghb_data.append([0, 0, ncol - 1, -20, 0.1]) ghb_stress_per[sp] = ghb_data temporal_param.loc[temporal_param['stress_period'] == sp, 'GHB_UP'] = -10 temporal_param.loc[temporal_param['stress_period'] == sp, 'GHB_DN'] = -20 ghbs = flopy.modflow.mfghb.ModflowGhb(mf, ipakcb=55, stress_period_data=ghb_stress_per, dtype=None, no_print=False, options=None, extension='ghb') # --- well wel_data = dict() for sp in range(mf.dis.nper): flow = -3.5 if sp == 0: flow = 0 wel_data[sp] = [[0, 0, 50, flow]] wel = flopy.modflow.mfwel.ModflowWel(mf, stress_period_data=wel_data) temporal_param.loc[temporal_param['stress_period'] == sp, 'Qw'] = flow # rech_data rech_data = dict() for sp in range(mf.dis.nper): # if sp == 0: # continue rech_data[sp] = np.zeros_like(rech_data) + 0.0002 + 1e-3 * sinPart[sp] rch = flopy.modflow.ModflowRch(mf, nrchop=3, rech=rech_data) temporal_param.loc[temporal_param['stress_period'] == sp, 'Rch'] = 0.0002 + 1e-3 * sinPart[sp] spd = dict() for isp, sp in enumerate(mf.dis.nstp.array): spd[(isp, sp - 1)] = ["print head", "print budget", "save head", "save budget"] oc = flopy.modflow.ModflowOc(mf, stress_period_data=spd, compact=True) nwt = flopy.modflow.mfnwt.ModflowNwt.load( r".\misc_files\solver_options.nwt", mf) mf.write_input() success, buff = mf.run_model() if not success: raise Exception("MODFLOW did not terminate normally.") hds = flopy.utils.HeadFile(os.path.join(model_ws, modelname + ".hds")) totims = hds.get_times() color = cm.rainbow(np.linspace(0, 1, len(totims))) fig1 = plt.figure() for ic, totim in enumerate(totims): wl = hds.get_data(totim=totim) plt.plot(wl[0][0], c=color[ic]) plt.xlabel("Distance") plt.ylabel("Water level") fig2 = plt.figure() cbc = flopy.utils.CellBudgetFile(os.path.join(model_ws, modelname + ".cbc")) plt.plot(cbc.get_ts(idx=(0, 0, ncol - 1), text=' HEAD DEP BOUNDS')[:, 1]) plt.xlabel("Time") plt.ylabel("Downstream Flow at GHB") # generate initial head to be steady-state for k = 1.0 wl = hds.get_data(totim=30.0) np.savetxt(os.path.join(model_ws, "iheads.dat"), wl[0][0]) # let use log of k np.savetxt(os.path.join(model_ws, "hk.dat"), np.log10(mf.upw.hk.array[0][0])) #mf3d_to_arrays(wl, os.path.join(model_ws, "iheads.dat")) #mf3d_to_arrays(mf.upw.hk.array, os.path.join(model_ws, "hk.dat")) # parnme = []; # parval1 = []; # ii, jj, kk = [], [], [] # # for k in range(nlay): # for i in range(nrow): # for j in range(ncol): # nm = "h_{}_{}_{}".format(k, i, j) # parnme.append(nm) # parval1.append(wl[k, i, j]) # ii.append(i) # jj.append(j) # kk.append(k) # # df = param_utils.add_param(df=df, parnme=parnme, # parval1=parval1, # gpname=['ihead'], i=ii, # j=jj, k=kk) # parnme = []; # parval1 = []; # ii, jj, kk = [], [], [] # # for k in range(nlay): # for i in range(nrow): # for j in range(ncol): # nm = "k_{}_{}_{}".format(k, i, j) # parnme.append(nm) # parval1.append(mf.upw.hk.array[k, i, j]) # ii.append(i) # jj.append(j) # kk.append(k) # # df = param_utils.add_param(df=df, parnme=parnme, # parval1=parval1, # gpname=['k'], i=ii, # j=jj, k=kk) # df.to_csv(os.path.join(model_ws, "input_param.csv"), index=False) temporal_param.to_csv(os.path.join(model_ws, "temporal_param.csv"), index=False) return [fig1, fig2]
def plot_Efield_path(vars, time_unit=1.0e6): ''' Plot electric field components and total magnitude at the particle position during a simulation ''' if time_unit == 1.0e6: time_label = 'time $[\mu s]$' else: time_label = 'time $[10^{%f} s]$' % (np.log10(1.0 / time_unit)) Emag = np.sqrt(vars['Ex']**2 + vars['Ey']**2) rot_angle = np.arccos(vars['xgc'] / vars['rgc']) # in radians dt_s = np.diff(vars['time'])[0] / time_unit rot_freq = np.abs(np.gradient(rot_angle, dt_s)) / (2 * np.pi) # in Hz # Compute E_{theta} and E_r E_r = vars['Ex'] * np.cos(rot_angle) + vars['Ey'] * np.sin(rot_angle) E_theta = -vars['Ex'] * np.sin(rot_angle) + vars['Ey'] * np.cos(rot_angle) minE = np.min([np.min(E_r), np.min(E_theta)]) maxE = np.max([np.max(E_r), np.max(E_theta)]) vExB_r = E_theta * vars['Bz'] vExB_tor = -E_r * vars['Bz'] minvE = np.min([np.min(vExB_r), np.min(vExB_tor)]) maxvE = np.max([np.max(vExB_r), np.max(vExB_tor)]) #vpar=2.0*vars['Kpara']*qe/me #vperp=vpar=2.0*vars['Kperp']*qe/me colors = cm.rainbow(np.linspace(0, 1, 5)) ##### Check role of E-field phases figgg = plt.figure(figsize=(10, 10)) ax0001 = plt.subplot(511) ax0001.plot(vars['time'], vars['Psi_g'] * 1.0e4, c=colors[0]) ax0001.set_ylabel(r'$\Psi_{gc}\times 10^4$ [T$m^2$]') ax0001.grid() ax0006 = plt.subplot(512, sharex=ax0001) ax0006.plot(vars['time'], E_r, c=colors[1]) ax0006.set_ylabel(r'$E_r$ [Vm]') ax0006.set_ylim([minE, maxE]) ax0006.grid() ax0007 = plt.subplot(513, sharex=ax0001) ax0007.plot(vars['time'], E_theta, c=colors[2]) ax0007.set_ylabel(r'$E_{\theta}$ [Vm]') ax0007.set_ylim([minE, maxE]) ax0007.grid() ax0008 = plt.subplot(514, sharex=ax0001) ax0008.plot(vars['time'], vExB_r, c=colors[3]) ax0008.set_ylabel(r'$v_{E\times B, r}$ [m/s]') ax0008.set_ylim([minvE, maxvE]) ax0008.grid() ax0009 = plt.subplot(515, sharex=ax0001) ax0009.plot(vars['time'], vExB_tor, c=colors[4]) ax0009.set_xlabel(r'%s' % time_label) ax0009.set_ylabel(r'$v_{E\times B,\theta}$ [m/s]') ax0009.set_ylim([minvE, maxvE]) ax0009.grid()
def main(): print "hello MAN" #first peak [2 2 0] data = np.loadtxt("../data/DE35214_UMG_treated_U03_firstpeak.xy") phi_angle = data[:,0] data_firstpeak_t = data[:,1] list_first_peaks_found_x = find_phi(phi_angle,data_firstpeak_t) list_peak_diff_first = find_difference_in_peaks(list_first_peaks_found_x) #second peak data = np.loadtxt("../data/DE35214_UMG_treated_U03_secondpeak.xy") phi_angle = data[:,0] data_secondpeak_t = data[:,1] list_second_peaks_found_x = find_phi(phi_angle,data_secondpeak_t) list_peak_diff_second = find_difference_in_peaks(list_second_peaks_found_x) #third peak data = np.loadtxt("../data/DE35214_UMG_treated_U03_thirdpeak.xy") phi_angle = data[:,0] data_thirdpeak_t = data[:,1] list_third_peaks_found_x = find_phi(phi_angle,data_thirdpeak_t) list_peak_diff_third = find_difference_in_peaks(list_third_peaks_found_x) #fourth peak data = np.loadtxt("../data/DE35214_UMG_treated_U04_02_fourthpeak.xy") phi_angle = data[:,0] data_fourthpeak_t = data[:,1] list_fourth_peaks_found_x = find_phi(phi_angle,data_fourthpeak_t) list_peak_diff_fourth = find_difference_in_peaks(list_fourth_peaks_found_x) #plotting phi-rotation of treated fiber color=iter(cm.rainbow(np.linspace(0,1,6))) fig2 = plt.figure() c1=next(color) plt.plot(phi_angle, data_firstpeak_t, color=c1, label=r'$\langle 220 \rangle$ planes') c=next(color) plt.plot(phi_angle, data_secondpeak_t, color=c, label=r'$\langle 400 \rangle$ planes') c=next(color) plt.plot(phi_angle, data_thirdpeak_t, color=c, label=r'$\langle 440 \rangle$ planes') c=next(color) #plt.plot(phi_angle, data_fourthpeak_t, color=c, label=r'$\langle 440 \rangle$ planes') #Plot peaks found for i in range(len(list_first_peaks_found_x)): plt.axvline(x=list_first_peaks_found_x[i],ymin=0.7, ymax=1, linewidth = 2, color = 'r') for i in range(len(list_second_peaks_found_x)): plt.axvline(x=list_second_peaks_found_x[i],ymin=0.7, ymax=1, linewidth = 2, color = 'b') for i in range(len(list_third_peaks_found_x)): plt.axvline(x=list_third_peaks_found_x[i],ymin=0.7, ymax=1, linewidth = 2, color = 'g') #for i in range(len(list_fourth_peaks_found_x)): #plt.axvline(x=list_fourth_peaks_found_x[i],ymin=0.7, ymax=1, linewidth = 2, color = 'k') plt.xlabel('$\phi$ rotation angle', fontsize=12) plt.ylabel('intensity', fontsize=12) plt.xlim(0,360) #plt.ylim(0,4500) plt.xticks(fontsize = 8) plt.yticks(fontsize = 8) plt.grid() plt.legend(loc='upper right', prop={'size':10}) fig2.savefig("./U3_phi.pdf") plt.show()
def drawJets(jets, name, label=None, eta=None, phi=None, pt=None, genjet=None, genpart=None, genjet_matched=None, genpart_matched=None, nJets=-1): n = 1 p = 1 print name fig = plt.figure(figsize=(12, 8)) ax = None colors = cm.rainbow(np.linspace(0, 1, max(2, len(jets)))) cmap = LinearSegmentedColormap.from_list('cmap', colors, len(colors)) if n > 3: ax = fig.add_subplot(2, int((n + 1) / 2), p, sharey=ax) else: ax = fig.add_subplot(1, n, p, sharey=ax) area = np.zeros((eta_edges.shape[0] - 1, phi_edges.shape[0] - 1), dtype=np.float64) if nJets > -1: jets = jets[:nJets] for ijet, jet in enumerate(jets): constit = jet.constituents_array() jetarea, _, _ = np.histogram2d(constit['eta'], constit['phi'], bins=(eta_edges, phi_edges)) area += (jetarea > 0) * (ijet + 1) ax.imshow(np.ma.masked_where(area == 0, area).T, cmap=cmap, extent=extent, aspect=(eta_max - eta_min) / (2 * np.pi), interpolation='none', origin='lower') if not eta is None: ax.scatter(eta, phi, s=30 * np.log10(pt) / np.log10(pt.max())) if not genjet is None: ax.scatter(genjet.gen_eta[genjet_matched].values, genjet.gen_phi[genjet_matched].values, s=50, marker="D", color='black') ax.scatter(genjet.gen_eta[np.logical_not(genjet_matched)], genjet.gen_phi[np.logical_not(genjet_matched)], s=50, marker="s", color='black') genjetList = "Gen Jets\n" for i in range(len(genjet.gen_eta)): isMatched = "" if genjet_matched[i]: isMatched = ' X' genjetList += "pt=%.2f, $\eta$=%.3f, $\phi$=%.3f%s\n" % ( genjet.gen_pt.values[i], genjet.gen_eta.values[i], genjet.gen_phi.values[i], isMatched) if len(genjet.gen_eta) == 0: genjetList = "No Gen Jets" ax.text(0.5, 0.85, genjetList, verticalalignment='top', horizontalalignment='center', transform=ax.transAxes, fontsize=12) if not genpart is None: ax.scatter(genpart.gen_eta[genpart_matched], genpart.gen_phi[genpart_matched], s=50, marker="x", color='black') ax.scatter(genpart.gen_eta[np.logical_not(genpart_matched)], genpart.gen_phi[np.logical_not(genpart_matched)], s=50, marker="o", color='black') genpartList = "Gen Partons\n" for i in range(len(genpart.gen_eta)): isMatched = "" if genpart_matched[i]: isMatched = ' X' genpartList += "pid=%i, pt=%.2f, $\eta$=%.3f, $\phi$=%.3f%s\n" % ( genpart.gen_pdgid.values[i], genpart.gen_pt.values[i], genpart.gen_eta.values[i], genpart.gen_phi.values[i], isMatched) if len(genpart.gen_eta) == 0: genpartList = "No Gen Partons" ax.text(0.5, 0.55, genpartList, verticalalignment='top', horizontalalignment='center', transform=ax.transAxes, fontsize=12) ax.set_xlim(extent[:2]) ax.set_ylim(extent[2:]) ax.set_ylabel(r'$\phi$') ax.set_xlabel(r'$\eta$') if not label == None: ax.text(0.5, 0.05, label, verticalalignment='bottom', horizontalalignment='center', transform=ax.transAxes, fontsize=12) for ijet, jet in enumerate(jets): ax.text(jet.eta / 6. + 0.5, jet.phi / (2 * np.pi) + 0.5, "%.2f" % jet.pt, verticalalignment='center', horizontalalignment='center', transform=ax.transAxes, fontsize=10) ax.legend([ "matched genJet", "unmatched genJet", "matched genPart", "unmatched genPart" ], loc=9) fig.subplots_adjust(hspace=0) plt.setp([a.get_yticklabels() for a in fig.axes[1:]], visible=False) fig.tight_layout() fig.savefig(name)
def get_n_different_colors(n): return cm.rainbow(np.linspace(0, 1, n))
# utils.print_policy_from_occupancies(cvar_opt_usa, mdp_env) # utils.print_stochastic_policy_action_probs(cvar_opt_usa, mdp_env) # cvar_reward, q = mdp.solve_minCVaR_reward(mdp_env, u_expert, posterior, posterior_probs, alpha) # print("cvar reward", cvar_reward) #generate efficient frontier lambda_range = [0.0, 0.3, 0.75, 0.95, 1.0] import matplotlib.pyplot as plt from matplotlib.pyplot import cm bar_width = 0.15 opacity = 0.9 color = iter(cm.rainbow(np.linspace(0, 1, 6))) cnt = 0 index = np.arange(num_states) for i, lamda in enumerate(lambda_range): print("lambda = ", lamda) cvar_opt_usa, cvar, exp_ret = mdp.solve_max_cvar_policy( mdp_env, u_expert, posterior, posterior_probs, alpha, False, lamda) print('action probs') utils.print_stochastic_policy_action_probs(cvar_opt_usa, mdp_env) stoch_pi = utils.get_optimal_policy_from_usa(cvar_opt_usa, mdp_env) print(stoch_pi[:, 1]) c = next(color)
decoder_src_atten = attentions["decoder"]["mh2"] tgt_label = tgt[1:11][::-1] src_label = ["" for _ in range(2)] + src[::-1] fig, ax = plt.subplots(nrows=2, ncols=2, sharex=True, figsize=(7, 14)) for i in range(2): for j in range(2): ax[i, j].set_yticks(np.arange(len(src_label))) ax[i, j].set_yticklabels(src_label, fontsize=9) # src ax[i, j].set_ylim(0, len(src_label)-1) ax_ = ax[i, j].twinx() ax_.set_yticks(np.linspace(ax_.get_yticks()[0], ax_.get_yticks()[-1], len(ax[i, j].get_yticks()))) ax_.set_yticklabels(tgt_label, fontsize=9) # tgt img = decoder_src_atten[-1][case, i + j][:10, :8] color = cm.rainbow(np.linspace(0, 1, img.shape[0])) left_top, right_top = img.shape[1], img.shape[0] for ri, c in zip(range(right_top), color): # tgt for li in range(left_top): # src alpha = (img[ri, li] / img[ri].max()) ** 7 ax[i, j].plot([0, 1], [left_top - li + 1, right_top - 1 - ri], alpha=alpha, c=c) ax[i, j].set_xticks(()) ax[i, j].set_xlabel("head %i" % (j + 1 + i * 2)) ax[i, j].set_xlim(0, 1) plt.subplots_adjust(top=0.9) plt.tight_layout() plt.savefig("./visual/results/transformer%d_encoder_decoder_attention_line.png" % case, dpi=100) def self_attention_matrix(bert_or_gpt="bert", case=0): with open("./visual/tmp/"+bert_or_gpt+"_attention_matrix.pkl", "rb") as f:
print('') # parametros para los graficos samples_x = 1000 eje_x = np.linspace(-L1, L2, num=samples_x) # \_ armo el eje x para cada tramo x1 = eje_x[eje_x < 0] # | x2 = eje_x[eje_x >= 0] # / cuantos_modos = 8 plot_derivada = False # graficos cuantos_modos = min(cuantos_modos, max_candidatos - 1, k2_finales.size - 1) my_colormap = iter(cm.rainbow(np.linspace(0, 1, cuantos_modos))) fig_modos, ax_modos = plt.subplots() if (plot_derivada): fig_deriv, ax_deriv = plt.subplots(nrows=cuantos_modos) lista_modos = np.zeros([cuantos_modos, samples_x]) for modo in np.arange(start=1, stop=cuantos_modos + 1, step=1): # k's k2 = k2_finales[modo] k1 = c2 * k2 / c1 # amplitudes de senos y cosenos A1 = 1
element_symbols = np.asarray([el.symbol for el in periodictable.elements]) # input Te must be in keV: temp_grid = np.geomspace(1e-1, 10, 1000) # keV dens_grid = np.ones_like(temp_grid) *1e13 # cm^-3 for ion in ['O','Mg','Ar','Fe']: #element_symbols: Z = np.where(element_symbols==ion)[0][0] try: plot_wz_case(ion, Z, dens_grid, temp_grid) except: pass # just for single ion cols = cm.rainbow(np.linspace(0,1,3)) # w line: fig_stuff = plot_line_case('Ca', 20, np.ones_like(temp_grid) *1e12, temp_grid, cols[0], spec_line='w') fig_stuff = plot_line_case('Ca', 20, np.ones_like(temp_grid) *1e13, temp_grid, cols[1], fig_stuff=fig_stuff, spec_line='w') fig_stuff = plot_line_case('Ca', 20, np.ones_like(temp_grid) *1e14, temp_grid, cols[2], fig_stuff=fig_stuff, spec_line='w') # z line: fig_stuff = plot_line_case('Ca', 20, np.ones_like(temp_grid) *1e12, temp_grid, cols[0], spec_line='z') fig_stuff = plot_line_case('Ca', 20, np.ones_like(temp_grid) *1e13, temp_grid, cols[1], fig_stuff=fig_stuff, spec_line='z') fig_stuff = plot_line_case('Ca', 20, np.ones_like(temp_grid) *1e14, temp_grid, cols[2], fig_stuff=fig_stuff, spec_line='z') ### #axs = Helike_emiss_metrics(imp='Ca')
for jj in range(9): fid.write("%.3f "%mag_ds[jj][ii]) fid.write("\n") fid.close() mag_ds = np.loadtxt(filename) mag1 = mag_ds[:,2] indexes = np.where(~np.isnan(mag1))[0] index1 = indexes[0] index2 = indexes[-1] mag_ds = mag_ds[index1:index2,:] t = mag_ds[:,0] filts = ["u","g","r","i","z","y","J","H","K"] colors=cm.rainbow(np.linspace(0,1,len(filts))) magidxs = [1,2,3,4,5,6,7,8,9] if opts.doPlots: plotName = "%s/%s.pdf"%(plotDir,basename) plt.figure(figsize=(10,12)) for filt, color, magidx in zip(filts,colors,magidxs): plt.plot(t,mag_ds[:,magidx],alpha=1.0,c=color,label=filt) plt.xlabel('Time [days]') plt.ylabel('Absolute AB Magnitude') plt.ylim([-20,10]) plt.legend(loc="lower center",ncol=5) title_name = [] if not np.isnan(opts.theta): title_name.append('Inclination: %.1f' % opts.theta)
def plot_bhp_e_slices(bhp_e_slices, e_bin_edges, slice_e_ranges=None, E_min=None, E_max=None, title=None, new_fig=True, show_flag=True, log_flag=False, clear=False, save_flag=True, save_filename='bhp_e_slices'): ''' Plot bhp_slices on same axes, normalized by integral Parameters ---------- bhp_e_slices : ndarray Array of bhp_e slices. Dimensions: # slices x len(e_bin_centers) e_bin_edges : ndarray One-dimensional array of bin edges slice_e_ranges : ndarray Array of slice ranges. Dimensions: # slices x 2 (min, max) new_fig : bool, optional Option to start new figure show_flag : bool, optional Option to display log_flag : bool, optional Option for log y-axis clear : bool, optional Option to clear axes Returns ------- legend_text : str String of legend text ''' if new_fig: plt.figure(figsize=(6, 4)) legend_text = [] color = iter(cm.rainbow(np.linspace( 0, 1, bhp_e_slices.shape[0]))) # Set up colors for plotting for i in range(bhp_e_slices.shape[0]): # Loop through slices c = next(color) plot_bhp_e_slice(bhp_e_slices[i, :], e_bin_edges, slice_e_ranges[i, :], normalized='int', c=c, clear=False, new_fig=False, title=False) if slice_e_ranges[i, :] is not None: legend_text.append('{:04.2f} to {:04.2f}'.format( np.min(slice_e_ranges[i, :]), np.max(slice_e_ranges[i, :]))) if E_min is not None: plt.axvline(E_min, c='r') if E_max is not None: plt.axvline(E_max, c='r') plt.legend(legend_text) if title is not None: plt.title(title) # Hack legend ax = plt.gca() leg = ax.get_legend() color = iter(cm.rainbow(np.linspace( 0, 1, bhp_e_slices.shape[0]))) # Reset colors for i in range(bhp_e_slices.shape[0]): # Make legend c = next(color) leg.legendHandles[i].set_color(c) if save_flag: save_fig_to_folder(save_filename, 'fig') if show_flag: plt.show() if clear: plt.clf() return legend_text
prop={'size': 36}, numpoints=1, shadow=True, fancybox=True) elif not cnt == len(filts): plt.setp(ax2.get_xticklabels(), visible=False) plt.xticks(fontsize=32) plt.yticks(fontsize=32) ax1.set_zorder(1) plt.xlabel('Time [days]', fontsize=48) plt.savefig(plotName, bbox_inches='tight') plt.close() keys = sorted(data_out.keys()) colors = cm.rainbow(np.linspace(0, 1, len(keys))) plotName = "%s/spec_panels_fit.pdf" % (plotDir) plotNamePNG = "%s/spec_panels_fit.png" % (plotDir) fig = plt.figure(figsize=(22, 28)) cnt = 0 for key, color in zip(keys, colors): cnt = cnt + 1 vals = "%d%d%d" % (len(keys), 1, cnt) if cnt == 1: #ax1 = plt.subplot(eval(vals)) ax1 = plt.subplot(len(keys), 1, cnt) else: #ax2 = plt.subplot(eval(vals),sharex=ax1,sharey=ax1) ax2 = plt.subplot(len(keys), 1, cnt, sharex=ax1, sharey=ax1)
def plot(self, mode: str = 'frequency', depth_bin_size: float = 1.0, filter_incomplete_swaths: bool = True): """ Plot all outermost points binned in the depth dimension according to the provided size. Each plot is organized by the given mode, if mode is frequency will plot once per frequency, such that the colors let you know the extinction at each frequency. Parameters ---------- mode allowable plot mode, must be one of "frequency", "mode", "modetwo" depth_bin_size bin size in meters for the depth, size of 1 will produce one point for each meter of depth filter_incomplete_swaths If True, will only plot outermost points if the outermost port alongtrack value is negative, outermost starboard alongtrack value is positive """ if self.alongtrack is None or self.depth is None: print( 'Data was not successfully loaded, ExtinctionTest must be recreated' ) return fig = plt.figure() totalmindepth = 9999 totalmaxdepth = 0 totalminacross = 0 totalmaxacross = 0 groups, comparison, lbl = self._build_groups(mode) colors = iter(cm.rainbow(np.linspace(0, 1, len(groups)))) for grp in groups: print('Building plot for {}={}'.format(mode, grp)) idx = comparison == grp atrack_by_idx = self.alongtrack[idx] dpth_by_idx = self.depth[idx] mindepth = np.int(np.min(dpth_by_idx)) maxdepth = np.ceil(np.max(dpth_by_idx)) minacross = np.int(np.min(atrack_by_idx)) maxacross = np.ceil(np.max(atrack_by_idx)) totalmindepth = min(mindepth, totalmindepth) totalmaxdepth = max(maxdepth, totalmaxdepth) totalminacross = min(minacross, totalminacross) totalmaxacross = max(maxacross, totalmaxacross) # maintain at least 5 bins just to make a halfway decent plot if they pick a bad bin size bins = np.linspace( mindepth, maxdepth, max(int((maxdepth - mindepth) / depth_bin_size), 5)) dpth_indices = np.digitize(dpth_by_idx, bins) - 1 min_across = np.array([ atrack_by_idx[dpth_indices == i].min() for i in range(len(bins) - 1) if i in dpth_indices ]) max_across = np.array([ atrack_by_idx[dpth_indices == i].max() for i in range(len(bins) - 1) if i in dpth_indices ]) dpth_vals = np.array( [bins[i] for i in range(len(bins) - 1) if i in dpth_indices]) # filter by those areas where the freq is not found on port and starboard sides if filter_incomplete_swaths: swath_filter = np.logical_and(min_across < 0, max_across > 0) min_across = min_across[swath_filter] max_across = max_across[swath_filter] dpth_vals = dpth_vals[swath_filter] c = next(colors) lbl, grp = self._translate_label(mode, grp, lbl) plt.scatter(min_across, dpth_vals, c=np.array([c]), label=lbl.format(grp)) plt.scatter(max_across, dpth_vals, c=np.array([c])) self._plot_depth_guidelines(totalmindepth, totalmaxdepth) plt.xlim(-totalmaxacross * 1.3, totalmaxacross * 1.3) plt.gca().invert_yaxis() plt.title('{} (SN{}): {} by {}'.format(self.sonartype, self.serialnum, self.name, mode)) plt.xlabel('AcrossTrack Distance (meters)') plt.ylabel('Depth (meters, +down)') plt.legend() plt.show()
def visualize(self, indices=[], center_num=0, ref_labels=[], use_colors=True): # If indices are not given if len(indices) == 0: indices = np.arange(len(self.embeddings_)) # If center number is not given if center_num == 0: center_num = self.opt_speaker_num_ # If reference labels are used if len(ref_labels) != 0: speaker_labels = ref_labels # Allow visualization of different center number configurations else: # Get speaker labels spkmeans = SphericalKMeans(n_clusters=len( self.centers_[center_num]), init=self.centers_[center_num], max_iter=1, n_init=1, n_jobs=1).fit(self.embeddings_[indices]) speaker_labels = spkmeans.labels_ + 1 if len(self.speaker_labels_) == 0: raise RuntimeError("Clustering not performed.") # Compute TSNE only once if len(self.emb_2d_) == 0: print("Computing TSNE transform...") tsne = TSNE(n_jobs=4) self.emb_2d_ = tsne.fit_transform(self.embeddings_) # Visualize emb_2d = self.emb_2d_[indices] speaker_labels = speaker_labels.astype(np.int) speakers = np.unique(speaker_labels) colors = cm.rainbow(np.linspace(0, 1, len(speakers))) plt.figure(figsize=(7, 7)) for speaker in speakers: speak_ind = np.where(speaker_labels == speaker)[0] x, y = np.transpose(emb_2d[speak_ind]) if use_colors == True: plt.scatter(x, y, c="k", edgecolors=colors[speaker - 1], s=2, label=speaker) else: plt.scatter(x, y, c="k", edgecolors="k", s=2, label=speaker) plt.legend(title="Speakers", prop={'size': 10}) if len(ref_labels) == 0: plt.title("Predicted speaker clusters") else: plt.title("Reference speaker clusters") plt.show()
if len(score_list) == 0: continue y_multi.append(score_list) labels.append("%s->%s->%s" % (data_type, model_type, model_id)) model_amount = len(y_multi) state_amount = len(y_multi[0]) width = 0.7 / model_amount x = range(1, state_amount + 1) import matplotlib.pyplot as plt from matplotlib.pyplot import cm import numpy as np color = iter(cm.rainbow(np.linspace(0, 1, model_amount))) fig = plt.figure() ax = fig.add_subplot(111) for i in range(len(y_multi)): try: c = next(color) ax.bar([j + i * width for j in x], y_multi[i], width=width, label=labels[i], color=c) except AssertionError: print labels[i], y_multi[i], ' is problematic.' ax.legend(loc=3)
def dos_plot(ctrl="temp", lst=None, outfile=None, efermi=1, emin_lim=-6, emax_lim=8, centre_fermi=1, units="eV", yfontsize=None, xfontsize=None, dos_cut=None): s = loadfile("dos." + ctrl) top = s.split("\n", 1)[0].split(" ") top = ' '.join(top).split() data = s.split("\n", 1)[1] emin = float(top[0]) emax = float(top[1]) num_e = int(top[2]) num_orb = int(top[3]) nsp = int(top[4]) ef = float(top[5]) units = "eV" factor = {'Ry': 1, 'eV': 13.605698066}[units] if efermi: sub = ef else: sub = 0 x = np.linspace((emin - sub) * factor, (emax - sub) * factor, num_e) t = np.fromstring(data, sep='\n', dtype=float) dos = t.reshape(num_orb * nsp, num_e) def get_list(lst): lst = lst.split(";") list_data = [] def isint(s): try: int(s) return True except ValueError: return False for i in lst: if "," in i: list_data.append([int(x) for x in i.split(",")]) if isint(i): list_data.append([int(i)]) if ":" in i: s = i.split(":") if len(s) < 3: s.append(1) list_data.append(np.arange(int(s[0]), int(s[1]), int(s[2]))) return list_data def get_list(lst): lst = lst.split(";") list_data = [] def isint(s): try: int(s) return True except ValueError: return False def getcol(t="1:6"): s = t.split(":") if len(s) < 3: s.append(1) return (np.arange(int(s[0]), int(s[1]) + 1, int(s[2]))) for i in lst: if "," in i: temp = [] for small_lst in i.split(","): if ":" in small_lst: temp.append([int(x) for x in getcol(small_lst)]) else: temp.append(int(small_lst)) list_data.append(list(np.hstack(temp))) if isint(i): list_data.append([int(i)]) if ":" in i and "," not in i: s = i.split(":") if len(s) < 3: s.append(1) list_data.append( list(np.arange(int(s[0]), int(s[1]) + 1, int(s[2])))) return list_data if lst: lst_split = lst.split(("|")) plot_orb = get_list(lst_split[0]) label_orb = lst_split[0].split(";") if len(lst_split) > 1: k = 0 for name in lst_split[1].split(";"): if k < len(plot_orb): label_orb[k] = name k = k + 1 else: plot_orb = range(num_orb) label_orb = np.array(np.arange(num_orb), dtype=str) tot_up = np.zeros(num_e) tot_down = np.zeros(num_e) fig = plt.figure(figsize=(3, 7 + 1.187)) ax = fig.add_subplot(121) ax1 = fig.add_subplot(122) color = iter(cm.rainbow(np.linspace(0, 1, len(plot_orb)))) k = 0 for i in plot_orb: c = next(color) y = np.zeros(num_e) for j in i: y = np.add(y, dos[j - 1]) ax.plot(y, x, c=c, linewidth=1, label=label_orb[k]) if nsp > 1: for j in i: y = np.add(y, dos[j]) y = -1 * y ax.plot(y, x, c=c, linewidth=1) k = k + 1 if dos_cut != None: if nsp == 1: ax.set_xlim([-.05 * float(dos_cut), float(dos_cut)]) else: ax.set_xlim([-float(dos_cut), float(dos_cut)]) fig.legend(loc=7) tot_up = dos[0::2].sum(0) tot_down = dos[1::2].sum(0) if nsp > 1: ax1.plot(tot_up, x, color="red", linewidth=1) ax1.plot(-1 * tot_down, x, color="red", linewidth=1) ax.axvline(0, linestyle="--", color='black') ax1.axvline(0, linestyle="--", color='black') else: ax1.plot(np.add(tot_up, tot_down), x) ax.set_ylim(emin_lim, emax_lim) ax1.set_ylim(emin_lim, emax_lim) if xfontsize != None: [tl.set_fontsize(xfontsize) for tl in ax.xaxis.get_ticklabels()] [tl.set_fontsize(xfontsize) for tl in ax1.xaxis.get_ticklabels()] if yfontsize != None: [tl.set_fontsize(yfontsize) for tl in ax.yaxis.get_ticklabels()] [tl.set_fontsize(yfontsize) for tl in ax1.yaxis.get_ticklabels()] ax.axhline(0, linestyle=":", color='black') ax1.axhline(0, linestyle=":", color='black') ax.get_shared_y_axes().join(ax, ax1) ax.set_yticklabels([]) ax1.yaxis.tick_right() plt.subplots_adjust(wspace=.0, right=0.65) if (outfile != '' and outfile != None): plt.savefig(outfile, dpi=300, bbox_inches='tight') else: plt.show()
def plot_summary_1(vars_all, dt, downsampling, time_unit=1.0e6): ''' Particle simulation overview plots''' num_particles = len(vars_all) colors = cm.rainbow(np.linspace(0, 1, num_particles)) if time_unit == 1.0e6: time_label = 'time $[\mu s]$' else: time_label = 'time $[10^{%f} s]$' % (np.log10(1.0 / time_unit)) figg = plt.figure(figsize=(18, 10)) for nop in range(1, num_particles + 1): vars = vars_all['%s' % (str(nop))] # eliminate last 2 points to avoid visualization issues for 'dead' particles for i in range(len(vars)): vars[vars.keys()[i]] = vars[vars.keys()[i]][:-2] Emag = np.sqrt(vars['Ex']**2 + vars['Ey']**2) rot_angle = np.arccos(vars['xgc'] / vars['rgc']) # in radians dt_s = np.diff(vars['time'])[0] / time_unit rot_freq = np.abs(np.gradient(rot_angle, dt_s)) / (2 * np.pi) # in Hz # Compute E_{theta} and E_r E_r = vars['Ex'] * np.cos(rot_angle) + vars['Ey'] * np.sin(rot_angle) E_theta = -vars['Ex'] * np.sin(rot_angle) + vars['Ey'] * np.cos( rot_angle) vExB_r = E_theta * vars['Bz'] vExB_tor = -E_r * vars['Bz'] # Obtain frequency of complete azimuthal turns from nrot hist, bin_edges = np.histogram(vars['nrot'], int(max(vars['nrot'])) + 1) # find index of when the last complete turn begun endturn_idx = np.argmin(np.abs(vars['nrot'] - bin_edges[-1])) nrot = vars['nrot'][:endturn_idx] rot_time = vars['time'][:endturn_idx] # exclude last (incomplete) rotation hist_s = hist[1:-1] bin_edges_s = bin_edges[1:-1] time_per_rotation = hist_s * dt * downsampling f_tor_rot = 1.0 / time_per_rotation # time at the start of each rotation: cum_rot_time = np.cumsum(time_per_rotation) * time_unit # Summary plots ax001 = plt.subplot(331) ax001.plot(vars['time'], vars['Kpara'], c=colors[nop - 1]) ax001.set_ylabel(r'$K_{||} [eV]$') ax001.grid() ax002 = plt.subplot(332, sharex=ax001) ax002.plot(vars['time'], vars['Kperp'], c=colors[nop - 1]) ax002.set_ylabel(r'$K_{\perp} [eV]$') ax002.grid() ax003 = plt.subplot(333, sharex=ax001) ax003.plot(vars['time'], vars['Psi_g'] * 1.0e4, c=colors[nop - 1]) ax003.set_ylabel(r'$\Psi_{gc}\times 10^4 [Tm^2]$') ax003.grid() ax004 = plt.subplot(334, sharex=ax001) ax004.plot(vars['time'], Emag, c=colors[nop - 1]) ax004.set_ylabel(r'|E| [Vm]') ax004.grid() ax005 = plt.subplot(335, sharex=ax001) ax005.plot(vars['time'], vars['B'] * 1.0e3, c=colors[nop - 1]) ax005.set_ylabel(r'$B_{tot} [mT]$') ax005.grid() ax006 = plt.subplot(336, sharex=ax001) ax006.plot(vars['time'], vars['rgc'], c=colors[nop - 1]) ax006.set_ylabel(r'$r_{gc}$ [m]') ax006.grid() ax007 = plt.subplot(337, sharex=ax001) ax007.plot(vars['time'], vars['mu'], c=colors[nop - 1]) ax007.set_xlabel(r'%s' % time_label) ax007.set_ylabel(r'$\mu [Am^2]$') ax007.grid() ax008 = plt.subplot(338, sharex=ax001) ax008.plot(cum_rot_time, f_tor_rot / 1.0e3, c=colors[nop - 1], marker='*') ax008.set_xlabel(r'%s' % time_label) ax008.set_ylabel(r'$\langle f_{tor}\rangle [kHz]$') ax008.grid() ax009 = plt.subplot(339, sharex=ax001) ax009.set_xlabel(r'%s' % time_label) ax009.set_ylabel(r'$v_{E\times B,tor} [m/s^{-1}]$') ax009.plot(vars['time'], vExB_tor, c=colors[nop - 1]) ax009.grid()
def plot_Psigc_rot(vars_all, rwa, rwf, rwfg, time_unit=1.0e6): ''' Plot radial position of gyrocenter (in terms of the flux function of the gyrocenter) and the toroidal rotation frequency vs. time. ''' num_particles = len(vars_all) colors = cm.rainbow(np.linspace(0, 1, num_particles)) if time_unit == 1.0e6: time_label = 'time $[\mu s]$' else: time_label = 'time $[10^{%f} s]$' % (np.log10(1.0 / time_unit)) figg = plt.figure(figsize=(16, 8)) for nop in range(1, num_particles + 1): vars = vars_all['%s' % (str(nop))] Emag = np.sqrt(vars['Ex']**2 + vars['Ey']**2) rot_angle = np.arccos(vars['xgc'] / vars['rgc']) # in radians dt_s = np.diff(vars['time'])[0] / time_unit rot_freq = np.abs(np.gradient(rot_angle, dt_s)) / (2 * np.pi) # in Hz # low-pass filter of rotation frequency to average over bouncing & gyration window_length = int(len(vars['time']) / 32.0) if np.mod(window_length, 2) == 0: window_length += 1 f_ave = savgol_filter(rot_freq, window_length, 1) if num_particles == 1: ccc = 'r' else: ccc = colors[nop - 1] # Compute E_{theta} and E_r E_r = vars['Ex'] * np.cos(rot_angle) + vars['Ey'] * np.sin(rot_angle) E_theta = -vars['Ex'] * np.sin(rot_angle) + vars['Ey'] * np.cos( rot_angle) vExB_r = E_theta * vars['Bz'] vExB_tor = -E_r * vars['Bz'] #vpar=2.0*vars['Kpara']*qe/me #vperp=vpar=2.0*vars['Kperp']*qe/me # Summary plot (style #2): ax001 = plt.subplot(121) ax001.plot(vars['time'], vars['Psi_g'] * 1.0e4, c=colors[nop - 1]) ax001.set_xlabel(r'%s' % time_label) ax001.set_ylabel(r'$\Psi_{gc}\times 10^4 [Tm^2]$') ax001.grid() f_RW = rwf + rwfg * vars['time'] / time_unit ax002 = plt.subplot(122, sharex=ax001) ax002.set_xlabel(r'%s' % time_label) ax002.set_ylabel(r'$f_{tor} [kHz]$') ax002.plot(vars['time'], rot_freq / 1.0e3, c=colors[nop - 1]) ax002.plot(vars['time'], f_ave / 1.0e3, c=ccc, linewidth=3.0) if rwa != 0: ax002.plot(vars['time'], f_RW / 1.0e3, c='k', linewidth=4.0, label='$f_{RW}$') if nop == 1: leg = plt.legend(loc='best', fontsize=20).draggable() ax002.grid()