def create_artists(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans): label = orig_handle.get_label() #print(label, orig_handle) if label == 'photon': return self.create_photon_legend(legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans) elif label == 'output amplifier': legline, legline_marker = HandlerLine2D.create_artists(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans) legline_marker.set_marker('>') legline_marker.set_mfc('w') legline_marker.set_ms(7.5) legline_marker.set_mew(1.5) return [legline, legline_marker] else: return HandlerLine2D.create_artists(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans)
def create_artists(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans): legline, legline_marker = HandlerLine2D.create_artists(self, legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans) if hasattr(orig_handle, "_markerhacked"): this_axes._hack_linedraw(legline_marker, True) return [legline, legline_marker]
def plot_loss_and_accurate(train_dict, test_dict): label1, = plt.plot(train_dict.keys(), train_dict.values(), "b-", label="Training accurate per epoch") label2, = plt.plot(test_dict.keys(), test_dict.values(), "r-", label="Test accurate per epoch") plt.legend(handler_map={label1: HandlerLine2D(numpoints=4)}) plt.legend(handler_map={label2: HandlerLine2D(numpoints=4)}) plt.show()
]) W = solve(A, p) f2 = fn(W) # matrix 3 A = np.array([ (1, 1, 1, 1), (1, 4, 4**2, 4**3), (1, 10, 10**2, 10**3), (1, 15, 15**2, 15**3), ]) p = np.array([ f(1), f(4), f(10), f(15), ]) W = solve(A, p) f3 = fn(W) for index, fun in enumerate((f, f1, f2, f3)): plot, = plt.plot(X, [fun(x) for x in X], label='f%s(x)' % (index or '')) plt.legend(handler_map={plot: HandlerLine2D(numpoints=4)}) with open('task2.txt', 'w') as answ: answ.write(('%.2f ' * 4).strip() % tuple(W))
def main(X, y): # X= X_train, y=y_train X_t = X #X_train y_t = y #y_train x_test = np.genfromtxt('../../Data/x_test.csv', delimiter=',') # shape = (50000, 29) """ I found that my best model was a decision tree classifier with max_depth= 6 for the current dataset """ # x_predicted, run_time = decision_tree_classsifier(6, 5, X_t, y_t, x_test) # np.savetxt("Best_Predictions_For_x_test.csv", x_predicted, delimiter=",") """ I will plot 2 lines ->test_results and train_results on graph -> y axis will correspond to AUC score (for different d) and x axis would be different hyperparameters (I am just trying depth and we can do similar stuff for different hyperparameters). The graph will let us know if my model is over fitting or underfitting. """ test_results=[] train_results= [] def k_fold_validation(depth=6, train_x=None, train_y=None): X = train_x y = train_y kf = KFold(n_splits=5) kf.get_n_splits(train_x) F1 = 0 AUC = 0 precision = 0 recall = 0 for i, (train_index, test_index) in enumerate(kf.split(X)): #print(" running for FOLD=" + str(i + 1)) X_train, X_test = X[train_index], X[test_index] y_train, y_test = y[train_index], y[test_index] predicted, run_time = decision_tree_classsifier(depth,10, X_train, y_train, X_test ) precision+=metrics.precision_score(y_test, predicted) recall+= metrics.recall_score(y_test, predicted) F1+= metrics.f1_score(y_test,predicted) AUC+=metrics.roc_auc_score(y_test,predicted) print("Final Precision for all the 5 folds is " + str(precision / 5)) print("Final Recall for all the 5 folds is " + str(recall / 5)) print("Final F1 for all the 5 folds is " + str(F1 / 5)) print("Final AUC for all the 5 folds is " + str(AUC / 5)) test_results.append(AUC / 5) D_list = [3,6,9,12,15] training_time=[] #used to plot graph for D in D_list: #hyper parameter tuning for choosing the best Depth print("#######################################################") print("Decision Tree FOR D="+str(D)) print("#######################################################") print("-----------Avg Validation Set ----------------") start = time.time() k_fold_validation(D, X_t, y_t) #K FOLD VALIDATION end = time.time() runtime = (end - start) * 1000 # covert to ms training_time.append(runtime) print("-----------Full Training Set ----------------") predicted_full, run_time_full = decision_tree_classsifier(D, 5, X_t, y_t, X_t) precision_full = metrics.precision_score(y_t, predicted_full) recall_full = metrics.recall_score(y_t, predicted_full) F1_full = metrics.f1_score(y_t, predicted_full) AUC_full = metrics.roc_auc_score(y_t, predicted_full) print("Final Precision for Full Training Set= " + str(precision_full)) print("Final Recall for Full Training Set= " + str(recall_full)) print("Final F1 for Full Training Set= " + str(F1_full)) print("AUC for Full Training Set= " + str(AUC_full)) train_results.append(AUC_full) plt.figure("DECISION TREE TIME FOR EACH MODEL") plt.plot(D_list, training_time) plt.xlabel("Value of D") plt.ylabel("Execution time in ms") plt.show() plt.figure("Hyper-parameter tuning for Max-Depth") line1, = plt.plot(D_list, train_results, 'b', label ="Train AUC") line2, = plt.plot(D_list, test_results, 'r', label ="Test AUC") plt.legend(handler_map={line1: HandlerLine2D(numpoints=2)}) plt.ylabel("AUC score") plt.xlabel("Tree depth") plt.show() #we can see how how we start to overfit with increasing depth. we can choose d=6 for our best model
'Isolated/Isolated_NodesDistinguishable1_Dayspresymp3_Daysasymp4_ps0.050_pt0.500_ShapeSkewed_Ignoreparents1_Ntrace30_IsolateRightAwaytrue.txt', color='g', label='Forward contact tracing', nbins=binnumber, smallfig=False) add_label(ax, inset, labels, labelsize) add_insetlabel(ax, 'B', insetnumbersize) add_insetimage(ax, height="50%", loc=1, image=im_skewed_empirical) give_ticksize(ax, labelsize) ax.legend(loc=4, frameon=False, handler_map={ PathCollection: HandlerPathCollection(update_func=update), plt.Line2D: HandlerLine2D(update_func=update) }, fontsize=5., markerfirst=True) plt.tight_layout() plt.savefig('figures/resfig_isolate.png', dpi=400) plot_dimension = (1, 1) fig_res(4, labels, length=5, factor=1) plt.figure(4) inset = (0, 0) ax = plt.subplot2grid(plot_dimension, inset, rowspan=1, colspan=1) hist_inf_prev_per_isolate( ax,
def plot(parameters_file, list_of_pairs_of_files=[], image_output_file=None): """ Plot the results of the previously run design space exploration. """ try: hypermapper_pwd = os.environ["PWD"] hypermapper_home = os.environ["HYPERMAPPER_HOME"] os.chdir(hypermapper_home) except: hypermapper_home = "." hypermapper_pwd = "." show_samples = False filename, file_extension = os.path.splitext(parameters_file) if file_extension != ".json": print( "Error: invalid file name. \nThe input file has to be a .json file not a %s" % file_extension ) exit(1) with open(parameters_file, "r") as f: config = json.load(f) schema = json.load(resource_stream("hypermapper", "schema.json")) DefaultValidatingDraft4Validator = extend_with_default(Draft4Validator) DefaultValidatingDraft4Validator(schema).validate(config) application_name = config["application_name"] optimization_metrics = config["optimization_objectives"] feasible_output = config["feasible_output"] feasible_output_name = feasible_output["name"] run_directory = config["run_directory"] if run_directory == ".": run_directory = hypermapper_pwd config["run_directory"] = run_directory xlog = config["output_image"]["image_xlog"] ylog = config["output_image"]["image_ylog"] if "optimization_objectives_labels_image_pdf" in config["output_image"]: optimization_objectives_labels_image_pdf = config["output_image"][ "optimization_objectives_labels_image_pdf" ] else: optimization_objectives_labels_image_pdf = optimization_metrics # Only consider the files in the json file if there are no input files. if list_of_pairs_of_files == []: output_pareto_file = config["output_pareto_file"] if output_pareto_file == "output_pareto.csv": output_pareto_file = application_name + "_" + output_pareto_file output_data_file = config["output_data_file"] if output_data_file == "output_samples.csv": output_data_file = application_name + "_" + output_data_file list_of_pairs_of_files.append( ( deal_with_relative_and_absolute_path(run_directory, output_pareto_file), deal_with_relative_and_absolute_path(run_directory, output_data_file), ) ) else: for idx, (output_pareto_file, output_data_file) in enumerate( list_of_pairs_of_files ): list_of_pairs_of_files[idx] = ( deal_with_relative_and_absolute_path(run_directory, output_pareto_file), deal_with_relative_and_absolute_path(run_directory, output_data_file), ) if image_output_file != None: output_image_pdf_file = image_output_file output_image_pdf_file = deal_with_relative_and_absolute_path( run_directory, output_image_pdf_file ) filename = os.path.basename(output_image_pdf_file) path = os.path.dirname(output_image_pdf_file) if path == "": output_image_pdf_file_with_all_samples = "all_" + filename else: output_image_pdf_file_with_all_samples = path + "/" + "all_" + filename else: tmp_file_name = config["output_image"]["output_image_pdf_file"] if tmp_file_name == "output_pareto.pdf": tmp_file_name = application_name + "_" + tmp_file_name output_image_pdf_file = deal_with_relative_and_absolute_path( run_directory, tmp_file_name ) filename = os.path.basename(output_image_pdf_file) path = os.path.dirname(output_image_pdf_file) if path == "": output_image_pdf_file_with_all_samples = "all_" + filename else: output_image_pdf_file_with_all_samples = path + "/" + "all_" + filename str_files = "" for e in list_of_pairs_of_files: str_files += str(e[0] + " " + e[1] + " ") print("######### plot_pareto.py ##########################") print("### Parameters file is %s" % parameters_file) print("### The Pareto and DSE data files are: %s" % str_files) print("### The first output pdf image is %s" % output_image_pdf_file) print( "### The second output pdf image is %s" % output_image_pdf_file_with_all_samples ) print("################################################") param_space = space.Space(config) xelem = optimization_metrics[0] yelem = optimization_metrics[1] handler_map_for_legend = {} xlabel = optimization_objectives_labels_image_pdf[0] ylabel = optimization_objectives_labels_image_pdf[1] x_max = float("-inf") x_min = float("inf") y_max = float("-inf") y_min = float("inf") print_legend = True fig = plt.figure() ax1 = plt.subplot(1, 1, 1) if xlog: ax1.set_xscale("log") if ylog: ax1.set_yscale("log") objective_1_max = objective_2_max = 1 objective_1_is_percentage = objective_2_is_percentage = False if "objective_1_max" in config["output_image"]: objective_1_max = config["output_image"]["objective_1_max"] objective_1_is_percentage = True if "objective_2_max" in config["output_image"]: objective_2_max = config["output_image"]["objective_2_max"] objective_2_is_percentage = True input_data_array = {} fast_addressing_of_data_array = {} non_valid_optimization_obj_1 = defaultdict(list) non_valid_optimization_obj_2 = defaultdict(list) for ( file_pair ) in ( list_of_pairs_of_files ): # file_pair is tuple containing: (pareto file, DSE file) next_color = get_next_color() ############################################################################# ###### Load data from files and do preprocessing on the data before plotting. ############################################################################# for file in file_pair: print(("Loading data from %s ..." % file)) ( input_data_array[file], fast_addressing_of_data_array[file], ) = param_space.load_data_file(file, debug) if input_data_array[file] == None: print("Error: no data found in input data file: %s. \n" % file_pair[1]) exit(1) if (xelem not in input_data_array[file]) or ( yelem not in input_data_array[file] ): print( "Error: the optimization variables have not been found in input data file %s. \n" % file ) exit(1) print(("Parameters are " + str(list(input_data_array[file].keys())) + "\n")) input_data_array[file][xelem] = [ float(input_data_array[file][xelem][i]) / objective_1_max for i in range(len(input_data_array[file][xelem])) ] input_data_array[file][yelem] = [ float(input_data_array[file][yelem][i]) / objective_2_max for i in range(len(input_data_array[file][yelem])) ] if objective_1_is_percentage: input_data_array[file][xelem] = [ input_data_array[file][xelem][i] * 100 for i in range(len(input_data_array[file][xelem])) ] if objective_2_is_percentage: input_data_array[file][yelem] = [ input_data_array[file][yelem][i] * 100 for i in range(len(input_data_array[file][yelem])) ] x_max, x_min, y_max, y_min = compute_min_max_samples( input_data_array[file], x_max, x_min, xelem, y_max, y_min, yelem ) input_data_array_size = len( input_data_array[file][list(input_data_array[file].keys())[0]] ) print("Size of the data file %s is %d" % (file, input_data_array_size)) file_pareto = file_pair[0] # This is the Pareto file file_search = file_pair[1] # This is the DSE file ###################################################################################################### ###### Compute invalid samples to be plot in a different color (and remove them from the data arrays). ###################################################################################################### if show_samples: i = 0 for ind in range(len(input_data_array[file][yelem])): if input_data_array[file][feasible_output_name][i] == False: non_valid_optimization_obj_2[file_search].append( input_data_array[file][yelem][i] ) non_valid_optimization_obj_1[file_search].append( input_data_array[file][xelem][i] ) for key in list(input_data_array[file].keys()): del input_data_array[file][key][i] else: i += 1 label_is = get_last_dir_and_file_names(file_pareto) (all_samples,) = plt.plot( input_data_array[file_search][xelem], input_data_array[file_search][yelem], color=next_color, linestyle="None", marker=".", mew=0.5, markersize=3, fillstyle="none", label=label_is, ) plt.plot( input_data_array[file_pareto][xelem], input_data_array[file_pareto][yelem], linestyle="None", marker=".", mew=0.5, markersize=3, fillstyle="none", ) handler_map_for_legend[all_samples] = HandlerLine2D(numpoints=1) ################################################################################################################ ##### Create a straight Pareto plot: we need to add one point for each point of the data in paretoX and paretoY. ##### We also need to reorder the points on the x axis first. ################################################################################################################ straight_pareto_x = list() straight_pareto_y = list() if len(input_data_array[file_pareto][xelem]) != 0: data_array_pareto_x, data_array_pareto_y = ( list(t) for t in zip( *sorted( zip( input_data_array[file_pareto][xelem], input_data_array[file_pareto][yelem], ) ) ) ) for j in range(len(data_array_pareto_x)): straight_pareto_x.append(data_array_pareto_x[j]) straight_pareto_x.append(data_array_pareto_x[j]) straight_pareto_y.append(data_array_pareto_y[j]) straight_pareto_y.append(data_array_pareto_y[j]) straight_pareto_x.append(x_max) # Just insert the max on the x axis straight_pareto_y.insert(0, y_max) # Just insert the max on the y axis label_is = "Pareto - " + get_last_dir_and_file_names(file_pareto) (pareto_front,) = plt.plot( straight_pareto_x, straight_pareto_y, label=label_is, linewidth=1, color=next_color, ) handler_map_for_legend[pareto_front] = HandlerLine2D(numpoints=1) label_is = "Invalid Samples - " + get_last_dir_and_file_names(file_search) if show_samples: (non_valid,) = plt.plot( non_valid_optimization_obj_1[file_search], non_valid_optimization_obj_2[file_search], linestyle="None", marker=".", mew=0.5, markersize=3, fillstyle="none", label=label_is, ) handler_map_for_legend[non_valid] = HandlerLine2D(numpoints=1) plt.ylabel(ylabel, fontsize=16) plt.xlabel(xlabel, fontsize=16) for tick in ax1.xaxis.get_major_ticks(): tick.label.set_fontsize( 14 ) # Set the fontsize of the label on the ticks of the x axis for tick in ax1.yaxis.get_major_ticks(): tick.label.set_fontsize( 14 ) # Set the fontsize of the label on the ticks of the y axis # Add the legend with some customizations if print_legend: lgd = ax1.legend( handler_map=handler_map_for_legend, loc="best", bbox_to_anchor=(1, 1), fancybox=True, shadow=True, ncol=1, prop={"size": 14}, ) # Display legend. font = {"size": 16} matplotlib.rc("font", **font) fig.savefig(output_image_pdf_file_with_all_samples, dpi=120, bbox_inches="tight") if objective_1_is_percentage: plt.xlim(0, 100) if objective_2_is_percentage: plt.ylim(0, 100) fig.savefig(output_image_pdf_file, dpi=120, bbox_inches="tight")
mew=0, ls='', label='$p_f$') legend( handles=[leg_cluster, leg_dipole, leg_free], #loc = 2, bbox_to_anchor=(0.95, 0.953), ncol=3, borderpad=0, borderaxespad=0, handletextpad=0.2, columnspacing=0.5, handlelength=1, frameon=False, handler_map={ leg_cluster: HandlerLine2D(numpoints=1, marker_pad=0), leg_dipole: HandlerLine2D(numpoints=1, marker_pad=0), leg_free: HandlerLine2D(numpoints=1, marker_pad=0) }) sca(t10_ax) ylabel('$p_i$') t10_ax.yaxis.set_label_coords(ylabel_x, 0.5) xlabel( "$\\beta / |\\beta_{\mathrm{BKT}}|$ | $\\beta / |\\beta_{\mathrm{EBC}}|$" ) t10_ax.xaxis.set_label_coords(xlabel_x, xlabel_y) sca(t14_ax) xlabel( "$\\beta / |\\beta_{\mathrm{BKT}}|$ | $\\beta / |\\beta_{\mathrm{EBC}}|$"
def main(): data = get_data_from_csv('results.csv') items = clean_and_sort_data_items(data) counter = 0 for site_url, values in items: tti_values = [v['TTI'] for v in values] fcp_line, = plt.plot([v['TTFCP'] for v in values], range(len(values)), 'g-.', label='TTFCP') fmp_line, = plt.plot([v['TTFMP'] for v in values], range(len(values)), 'r--', label='TTFMP') tti_line, = plt.plot(tti_values, range(len(values)), 'b-o', label='TTI') # import IPython; IPython.embed() # import sys # sys.exit(0) onload_line, = plt.plot([v['TTOnload'] for v in values], range(len(values)), 'k-', label='TTOnload') plt.xlabel('NetworkReverseSearch FirstInteractive (ms)') plt.ylabel('Run index') plt.axis([0, 150000, 0, 25]) mean = np.mean(tti_values) std = np.std(tti_values) rel_std = std / mean plt.title(site_url) print '<p id="{0}">{0}: {1}</p>'.format(counter, site_url) print '<img src="{0}.png">'.format(counter) stats = """mean: {0:.2f} std: {1:.2f} rel_std: {2:.4f}""".format(mean, std, rel_std) plt.text(0.95, 0.05, stats, horizontalalignment='right', verticalalignment='bottom', transform=plt.gca().transAxes) handler_map = { fcp_line: HandlerLine2D(numpoints=5), fmp_line: HandlerLine2D(numpoints=5), tti_line: HandlerLine2D(numpoints=5) } plt.legend(handler_map=handler_map, loc='best') if not os.path.exists(generated_graph_dir_name): os.mkdir(generated_graph_dir_name) # plt.show() plt.savefig( os.path.join(generated_graph_dir_name, str(counter) + '.png')) plt.gcf().clear() counter += 1 # break print "Generated " + str(counter) + " graphs"
trainpredictions = dtc.predict(training_inputs) fpr2, tpr2, _ = metrics.roc_curve(training_classes, trainpredictions) dtc_train_accuracy.append( metrics.accuracy_score(training_classes, trainpredictions)) dtc_train_auc.append(metrics.auc(fpr2, tpr2)) train_results.append(metrics.auc(fpr2, tpr2)) # Testing data testpredictions = dtc.predict(testing_inputs) dtc_accuracy.append( metrics.accuracy_score(testing_classes, testpredictions)) fpr, tpr, _ = metrics.roc_curve(testing_classes, testpredictions) dtc_auc.append(metrics.auc(fpr, tpr)) test_results.append(metrics.auc(fpr, tpr)) line1, = plt.plot(min_samples_leafs, train_results, 'b', label="Decision Tree Train AUC") line2, = plt.plot(min_samples_leafs, test_results, 'r', label="Decision Tree Test AUC") plt.legend(handler_map={line1: HandlerLine2D(numpoints=2)}) plt.ylabel('Auc Score') plt.xlabel('Min Samples Leaf') plt.show()
c2 = np.array(c2) c2 = c2[(c2[:, 0] > 3)] plt.yscale('log', nonposy='clip') plt.xscale('log', nonposy='clip') plot(c2[:, 0], c2[:, 1], 'o') # LOWESS Fit #z = lowess(c2[:,1], c2[:,0]); #plot(z[:,0],z[:,1],lw=3,color="yellow",label="LOWESS Fit") # linear fit: slope, intercept = np.polyfit(c2[:, 0], c2[:, 1], 1) plot(c2[:, 0], c2[:, 0] * slope + intercept, 'r', lw=6, label="linear fit") plt.xlabel('% of Recombination', fontsize=15) plt.ylabel('3C score', fontsize=15) plt.legend(handler_map={line1: HandlerLine2D(numpoints=4)}, loc=1) plt.title('Comparions between 3C and Recombination methods', fontsize=15) xticks(fontsize=15) yticks(fontsize=15) PCC = pearsonr(c2[:, 0], c2[:, 1]) text(28, 0.00065, "PCC = " + "0.80", fontsize=15) text(28, 0.00050, "p-value = " + "6.32e-27", fontsize=15) grid()
def plot_time_series(specify_sequence): '''Generates a figure with graphs of data vs time for a specified sequence of experiments, corresponding to a fixed grid width.''' print "Working on sequence", specify_sequence ## Get a dataframe containing only the data for the current grid sequences = [os.path.split(path)[1][0:15] for path in full_df['filepath']] df = full_df[[(sequence == specify_sequence) for sequence in sequences]] ## Throw out rejected shots df = df[df['review_vortex_locations', 'Good'] == True] grid_radius = df['vortex_beam_radius'][0] * dmd_pixel_size grid_radius_micron = grid_radius * 1e6 ## Set up worksheet for data saving worksheet = workbook.add_worksheet('%s micron grid' % grid_radius_micron) worksheet.write(0, 0, 'Time series data for %s micron grid' % grid_radius_micron, bold) for head_i, heading in enumerate(data_table_headings): worksheet.write(1, head_i, heading, bold) worksheet_spectra = workbook.add_worksheet('%s micron grid Spectra' % grid_radius_micron) worksheet_spectra.write( 0, 0, 'Kinetic energy spectra for %s micron grid' % grid_radius_micron, bold) worksheet_spectra.write(1, 0, 'Hold time:', boldshaded) worksheet_spectra.write(2, 0, 'k vector', bold) ### Set up the figure windows and axes for this grid ### fig = figure('dynamics %s' % specify_sequence, figsize=(4.75, 2.8)) ## We use gridspec to arrange the subfigures ## there are two with the same splitting, so that we can control padding better for the larger log-scale graph gs = GridSpec(5, 3, width_ratios=[2, 1, 1]) gs_log = GridSpec(5, 3, width_ratios=[2, 1, 1]) ## Create an axis for each graph class_ax = fig.add_subplot(gs[0, 0]) corr_ax = fig.add_subplot(gs[1, 0]) dm_ax = fig.add_subplot(gs[2, 0]) temp_ax = fig.add_subplot(gs[3, 0]) e_ax = fig.add_subplot(gs[4, 0]) spec_ax = fig.add_subplot(gs_log[:3, 1:3]) logN_ax = fig.add_subplot(gs_log[3:, 1]) logL_ax = fig.add_subplot(gs_log[3:, 2]) ## Set up an inset axis to place the colorbar on the energy spectrum plot in a nice position colorbar_location = [0.73, 0.8, 0.22, 0.03] col_ax = axes([0, 0, 1, 1], frameon=False) col_ip = InsetPosition(spec_ax, colorbar_location) col_ax.set_axes_locator(col_ip) ## Calculations for where to place the inset figure on the energy spectrum such that the x-axis lines up espec_x_min = 2e-2 espec_x_max = 5 espec_inset_x_min = 3.5e-2 espec_inset_x_max = 1.25 figw = log(espec_x_max) - log(espec_x_min) insetoffset = (log(espec_inset_x_min) - log(espec_x_min)) / figw insetw = (log(espec_inset_x_max) - log(espec_inset_x_min)) / figw delta_e_location = [insetoffset, .05, insetw, 0.35] delta_e_ax = axes([0, 0, 1, 1]) delta_e_ip = InsetPosition(spec_ax, delta_e_location) delta_e_ax.set_axes_locator(delta_e_ip) ## An iterator to use to cycle through colours on the energy spectra e_spec_color = iter(cm.inferno_r(np.linspace(0.1, 1, 10))) ### Create empty lists in which we can later store the average value and the uncertainty of each measurement at each hold time ## Classified vortex numbers avg_N_c = [] avg_u_N_c = [] avg_N_d = [] avg_u_N_d = [] avg_N_f = [] avg_u_N_f = [] avg_N_v = [] avg_u_N_v = [] ## Dipole moment avg_d = [] avg_u_d = [] ## Total incompressible kinetic energy per vortex avg_en = [] avg_u_en = [] ## Correlation function avg_c1 = [] avg_u_c1 = [] ## Mean nearest-neighbor vortex distance avg_mean_nearest_vortex = [] u_avg_mean_nearest_vortex = [] ## and of course, we need a time vector t_vals = [] ## Now, we group the dataframe by hold time, and for each time, add the time to t_vals, ## calculate the mean and sem of each measurement, and add them to their appropriate lists: spreadsheet_row = 0 for hold_time, group in df.groupby('vortex_spoon_wait_time'): t_vals.append(hold_time) N_v = group[('vortex_signs_classification_and_statistics', 'N_v')] avg_N_v.append(mean(N_v)) avg_u_N_v.append(sem(N_v)) ## We want the fractional populations, so before averaging, ## each absolute number of clusters has to be divided by the ## total number of vortices in that shot. N_c = group[('vortex_signs_classification_and_statistics', 'N_c')] / N_v avg_N_c.append(mean(N_c)) avg_u_N_c.append(sem(N_c)) N_d = group[('vortex_signs_classification_and_statistics', 'N_d')] / N_v avg_N_d.append(mean(N_d)) avg_u_N_d.append(sem(N_d)) N_f = group[('vortex_signs_classification_and_statistics', 'N_f')] / N_v avg_N_f.append(mean(N_f)) avg_u_N_f.append(sem(N_f)) D = group[('vortex_signs_classification_and_statistics', 'D')] avg_d.append(mean(D)) avg_u_d.append(sem(D)) eN = group[('energy_spectra', 'KE_per_vortex')] avg_en.append(mean(eN)) avg_u_en.append(sem(eN)) C_1 = group[('vortex_signs_classification_and_statistics', 'C_1')] avg_c1.append(mean(C_1)) avg_u_c1.append(sem(C_1)) mean_nearest_vortex = group[( 'vortex_signs_classification_and_statistics', 'mean_nearest_vortex')] avg_mean_nearest_vortex.append(mean(mean_nearest_vortex)) u_avg_mean_nearest_vortex.append(sem(mean_nearest_vortex)) ### Kinetic energy spectra ### ## We make a list containing arrays with the energy spectra of each shot, for this current hold time e_specs = [] for path in group['filepath']: run = lyse.Run(path, no_write=True) e_spec = run.get_result_array('energy_spectra', 'KE_per_vortex_spec') k_vec = run.get_result_array('energy_spectra', 'k_vec') e_specs.append(e_spec) ## Now take that list of arrays and make it an array itself, so that we can take its average and sem across each shot at each k-vector e_specs = array(e_specs) av_e_spec = mean(e_specs, axis=0) u_e_spec = sem(e_specs, axis=0) ## We're going to plot this in the loop, so that we don't have to worry about storing these values for each time point independantly sca(spec_ax) ## Get the colour to use in this loop from the iterator col_now = next(e_spec_color) loglog(k_vec, av_e_spec, c=col_now, label=r"$E(k)$, t = %s" % hold_time) ## We want to plot the difference from t=0.5 in the inset, so on the first loop, we will get the t=0.5 data, ## then subsequent loops will subtract this from the current time's data to get the difference. if hold_time == 0.5: initial_spec = av_e_spec delta_e_ax.plot(k_vec, zeros(shape(initial_spec)), c=col_now, label=r"$E(k)$, t = %s" % hold_time) else: delta_spec = av_e_spec - initial_spec delta_e_ax.plot(k_vec, delta_spec * 1e7, c=col_now, label=r"$E(k)$, t = %s" % hold_time) ## Add energy spectra data for this time point to the spreadsheet: for k_vec_i in range(len(k_vec)): if hold_time == 0.5: worksheet_spectra.write(k_vec_i + 3, 0, k_vec[k_vec_i]) worksheet_spectra.write(k_vec_i + 3, 2 * spreadsheet_row + 1, av_e_spec[k_vec_i], leftborder) worksheet_spectra.write(k_vec_i + 3, 2 * spreadsheet_row + 2, u_e_spec[k_vec_i], rightborder) worksheet_spectra.merge_range(1, 2 * spreadsheet_row + 1, 1, 2 * spreadsheet_row + 2, hold_time, shaded) worksheet_spectra.write(2, 2 * spreadsheet_row + 1, 'E(k)', boldleftborder) worksheet_spectra.write(2, 2 * spreadsheet_row + 2, 'sem(E(k))', boldrightborder) spreadsheet_row += 1 ##### END OF LOOP OVER TIME ##### ### Now, calculate the temperature at each hold time, based on the fraction of clusters and dipoles, and the total vortex number. beta_measured = thermometer_cdN(array(avg_N_c), array(avg_N_d), array(avg_N_v)) beta_upper_error = thermometer_cdN( array(avg_N_c) + array(avg_u_N_c), array(avg_N_d) - array(avg_u_N_d), array(avg_N_v)) beta_lower_error = thermometer_cdN( array(avg_N_c) - array(avg_u_N_c), array(avg_N_d) + array(avg_u_N_d), array(avg_N_v)) ### Now we have everything that we want to plot! ### ## First save it to the spreadsheet for time_i, hold_time in enumerate(t_vals): worksheet.write(time_i + 2, 0, hold_time) worksheet.write(time_i + 2, 1, avg_N_c[time_i]) worksheet.write(time_i + 2, 2, avg_u_N_c[time_i]) worksheet.write(time_i + 2, 3, avg_N_d[time_i]) worksheet.write(time_i + 2, 4, avg_u_N_d[time_i]) worksheet.write(time_i + 2, 5, avg_N_f[time_i]) worksheet.write(time_i + 2, 6, avg_u_N_f[time_i]) worksheet.write(time_i + 2, 7, avg_c1[time_i]) worksheet.write(time_i + 2, 8, avg_u_c1[time_i]) worksheet.write(time_i + 2, 9, avg_d[time_i]) worksheet.write(time_i + 2, 10, avg_u_d[time_i]) worksheet.write(time_i + 2, 11, beta_measured[time_i]) worksheet.write(time_i + 2, 12, beta_measured[time_i] - beta_upper_error[time_i]) worksheet.write(time_i + 2, 13, beta_lower_error[time_i] - beta_measured[time_i]) worksheet.write(time_i + 2, 14, avg_en[time_i]) worksheet.write(time_i + 2, 15, avg_u_en[time_i]) worksheet.write(time_i + 2, 16, avg_N_v[time_i]) worksheet.write(time_i + 2, 17, avg_u_N_v[time_i]) worksheet.write(time_i + 2, 18, avg_mean_nearest_vortex[time_i]) worksheet.write(time_i + 2, 19, u_avg_mean_nearest_vortex[time_i]) ## Temperature graph sca(temp_ax) temp_ax.errorbar(t_vals, beta_measured, yerr=array([ beta_measured - beta_lower_error, beta_upper_error - beta_measured ]), c='k', mfc='k', fmt="o", ms=5, mew=0, capsize=1, capthick=1, ls='-') temp_ax.axhline(y=0, c='k', ls=':', lw=0.5) temp_ax.invert_yaxis() xlim(0, 5.5) ylabel(r"$\beta$") ## Vortex number graph sca(logN_ax) logN_ax.errorbar(t_vals, avg_N_v, yerr=avg_u_N_v, c="k", fmt="o", ms=5, mew=0, capsize=1, capthick=1) logN_ax.set_xscale('log') logN_ax.set_yscale('log') ylabel("$N_v$") xlabel('Hold time (s)') ### Generate guide-to-eye lines to plot on the vortex number panel ### The values of these lines are chosen for each grid such that the lines are close to the data t_for_lines = linspace(0.4, 6, 12) ## 6.0 if specify_sequence == '20171004T121555': ## 3.5 body tn25 = 15 * t_for_lines**(-2. / 5) # 2 body tn1 = 20 * t_for_lines**(-1.) ## 11.5 elif specify_sequence == '20171006T101525': ## 3.5 body tn25 = 13 * t_for_lines**(-2. / 5) # 2 body tn1 = 30 * t_for_lines**(-1.) ##4.2 elif specify_sequence == '20171004T093812': ## 3.5 body tn25 = 11 * t_for_lines**(-2. / 5) # 2 body tn1 = 15 * t_for_lines**(-1.) ## 9.7 elif specify_sequence == '20171004T144649': ## 3.5 body tn25 = 13 * t_for_lines**(-2. / 5) # 2 body tn1 = 25 * t_for_lines**(-1.) ## 7.9 else: ## 3.5 body tn25 = 14 * t_for_lines**(-2. / 5) # 2 body tn1 = 25 * t_for_lines**(-1.) loglog(t_for_lines, tn25, c='k', lw=0.5, ls='-', zorder=-1) loglog(t_for_lines, tn1, c='k', lw=0.5, ls=':', zorder=-1) xlim(0.4, 6) ylim(3, 25) ## Mean distance graph sca(logL_ax) logL_ax.errorbar(t_vals, avg_mean_nearest_vortex, yerr=u_avg_mean_nearest_vortex, c="k", fmt="o", ms=5, mew=0, capsize=1, capthick=1) logL_ax.set_xscale('log') logL_ax.set_yscale('log') ylabel("$l_v/R_\perp$") xlabel('Hold time (s)') ### Generate guide-to-eye lines to plot on the vortex spacing panel ### The values of these lines are chosen for each grid such that the lines are close to the data ## 6.0 if specify_sequence == '20171004T121555': t12 = 0.22 * t_for_lines**(0.5) t15 = 0.23 * t_for_lines**(1. / 5) ## 11.5 elif specify_sequence == '20171006T101525': t12 = 0.22 * t_for_lines**(0.5) t15 = 0.26 * t_for_lines**(1. / 5) ## 4.2 elif specify_sequence == '20171004T093812': t12 = 0.23 * t_for_lines**(0.5) t15 = 0.27 * t_for_lines**(1. / 5) ## 9.7 elif specify_sequence == '20171004T144649': t12 = 0.22 * t_for_lines**(0.5) t15 = 0.26 * t_for_lines**(1. / 5) ##7.9 else: t12 = 0.2 * t_for_lines**(0.5) t15 = 0.25 * t_for_lines**(1. / 5) loglog(t_for_lines, t12, c='k', lw=0.5, ls=':', label=r'$t^{1/2}$', zorder=-1) loglog(t_for_lines, t15, c='k', lw=0.5, ls='-', label=r'$t^{1/5}$', zorder=-1) xlim(0.4, 6) ylim(0.18, 0.55) ## Classified populations graph sca(class_ax) class_ax.errorbar(t_vals, avg_N_f, yerr=avg_u_N_f, c=colour_free, mec=colour_free, mfc=colour_free, fmt="o", ms=5, mew=0, capsize=1, capthick=1, ls='-', label="Free vortices") class_ax.errorbar(t_vals, avg_N_d, yerr=avg_u_N_d, c=colour_dipole, mec=colour_dipole, mfc=colour_dipole, fmt="o", ms=5, mew=0, capsize=1, capthick=1, ls='-', label="Dipole vortices") class_ax.errorbar(t_vals, avg_N_c, yerr=avg_u_N_c, c=colour_cluster, mec=colour_cluster, mfc=colour_cluster, fmt="o", ms=5, mew=0, capsize=1, capthick=1, ls='-', label="Clustered vortices") ylabel("$p_i$") xlim(0, 5.5) ## Add a legend - this is done manually so that we can squash it down to the smallest possible size leg_cluster = mlines.Line2D([], [], color=colour_cluster, marker='o', ms=5, mew=0, ls='-', label='$p_c$') leg_dipole = mlines.Line2D([], [], color=colour_dipole, marker='o', ms=5, mew=0, ls='-', label='$p_d$') leg_free = mlines.Line2D([], [], color=colour_free, marker='o', ms=5, mew=0, ls='-', label='$p_f$') legend(handles=[leg_cluster, leg_dipole, leg_free], bbox_to_anchor=(0.52, 0.99), ncol=3, borderpad=0, borderaxespad=0, handletextpad=0.2, columnspacing=0.5, handlelength=1, frameon=False, handler_map={ leg_cluster: HandlerLine2D(numpoints=1, marker_pad=0), leg_dipole: HandlerLine2D(numpoints=1, marker_pad=0), leg_free: HandlerLine2D(numpoints=1, marker_pad=0) }) ## Total incompressible kinetic energy graph sca(e_ax) ylabel(r"$E_k/N_v$") e_ax.errorbar(t_vals, avg_en, yerr=avg_u_en, c="k", fmt="o", ls='-', ms=5, mew=0, capsize=1, capthick=1) xlim(0, 5.5) ## Dipole moment graph sca(dm_ax) ylabel('$d/R_\perp$') errorbar(t_vals, avg_d, yerr=avg_u_d, c="k", fmt="o", ls='-', ms=5, mew=0, capsize=1, capthick=1) xlim(0, 5.5) ## Correlation function graph sca(corr_ax) corr_ax.axhline(y=0, c='k', ls=':', lw=0.5) ylabel(r"$C_1$") errorbar(t_vals, avg_c1, yerr=avg_u_c1, c="k", fmt="o", label="$C_1$", ls='-', ms=5, mew=0, capsize=1, capthick=1) xlim(0, 5.5) #### Done plotting the data, now tidy up the figure formatting #### ## Turn off tick labels on the x-axis of the stacked graphs class_ax.xaxis.set_ticklabels([]) temp_ax.xaxis.set_ticklabels([]) corr_ax.xaxis.set_ticklabels([]) dm_ax.xaxis.set_ticklabels([]) class_ax.tick_params(axis='x', which='minor', bottom='off', top="off") temp_ax.tick_params(axis='x', which='minor', bottom='off', top="off") corr_ax.tick_params(axis='x', which='minor', bottom='off', top="off") dm_ax.tick_params(axis='x', which='minor', bottom='off', top="off") e_ax.tick_params(axis='x', which='minor', bottom='off', top="off") ## label positioning common values figlabelx = -0.19 figlabely = 0.68 labelx = -0.15 labely = -0.38 ## Fix classification graph formatting sca(class_ax) ## Add the label class_ax.yaxis.set_label_coords(labelx, 0.5) class_ax.xaxis.set_label_coords(0.5, labely) class_ax.set_title('A', fontdict=blackfont, x=figlabelx, y=figlabely) ## Set the y-axis limits and tick marks depending on the grid (values chosen to best display data and provide sensible tick marks) ## 6.0 if specify_sequence == '20171004T121555': yticks([0.2, 0.4, 0.6]) ylim(0, 0.8) ## 11.5 elif specify_sequence == '20171006T101525': yticks([0.2, 0.4, 0.6]) ylim(0, 0.8) ## 4.2 elif specify_sequence == '20171004T093812': yticks([0.2, 0.4, 0.6]) ylim(0, 0.8) ## 9.7 elif specify_sequence == '20171004T144649': yticks([0.2, 0.4, 0.6]) ylim(0, 0.8) ## 7.9 else: yticks([0.2, 0.4, 0.6]) ylim(0, 0.8) ## Fix correlation function graph formatting sca(corr_ax) ## Add the label corr_ax.yaxis.set_label_coords(labelx, 0.5) corr_ax.xaxis.set_label_coords(0.5, labely) corr_ax.set_title('B', fontdict=blackfont, x=figlabelx, y=figlabely) # since this graph has another on top of it, don't plot the top border, it will rely on the bottom border of the next graph up corr_ax.spines["top"].set_visible(False) ## Set the y-axis limits and tick marks depending on the grid (values chosen to best display data and provide sensible tick marks) ## 9.7 if specify_sequence == '20171004T144649': yticks([0, 0.2, 0.4]) ## 7.9 elif specify_sequence == '20171005T090729': yticks([-0.2, 0, 0.2, 0.4]) ## 11.5 elif specify_sequence == '20171006T101525': yticks([0.1, 0.3, 0.5]) ## 4.2 elif specify_sequence == '20171004T093812': yticks([-0.6, -0.4, -0.2, 0, 0.2]) ## 6.0 else: ylim(-0.3, 0.35) yticks([-0.2, 0, 0.2]) ## Fix dipole moment graph formatting sca(dm_ax) ## Add the label dm_ax.yaxis.set_label_coords(labelx, 0.5) dm_ax.xaxis.set_label_coords(0.5, labely) dm_ax.set_title('C', fontdict=blackfont, x=figlabelx, y=figlabely) # since this graph has another on top of it, don't plot the top border, it will rely on the bottom border of the next graph up dm_ax.spines["top"].set_visible(False) ## Set the y-axis limits and tick marks depending on the grid (values chosen to best display data and provide sensible tick marks) # 6.0 if specify_sequence == '20171004T121555': yticks([0.1, 0.2, 0.3]) ylim(0.05, 0.35) ## 11.5 elif specify_sequence == '20171006T101525': ylim(0.18, 0.38) yticks([0.2, 0.25, 0.3, 0.35]) # 4.2 elif specify_sequence == '20171004T093812': yticks([0.1, 0.2, 0.3]) ## 9.7 elif specify_sequence == '20171004T144649': yticks([0.22, 0.26, 0.3]) # 7.9 else: yticks([0.15, 0.2, 0.25, 0.3]) ## Fix temperature graph formatting sca(temp_ax) ## Add the label temp_ax.yaxis.set_label_coords(labelx, 0.5) temp_ax.xaxis.set_label_coords(0.5, labely) temp_ax.set_title('D', fontdict=blackfont, x=figlabelx, y=figlabely) # since this graph has another on top of it, don't plot the top border, it will rely on the bottom border of the next graph up temp_ax.spines["top"].set_visible(False) ## Set the y-axis limits and tick marks depending on the grid (values chosen to best display data and provide sensible tick marks) # 7.9 micron if specify_sequence == '20171005T090729': yticks([0, -0.2, -0.4, -0.6]) # 11.5 micron elif specify_sequence == '20171006T101525': ylim(-0.18, -0.78) yticks([-0.3, -0.5, -0.7]) # 4.2 micron elif specify_sequence == '20171004T093812': yticks([0.2, 0, -0.2, -0.4, -0.6]) ylim(0.4, -0.7) # 9.7 micron elif specify_sequence == '20171004T144649': ylim(-0.1, -0.75) yticks([-0.2, -0.4, -0.6]) # 6.0 micron else: ylim(0.2, -0.65) yticks([0.1, -0.1, -0.3, -0.5]) ## Fix energy graph formatting sca(e_ax) ## Add the label e_ax.yaxis.set_label_coords(labelx, 0.5) e_ax.xaxis.set_label_coords(0.5, labely) e_ax.set_title('E', fontdict=blackfont, x=figlabelx, y=figlabely) # since this graph has another on top of it, don't plot the top border, it will rely on the bottom border of the next graph up e_ax.spines["top"].set_visible(False) # also set the x-label for this graph, since it's on the bottom of the stack xlabel("Hold time (s)") ## Set the y-axis limits and tick marks depending on the grid (values chosen to best display data and provide sensible tick marks) ## 6.0 if specify_sequence == '20171004T121555': ylim(2.25, 3.35) yticks([2.4, 2.6, 2.8, 3, 3.2]) ## 7.9 elif specify_sequence == '20171005T090729': yticks([2.8, 3.0, 3.2]) ## 4.2 elif specify_sequence == '20171004T093812': yticks([2.4, 2.8, 3.2]) ## 11.5 elif specify_sequence == '20171006T101525': yticks([3.0, 3.2, 3.4, 3.6]) ## 9.7 else: yticks([3, 3.2, 3.4]) #### Now fix the spines on the stacked left-hand graphs spine_left_value = -0.8 class_ax.spines['top'].set_bounds(spine_left_value, class_ax.viewLim.intervalx[1]) class_ax.spines['bottom'].set_bounds(spine_left_value, class_ax.viewLim.intervalx[1]) corr_ax.spines['bottom'].set_bounds(spine_left_value, corr_ax.viewLim.intervalx[1]) dm_ax.spines['bottom'].set_bounds(spine_left_value, dm_ax.viewLim.intervalx[1]) temp_ax.spines['bottom'].set_bounds(spine_left_value, temp_ax.viewLim.intervalx[1]) e_ax.spines['bottom'].set_bounds(spine_left_value, e_ax.viewLim.intervalx[1]) ## Fix energy spectrum graph formatting sca(spec_ax) ylabel(r'$E(k)/N_v$') xlabel(r'$k\xi$') ## Add vertical lines: ## Note, k_vec is in units of xi # k*xi = 1 plt.axvline(x=1, c='0.5', ls=':', zorder=-3) # system size k_sys = xi * 2 * pi / (circ_radius * pixel_size * 2) plt.axvline(x=k_sys, c='0.5', ls='-', zorder=-3) # grid size k_grid_radius = xi * pi / grid_radius plt.axvline(x=k_grid_radius, c='0.5', ls='--', zorder=-3) ## Generate guides to the eye at power-law scalings minus1 = 2e-7 * k_vec**(-1) minus3 = 2e-7 * k_vec**(-3) minus53 = 1.55e-7 * k_vec**(-5. / 3) plt.loglog(k_vec, minus1, c='k', ls='-', lw=0.5, zorder=-3) plt.loglog(k_vec, minus3, c='k', ls=':', lw=0.5, zorder=-3) plt.loglog(k_vec, minus53, c='k', ls='--', lw=0.5, zorder=-3) ## Generate a temporary figure environment for using to generate a colorbar for the energy spectra. fakefig = figure('Colorbar') cbar_show = imshow(array([[0, 5]]), cmap="inferno_r") ## Go back to the spectrum axis (creating the figure above will have changed the current axis) and create the colorbar, based on the above imshow sca(spec_ax) cb = colorbar(cbar_show, cax=col_ax, ticks=[0, 5], orientation="horizontal") cb.outline.set_linewidth(0.5) cb.ax.set_xticklabels(cb.ax.get_xticklabels(), fontsize=5, y=1) plt.text(colorbar_location[0] + 0.5 * colorbar_location[2], colorbar_location[1] + 2 * colorbar_location[3], "Hold time (s)", fontsize=5, ha='center', transform=spec_ax.transAxes) ## Now format the figure itself xlim(espec_x_min, espec_x_max) ylim(1e-9, 4e-6) yticks([1e-8, 1e-7, 1e-6]) spec_ax.yaxis.set_label_coords(-0.1, 0.5) spec_ax.xaxis.set_label_coords(0.5, -0.1) spec_ax.set_title('F', fontdict=blackfont, x=-0.14, y=0.88) spec_ax.tick_params(axis='y', direction='in', pad=1) spec_ax.tick_params(axis='x', direction='in', pad=1.5) ## Fix vortex number graph formatting sca(logN_ax) logN_ax.yaxis.set_label_coords(-0.22, 0.5) logN_ax.xaxis.set_label_coords(0.5, -0.24) logN_ax.set_title('G', fontdict=blackfont, x=-0.32, y=0.8) logN_ax.xaxis.set_major_formatter(ScalarFormatter()) logN_ax.yaxis.set_major_formatter(ScalarFormatter()) yticks([4, 6, 10, 20]) xticks([0.5, 1, 2, 5]) ## Fix vortex spacing graph formatting sca(logL_ax) logL_ax.yaxis.set_label_coords(-0.22, 0.5) logL_ax.xaxis.set_label_coords(0.5, -0.24) logL_ax.set_title('H', fontdict=blackfont, x=-0.32, y=0.8) logL_ax.xaxis.set_major_formatter(ScalarFormatter()) logL_ax.yaxis.set_major_formatter(ScalarFormatter()) yticks([0.2, 0.3, 0.4, 0.5]) xticks([0.5, 1, 2, 5]) ## Fix the inset in the energy spectrum graph's formatting sca(delta_e_ax) title(r'$\Delta E(k)/N_v \times 10^7$', fontdict=tinyfont, x=0.2, y=0.9) xlim(espec_inset_x_min, espec_inset_x_max) delta_e_ax.set_xscale("log", nonposx='clip') locator_params(axis='y', nbins=4) delta_e_ax.tick_params(axis='both', length=2) delta_e_ax.tick_params(axis='x', which='minor', length=1) ## Make everything a bit smaller for this inset! for label in (delta_e_ax.get_xticklabels() + delta_e_ax.get_yticklabels()): label.set_fontsize(tinyfont['size']) [i.set_linewidth(0.5) for i in delta_e_ax.spines.itervalues()] delta_e_ax.xaxis.set_major_formatter(NullFormatter()) delta_e_ax.patch.set_alpha(0) delta_e_ax.yaxis.offsetText.set_fontsize(tinyfont['size']) delta_e_ax.tick_params(axis='y', direction='in', pad=1) ## Finally, adjust the spacing and padding on the GridSpecs to make the figure look right gs.update(left=0.085, right=0.85, top=0.995, bottom=0.1, wspace=0, hspace=0.02) gs_log.update(left=0.12, right=0.995, top=0.995, bottom=0.1, wspace=0.35, hspace=1.5) ## Make sure we've got the correct figure, before saving the pdf figure('dynamics %s' % specify_sequence) savefig(os.path.join(results_path, 'individual_run_%s.pdf' % int(grid_radius * 1e6)), transparent=True)
def make_plot(num_plot, color_scale, fluxes_cu, fluxes_cu_2, fluxes_cu_3, fluxes_cu_4, fluxes_cu_5): import matplotlib.pyplot as plt import numpy as np num_bins = 100 flux_min = 0.007 flux_max = 110 plt.figure() bins = np.logspace(np.log10(flux_min), np.log10(flux_max), num_bins) print('bins: ', bins) #bins = np.logspace(flux_min, flux_max, num_bins) hist, bins_edges = np.histogram(fluxes_cu, bins=bins) print(hist) print('the sum: ', hist.sum(), len(hist)) for yy in range(len(hist)): print(bins[yy], hist[yy]) y = np.insert(hist[::-1].astype('float64').cumsum(), 0, 0.001) print('y: ', y) # plt.step(bins[::-1], y, color=color_scale[0], lw=2) if num_plot > 1: hist_2, bins_edges_2 = np.histogram(fluxes_cu_2, bins=bins) y_2 = np.insert(hist_2[::-1].astype('float64').cumsum(), 0, 0.01) # plt.step(bins[::-1], y_2, color=color_scale[1], lw=2) if num_plot > 2: hist_3, bins_edges_3 = np.histogram(fluxes_cu_3, bins=bins) y_3 = np.insert(hist_3[::-1].astype('float64').cumsum(), 0, 0.01) plt.step(bins[::-1], y_3, color=color_scale[2], lw=2) if num_plot > 3: hist_4, bins_edges_4 = np.histogram(fluxes_cu_4, bins=bins) y_4 = np.insert(hist_4[::-1].astype('float64').cumsum(), 0, 0.01) plt.step(bins[::-1], y_4, color=color_scale[3], lw=2) if num_plot > 4: hist_5, bins_edges_5 = np.histogram(fluxes_cu_5, bins=bins) y_5 = np.insert(hist_5[::-1].astype('float64').cumsum(), 0, 0.01) # plt.step(bins[::-1], y_5, color=color_scale[4], lw=2) # import IPython; IPython.embed(); y_sum = [] y_bright = [] for ii in range(len(y)): ysum = y[ii] + y_2[ii] + y_3[ii] + y_4[ii] + y_5[ii] ybright = y[ii] + y_5[ii] y_sum.append(ysum) y_bright.append(ybright) print(y[ii], y_2[ii], y_3[ii], y_4[ii], y_sum[ii], y_bright[ii]) #print(y[ii], y_2[ii], y_sum[ii]) #hist_sum, bin_edges_sum = np.histogram(y_sum,bins=bins) plt.step(bins[::-1], y_sum, color=color_scale[6], lw=2) plt.step(bins[::-1], y_bright, color=color_scale[5], lw=2) plt.loglog() plt.ylim(0.8, 2000) plt.xlim(0.05, 100) plt.ylabel('#') plt.xlabel('F (1-10 TeV) [%cu]') plt.plot([10, 10], [flux_min, 100], 'k-', lw=1, color='black') plt.plot([0.2, 0.2], [flux_min, 5000], 'k--', lw=1, color='black') #line1, = plt.plot(label="pwn", linestyle='-', color='green', lw=2) #line2, = plt.plot(label="snr", linestyle='-', color='blue', lw=2) #plt.legend(handles=[line1], loc=1) #plt.legend(handles=[line2], loc=2) from matplotlib.legend_handler import HandlerLine2D line1, = plt.plot([100000, 10000, 10000], linestyle='-', lw=2, label='PWN', color='green') line2, = plt.plot([1000, 10000, 10000], linestyle='-', lw=2, label='SNR', color='blue') line3, = plt.plot([1000, 10000, 10000], linestyle='-', lw=2, label='gamma-cat', color='red') line4, = plt.plot([1000, 10000, 10000], linestyle='-', lw=2, label='All', color='black') # line5, = plt.plot([1000, 10000, 10000], linestyle='-', lw=2, label='binaries', color='yellow') # line6, = plt.plot([1000, 10000, 10000], linestyle='-', lw=2, label='templates', color='orange') # line7, = plt.plot([1000, 10000, 10000], linestyle='-', lw=2, label='gamma-cat', color='magenta') plt.legend(handler_map={line1: HandlerLine2D(numpoints=8)}) #import matplotlib.patches as mpatches #red_patch = mpatches.Patch(color='red', label='bright sources') #plt.legend(handles=[red_patch]) #blue_patch = mpatches.Patch(color='blue', label='SNR') #plt.legend(handles=[red_patch]) #green_patch = mpatches.Patch(color='red', label='PWN') #plt.legend(handles=[green_patch]) #black_patch = mpatches.Patch(color='black', label='All') #plt.legend(handles=[black_patch]) #plt.hist(fluxes) filename = 'logN_logS_gammalib.png' print('Writing {}'.format(filename)) plt.savefig(filename)
def plot_flux_onlyplaw(total_integratedflux, onlyplaw_alpha, mjdarr, oldplotout, name): inverseflux = np.float64(1.0 / total_integratedflux) #get a linear fit to the inverse flux #group the arrays by mjd so that the plot can be color coded. bluegroup = np.where(mjdarr < 55450) redgroup = np.where(np.logical_and(mjdarr > 55450, mjdarr < 55800)) greengroup = np.where(np.logical_and(mjdarr > 55800, mjdarr < 56200)) brgroup = np.where(np.logical_and(mjdarr > 56200, mjdarr < 56500)) rggroup = np.where(np.logical_and(mjdarr > 56500, mjdarr < 56717)) blackgroup = np.where(mjdarr > 56717) normalinverse = gom(inverseflux) normalized = inverseflux / normalinverse linexarr = np.linspace(0.01, 7, num=400) linefit = np.polyfit(normalized, onlyplaw_alpha, 1) theline = linefit[0] * linexarr + linefit[1] # If the spectral index goes to -2, this would indicate a very hot #Blackbody. Anything with a steeper spectral index will not be thermal #So figure out what the flux of a alpha=-2 power law is with this regression minbump = np.float64(linefit[0] / ((-2.0) - linefit[1])) minbump = (minbump / normalinverse) print linefit, 'linefit' fig = plt.figure(22, figsize=(10, 7)) x = (1.0 / (inverseflux / normalinverse)) line1, = plt.plot(x[bluegroup], onlyplaw_alpha[bluegroup], marker='o', color=(0, 0, 1), linestyle='', label='MJD < 55450', ms=10) line2, = plt.plot(x[redgroup], onlyplaw_alpha[redgroup], marker='<', color=(1, 0, 0), linestyle='', label='55450 < MJD < 55800', ms=10) line3, = plt.plot(x[greengroup], onlyplaw_alpha[greengroup], marker='>', color=(0, 1, 0), linestyle='', label='55800 < MJD < 56200', ms=10) line4, = plt.plot(x[brgroup], onlyplaw_alpha[brgroup], marker='H', color=(1, 0, 1), linestyle='', label='56200 < MJD < 56500', ms=10) line5, = plt.plot(x[rggroup], onlyplaw_alpha[rggroup], marker='D', color=(1, 1, 0), linestyle='', label='56500< MJD < 56714') line6, = plt.plot(x[blackgroup], onlyplaw_alpha[blackgroup], marker='s', color=(0, 0, 0), linestyle='', label='MJD > 56714', ms=10) plt.plot(1.0 / linexarr, theline, color=(0, 0, 1), lw=4) plt.xlim([0.0, 3.0]) plt.xlabel(r'$\mathrm{Flux} \; (10^{-' + str(np.trunc(np.log10(normalinverse)).astype(int)) + r'} \; \mathrm{erg} \; \mathrm{s}^{-1} \;\mathrm{cm}^{-2})$') plt.ylabel(r'$\alpha_{F_{\nu}}$') plt.ylim([-2.0, 1.0]) #plt.legend(loc ='lower right') plt.legend(handler_map={type(line1): HandlerLine2D(numpoints=1)}, loc='lower right') pp = oldplotout + name + '.png' plt.savefig(pp, padinches=0.85) plt.clf() plt.close() fig2 = plt.figure(23, figsize=(10, 7)) x = (inverseflux / normalinverse) line1, = plt.plot(x[bluegroup], onlyplaw_alpha[bluegroup], marker='o', color=(0, 0, 1), linestyle='', label='MJD < 55450', ms=10) line2, = plt.plot(x[redgroup], onlyplaw_alpha[redgroup], marker='<', color=(1, 0, 0), linestyle='', label='55450 < MJD < 55800', ms=10) line3, = plt.plot(x[greengroup], onlyplaw_alpha[greengroup], marker='>', color=(0, 1, 0), linestyle='', label='55800 < MJD < 56200', ms=10) line4, = plt.plot(x[brgroup], onlyplaw_alpha[brgroup], marker='H', color=(1, 0, 1), linestyle='', label='56200 < MJD < 56500', ms=10) line5, = plt.plot(x[rggroup], onlyplaw_alpha[rggroup], marker='D', color=(1, 1, 0), linestyle='', label='56500< MJD < 56714') line6, = plt.plot(x[blackgroup], onlyplaw_alpha[blackgroup], marker='s', color=(0, 0, 0), linestyle='', label='MJD > 56714', ms=10) plt.plot(linexarr, theline, color=(0, 0, 1), lw=4) plt.xlim([0.0, 5.0]) plt.ylim([-2.0, 1.0]) plt.xlabel( r'$\mathrm{Inverse\;Flux} \; (10^{-' + str(np.trunc(np.log10(normalinverse)).astype(int)) + r'} \; \mathrm{erg} \; \mathrm{s}^{-1} \;\mathrm{cm}^{-2})^{-1}$') plt.ylabel(r'$\alpha_{F_{\nu}}$') #plt.legend(loc ='lower left') plt.legend(handler_map={type(line1): HandlerLine2D(numpoints=1)}, loc='lower left') pp = oldplotout + name + '_linear.png' plt.savefig(pp, padinches=0.85) plt.clf() plt.close() return minbump
# <codecell> from matplotlib.legend_handler import HandlerLine2D plt.figure(1) plt.subplot(211) plt.title('Multi-speaker model with 2 English accent speakers',fontsize=14) plt.xlabel('Epoch') plt.ylabel('RMSE') plt.grid(True) speaker1, = plt.plot(vector_1,label = 'Speaker 1',linestyle = '-',marker='^',markersize=7,linewidth=2.0) speaker2, = plt.plot(vector_2,label = 'Speaker 2',linestyle = '-',marker='o',markersize=7,linewidth=2.0) plt.legend(handler_map={speaker1: HandlerLine2D(numpoints=1)}) plt.subplot(212) plt.title('Multi-speaker model with 2 Scottish accent speakers',fontsize=14) plt.xlabel('Epoch') plt.ylabel('RMSE') plt.grid(True) speaker1, = plt.plot(vector_3,label = 'Speaker 1',linestyle = '-',marker='^',markersize=7,linewidth=2.0) speaker2, = plt.plot(vector_4,label = 'Speaker 2',linestyle = '-',marker='o',markersize=7,linewidth=2.0) plt.legend(handler_map={speaker1: HandlerLine2D(numpoints=1)}) plt.show() # <codecell>
a = [map(eval, l.split()[::2]) for l in f] a = [x for x in a if x[0] > 0 and x[3] == 25] pl.figure(figsize=(10, 5), dpi=80) pl.subplots_adjust(bottom=0.2, left=0.1, top=0.9, right=0.95) hm = {} for i, q in enumerate(sorted(set((x[0], x[1]) for x in a))): X = [x[2] for x in a if tuple(x[:2]) == q] Y = [x[5] for x in a if tuple(x[:2]) == q] l, = pl.plot(X, Y, "pos*hd"[i], label="%d Kern%s, %d Thread%s" % (q[0], "e" * (q[0] != 1), q[1] + 1, "s" * (q[1] > 0))) hm[l] = HandlerLine2D(numpoints=1) xticks = X pl.xlabel(u"Taktfrequenz in MHz") pl.ylabel(u"Stromstärke in mA") pl.legend(loc='upper left', prop={"size": 12}, handler_map=hm) pl.grid(True, which='major') pl.xticks(xticks, [ 240, '', '', '', 360, '', '', 480, '', 600, '', '', '', 720, '', '', 816, '', 912, '', 1008 ]) pl.xlim(200, 1008 + 40) #pl.ylim(200, 470) pl.savefig("cubie-energy.pdf")
def __init__(self, ms, *args, **kwargs): self.ms = ms HandlerLine2D.__init__(self, *args, **kwargs)
def optimise_bdt(X_train_new, y_train, X_test_new, y_test): """ The first parameter to tune is max_depth. This indicates how deep the tree can be. The deeper the tree, the more splits it has and it captures more information about the data. We fit a decision tree with depths ranging from 1 to 32 and plot the training and test auc scores. min_samples_split represents the minimum number of samples required to split an internal node. This can vary between considering at least one sample at each node to considering all of the samples at each node. When we increase this parameter, the tree becomes more constrained as it has to consider more samples at each node. Here we will vary the parameter from 10% to 100% of the samples min_samples_leaf is The minimum number of samples required to be at a leaf node. This parameter is similar to min_samples_splits, however, this describe the minimum number of samples of samples at the leafs, the base of the tree. """ optimisation_variables_properties = { "max_depth": { "start": 1, "stop": 32, "num": 32, "dtype": None }, "min_samples_split": { "start": 0.1, "stop": 1.0, "num": 10, "dtype": None }, "min_samples_leaf": { "start": 1, "stop": 2000, "num": 100, "dtype": int } } for key, value in optimisation_variables_properties.items(): optimisation_variables = np.linspace(value['start'], value['stop'], value['num'], endpoint=True, dtype=value['dtype']) train_results = [] test_results = [] for optimisation_variable in optimisation_variables: if key == "max_depth": dt = DecisionTreeClassifier(max_depth=optimisation_variable) elif key == "min_samples_split": dt = DecisionTreeClassifier( min_samples_split=optimisation_variable) elif key == "min_samples_leaf": dt = DecisionTreeClassifier( min_samples_leaf=optimisation_variable) dt.fit(X_train_new, y_train) train_pred = dt.predict(X_train_new) false_positive_rate, true_positive_rate, _ = roc_curve( y_train, train_pred) roc_auc = auc(false_positive_rate, true_positive_rate) train_results.append(roc_auc) y_pred = dt.predict(X_test_new) false_positive_rate, true_positive_rate, _ = roc_curve( y_test, y_pred) roc_auc = auc(false_positive_rate, true_positive_rate) test_results.append(roc_auc) line1, = plt.plot(optimisation_variables, train_results, 'b', label="Train AUC") plt.plot(optimisation_variables, test_results, 'r', label="Test AUC") plt.legend(handler_map={line1: HandlerLine2D(numpoints=2)}) plt.ylabel('AUC score') plt.xlabel(key) plt.savefig(BASE_PATH + 'Plots/optimise_bdt.png')
line1, = plt.semilogx(massRatioSpace,L2space, color="r", marker="o", markersize = 2,markerfacecolor='None',markeredgecolor = 'r', linestyle = "None", label=r'$\frac{L_{2}}{L_{1}}$') line2, = plt.semilogx(massRatioSpace,L3space, color="b", marker="+", markersize = 2,markerfacecolor='w', linestyle = "None", label=r'$\frac{L_{3}}{L_{1}}$') # Plot the range on the y-axis two. ax2 = ax.twinx() line3, = ax2.loglog(massRatioSpace, rangeSpace, color="g", marker="^", markersize = 2,markerfacecolor='None',markeredgecolor = 'g', linestyle = "None", label=r'Range') #ax2.yaxis.set_major_formatter(matplotlib.ticker.ScalarFormatter()) ax2.set_ylabel('Range') #ax2.set_ylim(0.007,2.000) ax.set_xlabel(r'CW/projectile ($m_{1}/m_{2}$) mass ratio') ax.set_ylabel(r'Arm ratio') h1, l1 = ax.get_legend_handles_labels() h2, l2 = ax2.get_legend_handles_labels() plt.legend(h1+h2, l1+l2, loc=0, handler_map={line1: HandlerLine2D(numpoints=1),line2: HandlerLine2D(numpoints=1),line3: HandlerLine2D(numpoints=1)}) xlimits = plt.xlim(10,2000) plt.tight_layout() lpt.savefig('MurlinOptimisation') # Plot a and range on the other graph fig, ax = lpt.newfig(0.6) #lpt.subplot(2,1,1) line1, = plt.semilogx(massRatioSpace,aSpace, color="r", marker="o", markersize = 2,markerfacecolor='None',markeredgecolor = 'r', linestyle = "None", label = r'$a$~value') #plt.ylim(0.97*np.min(aSpace), 1.03*np.max(aSpace)) line2, = plt.semilogx(massRatioSpace,bSpace, color="b", marker="+", markersize = 2,markerfacecolor='w', linestyle = "None", label = r'$b$~value') # Plot the range on the y-axis two. ax2 = ax.twinx() line3, = ax2.loglog(massRatioSpace, rangeSpace, color="g", marker="^", markersize = 2,markerfacecolor='None',markeredgecolor = 'g', linestyle = "None", label = 'range')
def main(): start = timeit.default_timer() #------------------------------------------------------------------------------ # Parametere i sumuleringen #------------------------------------------------------------------------------ #Antall plott-punkter n = 100 # tidsperioder t_1 = 60 * 60 * 24 # 1 dag t_2 = t_1 * 31 # 1 måned t_3 = t_2 * 6 # 6 måneder t_4 = t_1 * 365 # 1 år t_5 = t_4 * 10 # 10 år t = [t_1, t_2, t_3, t_4, t_5] #tidsvektor # (Termiske) egenskaper T_g = 6 # uforstyrret grunntemperatur['C] k_g = 1 # konduktivitet i grunnen [W/mK] a_g = 10**-6 # diffusivitet i grunnen [m^2/s] q = -2 * np.pi * k_g # uniform varmeuttømming fra grunnen [W/m] # Egenskaper til borehull r_b = 0.05 # Avstand til borehullveggen[m] # Diverse matriser u = np.zeros(n) # verdier for nedre grense i intergralet i ILS-løsningen s = (n, 2) I_int = np.zeros(s) # Verdier av integralet i ILS-løsningen T = np.zeros(s) # Temperatur i avstand r[m] fra borehullet z = (n, len(t)) T_t = np.zeros(z) # Temperatur r[m] fra borehullet for ulike tidsperioder # Verdier som skal evalueres i radiell avstand fra linjesluk r_g = 20 # Avstand fra linjesluket som evalueres [m] r = np.linspace(0, r_g, num=n) #------------------------------------------------------------------------------ # Definerer koordinatsystem #------------------------------------------------------------------------------ plt.rc('figure') fig = plt.figure() ax1 = fig.add_subplot(111) # Tittel ax1.set_title('Temperaturprofil ved varmeuttømming') # Aksenavn ax1.set_xlabel(r'Radiell avstand fra linjesluk[m]') ax1.set_ylabel(r'Temperatur[($^\circ$C)]') # Aksegrenser ax1.set_xlim([0., 20.]) ax1.set_ylim([-2., 7.]) # ticks ax1.xaxis.set_minor_locator(AutoMinorLocator()) ax1.yaxis.set_minor_locator(AutoMinorLocator()) # grid ax1.grid(color='k', linestyle='--', linewidth=0.1) # Justerng av plottvindu plt.tight_layout() #------------------------------------------------------------------------------ # Evaluering av ILS-løsningen, der t=konstant og radius fra borehull varierer #------------------------------------------------------------------------------ for j in range(0, len(t) - 1): for i in range(0, n): # verdier for u=r^2/4at u[i] = r[i]**2 / (4 * a_g * t[j]) # integrasjon av integralet i ILS-løsningen I = lambda x: (np.exp(-x)) / x I_int[i] = integrate.quad(I, u[i], m.inf) T[i] = T_g + (q / (2 * m.pi * k_g)) * I_int[i] T_t[:, j] = T[:, 0] # plott av temperaturprofilene line1, = ax1.plot(r, T_t[:, 0], 'r-', markersize=0.5, label='Etter 1 dag') line2, = ax1.plot(r, T_t[:, 1], 'b-', markersize=0.5, label='Etter 1 måned') line3, = ax1.plot(r, T_t[:, 2], 'y-', markersize=0.5, label='Etter 6 måneder') line4, = ax1.plot(r, T_t[:, 3], 'k-', markersize=0.5, label='Etter 1 år') plt.legend(handler_map={line4: HandlerLine2D(numpoints=4)}, loc=4) plt.show() #------------------------------------------------------------------------------ # Evaluering av ILS-løsning, der radius er konstant (=r_b) og tiden varierer #------------------------------------------------------------------------------ # Tidssteg tid = np.linspace(0, t_4, num=n) # Diverse matriser u1 = np.zeros(n) # Nedre grense i integralet i ILS-løsningen I_int1 = np.zeros(s) # Verdier av integralet i ILS-løsningen T1 = np.zeros(s) # Temperatur ved borehullveggen som funksjon av tid # Evaluerer ILS-løsnningen for i in range(0, n): # verdier for u=r_b^2/4a_gt u1[i] = r_b**2 / (4 * a_g * tid[i]) # integrasjon av integralet i ILS-løsningen I = lambda x: (np.exp(-x)) / x I_int1[i] = integrate.quad(I, u1[i], m.inf) #verdier for temperaturen ved borehullveggen T1[i] = T_g - (q / (2 * m.pi * k_g)) * I_int1[i] # Definerer koordinatsystem plt.rc('figure') fig = plt.figure() ax2 = fig.add_subplot(111) # Tittel ax2.set_title('Temperaturprofil ved borehullveggen') # Aksenavn ax2.set_xlabel(r'Tid(sec)') ax2.set_ylabel(r'Temperatur[($^\circ$C)]') # Aksegrenser ax2.set_xlim([0., t_4]) ax2.set_ylim([5., 17.]) # ticks ax2.xaxis.set_minor_locator(AutoMinorLocator()) ax2.yaxis.set_minor_locator(AutoMinorLocator()) # grid ax2.grid(color='k', linestyle='--', linewidth=0.1) # Justerng av plottvindu plt.tight_layout() # plott av temperaturprofil line1, = ax2.plot(tid, T1[:, 0], 'r-', markersize=0.5, label='Temp. ved radius: r_b') plt.legend(handler_map={line4: HandlerLine2D(numpoints=4)}, loc=4) plt.show() stop = timeit.default_timer() print('Total beregningstid ', stop - start, 'sec')
component5diameter.append(nx.diameter(component5)) year.append(x) print component1diameter print component2diameter print component3diameter print component4diameter print component5diameter print plt.figure() plt.ylim(0,50) plt.xlim(1974,2006) fontP = FontProperties() fontP.set_size('small') line1, = plt.plot(year,component1diameter,'r^-', label='Diameter of largest component') plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.12), fancybox=True, shadow=True, ncol=2, handler_map={line1: HandlerLine2D(numpoints=2)}, prop = fontP) line2, = plt.plot(year,component2diameter,'b^-', label='Diameter of second largest component') plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.12), fancybox=True, shadow=True, ncol=2, handler_map={line2: HandlerLine2D(numpoints=2)}, prop = fontP) line3, = plt.plot(year,component3diameter,'g^-', label='Diameter of third largest component') plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.12), fancybox=True, shadow=True, ncol=2, handler_map={line3: HandlerLine2D(numpoints=2)}, prop = fontP) line4, = plt.plot(year,component4diameter,'y^-', label='Diameter of fourth largest component') plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.12), fancybox=True, shadow=True, ncol=2, handler_map={line4: HandlerLine2D(numpoints=2)}, prop = fontP) line5, = plt.plot(year,component5diameter,'k^-', label='Diameter of fifth largest component') plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.12), fancybox=True, shadow=True, ncol=2, handler_map={line5: HandlerLine2D(numpoints=2)}, prop = fontP) ax = plt.subplot(111) box = ax.get_position() ax.set_position([box.x0, box.y0 + box.height * 0.15, box.width, box.height * .85]) plt.title('Diameter vs Year plot') plt.xlabel('Year')