def make_plot_distance(args): room = Roof(args.L, args.B, args.H, objective_type=args.obj_function, obj_weight=args.obj_weight) base_algo = args.algorithm scipy_algo = scipy_algo_name[base_algo] our_save_string = get_save_string(args) args.algorithm = scipy_algo scipy_save_string = get_save_string(args) x_range = list(range(args.seed_min, args.seed_max)) with open(our_save_string, 'rb') as f: our_results = pkl.load(f) with open(scipy_save_string, 'rb') as f: scipy_results = pkl.load(f) metric = 'final_x' val_ours = onp.around(our_results[metric], 3) val_scipy = onp.around(scipy_results[metric], 3) distance_vec = [] for set1, set2 in zip(val_ours, val_scipy): set1 = onp.array(room.to_pos(set1)) set2 = onp.array(room.to_pos(set2)) set1 = set1.reshape(5, 2) set2 = set2.reshape(5, 2) # print(set1, set2) # dist = conv_distance(set1, set2) # print(dist) # distance_vec.append(dist[0]) min_dist = np.inf indices = np.arange(5, dtype=int) for x in multiset_permutations(indices): set2perm = set2[x] print(set1, '\n', set2perm) dist = np.sqrt(np.linalg.norm(set1 - set2perm)) min_dist = min(min_dist, dist) print(dist, min_dist) distance_vec.append(min_dist) save_plot_name = our_save_string.replace('.pkl', '_%s_distance.png' % metric) print(distance_vec) save_plot( distance_vec, x_range, '%s for %s on %s problem.' % (metric, args.algorithm, args.environment), 'Seeds', metric, save_plot_name) print('Metric %s:' % 'Distance', distance_vec)
def on_save(self, _event): dlg = wx.FileDialog(self, "Save a scan", self.dirname, self.filename, File.RFS, wx.SAVE | wx.OVERWRITE_PROMPT) if dlg.ShowModal() == wx.ID_OK: self.status.set_general("Saving") self.filename = dlg.GetFilename() self.dirname = dlg.GetDirectory() save_plot(self.dirname, self.filename, self.scanInfo, self.spectrum) self.isSaved = True self.status.set_general("Finished") dlg.Destroy()
def make_plot_one_seed_range(args): save_string = get_save_string(args) with open(save_string, 'rb') as f: results = pkl.load(f) metrics = ['final_obj', 'n_iter', 'runtime'] x_range = list(range(args.seed_min, args.seed_max)) for metric in metrics: save_plot_name = save_string.replace('.pkl', '_%s.png' % metric) save_plot( onp.around(results[metric], 3), x_range, '%s for %s on %s problem.' % (metric, args.algorithm, args.environment), 'Seeds', metric, save_plot_name) print('Metric %s:' % metric, results[metric]) print('Metric %s:' % 'final_x', results['final_x'])
def plot(self, euler_angles=True, nutation_angle=True, longitudinal_axis=True, show_plot=False, save_plot=True, filepath=os.path.join(os.path.expanduser('~'), 'SpinFigures'), filenames=['Euler.png', 'Nut.png', 'Axis.png']): """Plots figures and saves them to file by default. All arguments are optional and can be changed if necessary. """ if euler_angles: plot.plot_euler_angles(self.t_span, self.psi, self.theta, self.phi) if save_plot: if not os.path.exists(filepath): os.makedirs(filepath) plot.save_plot(os.path.join(filepath, filenames[0])) if nutation_angle: plot.plot_nutation_angle(self.t_span, self.nutation_angle) if save_plot: if not os.path.exists(filepath): os.makedirs(filepath) plot.save_plot(os.path.join(filepath, filenames[1])) if longitudinal_axis: plot.plot_longitudinal_axis(self.t_span, self.nutation_angle, self.precession_angle) if save_plot: if not os.path.exists(filepath): os.makedirs(filepath) plot.save_plot(os.path.join(filepath, filenames[2])) if show_plot: plot.show_plot()
def accumulated_swe_plots(nc_dir=UT_NC_DIR, domain='d02', domain_name="UT2.6km", labels=[], extent=None, central_longitude=-110): for nc_file in domain_netcdf_files(path=nc_dir, domain=domain): ds = Dataset(nc_dir + '/' + nc_file) swe_in = ds.variables['SNOWNC'][0] * MM_TO_IN lons = ds.variables['XLONG'][0] lats = ds.variables['XLAT'][0] init_time = parser.parse(ds.START_DATE.replace('_', ' ')) cycle = str(init_time.hour).zfill(2) fhour = int(ds.variables['XTIME'][0] / 60) fhour_str = str(fhour).zfill(2) valid_time = init_time + timedelta(hours=fhour) title = plot_title(init_time, valid_time, fhour, 'swe', 'danwrf', 'in') print('saving swe', domain_name, cycle, fhour) plot = SurfacePlot(lons, lats, swe_in, extent=extent, colormap=PRECIP_CMAP_DATA, color_levels=PRECIP_CLEVS, central_longitude=central_longitude, labels=labels, display_counties=True, title=title) plot.save_plot( f'wrf_prod/images/{cycle}z/{domain_name}-{cycle}z-swe-{fhour_str}.png' )
def update(self, position, wpm, volume): if fps_on: global frame_count frame_count+=1 optimal_wpm = (MAXWPM + MINWPM)/2 wpm = realtime_interpreter.get_wpm() #grab wpm value wpm = clamp(MAXWPM - wpm, MINWPM, MAXWPM) #clamp it # print("Updating...") # print("Current wpm (clamped): {}".format(wpm)) # print("Running average WPM: {}".format(float(sum(self.past_wpm[-6:-1]))/len(self.past_wpm[-6:-1]))) if enable_graphing: self.past_wpm.append(wpm) # self.past_volume.append(volume) if fps_on: self.pace_value['text'] = frame_count#'{} WPM'.format(int(wpm)) if enable_graphing: self.wpm_average_history.append(float(sum(self.past_wpm[-3:-1]))/len(self.past_wpm[-3:-1])) plot.save_plot(self.wpm_average_history[-10:-1], 'pace_graph.png', MAXWPM/ 2.0, MINWPM, MAXWPM) # self.scrollb.set(.1, 0.8) #SET SCROLL wpm_settings = plot.get_wpm_settings_outside(MAXWPM / 2.0, MINWPM, MAXWPM) #print(wpm_settings) if wpm > wpm_settings [0] and wpm / 2.0 <= wpm_settings [1]: self.speed_tip['text'] = "Speak faster" self.speed_tip.config(fg='#ff0000') elif wpm >= wpm_settings [1] and wpm / 2.0 <= wpm_settings [2]: self.speed_tip['text'] = "Speak a little slower" self.speed_tip.config(fg='#c9cf00') elif wpm >= wpm_settings [2] and wpm / 2.0 <= wpm_settings [3]: self.speed_tip['text'] = "Good speed" self.speed_tip.config(fg='#009800') elif wpm >= wpm_settings [3] and wpm / 2.0 <= wpm_settings [4]: self.speed_tip['text'] = "Speak a little faster" self.speed_tip.config(fg='#c9cf00') elif wpm >= wpm_settings [4] and wpm / 2.0 <= wpm_settings [5]: self.speed_tip['text'] = "Speak a lot faster" self.speed_tip.config(fg='#ff0000') else: self.speed_tip['text'] = "Please speak at a consistent pace" self.speed_tip.config(fg='black') # self.text.see(1) # print(self.scrollb.get()) # os.system("python3 plot.py 0 150 300 {} volume_graph.png 140".format(str.join(',',past_wpm_str))) # print("Done computing...") img2 = ImageTk.PhotoImage(Image.open("pace_graph.png")) self.Artwork.configure(image=img2) self.Artwork.image = img2 num_words = realtime_interpreter.get_word_number() # Update by word number #print("hi____"+str(num_words)) self.bold_by_word_number(num_words) variations = realtime_interpreter.get_variations() for variation in variations: self.highlight_by_word_number(variation.expected_index)
def update(self, position, wpm, volume): # return None # print("Current wpm: {}".format(wpm)) optimal_wpm = (MAXWPM + MINWPM)/2 wpm = realtime_interpreter.get_wpm() #grab wpm value #process wpm value wpm -= optimal_wpm wpm *= 0.2 if wpm > 0: wpm = abs(wpm ** 1.5) else: wpm = -abs(wpm ** 1.5) wpm += optimal_wpm wpm = clamp(MAXWPM - wpm, MINWPM, MAXWPM) #clamp it # print("Updating...") # print("Current wpm (clamped): {}".format(wpm)) # print("Running average WPM: {}".format(float(sum(self.past_wpm[-6:-1]))/len(self.past_wpm[-6:-1]))) self.past_wpm.append(wpm) # self.past_volume.append(volume) self.pace_value['text'] = ""#'{} WPM'.format(int(wpm)) self.wpm_average_history.append(float(sum(self.past_wpm[-3:-1]))/len(self.past_wpm[-3:-1])) plot.save_plot(self.wpm_average_history[-10:-1], 'rect1.png', MAXWPM/ 2.0, MINWPM, MAXWPM) # plot.save_plot(self.past_wpm, 'rect2.png', 5, 0, 10) # self.scrollb.set(.1, 0.8) wpm_settings = plot.get_wpm_settings_outside(MAXWPM / 2.0, MINWPM, MAXWPM) #print(wpm_settings) if wpm > wpm_settings [0] and wpm / 2.0 <= wpm_settings [1]: self.speed_tip['text'] = "Speak faster" self.speed_tip.config(fg='#ff0000') elif wpm >= wpm_settings [1] and wpm / 2.0 <= wpm_settings [2]: self.speed_tip['text'] = "Speak a little slower" self.speed_tip.config(fg='#c9cf00') elif wpm >= wpm_settings [2] and wpm / 2.0 <= wpm_settings [3]: self.speed_tip['text'] = "Good speed" self.speed_tip.config(fg='#009800') elif wpm >= wpm_settings [3] and wpm / 2.0 <= wpm_settings [4]: self.speed_tip['text'] = "Speak a little faster" self.speed_tip.config(fg='#c9cf00') elif wpm >= wpm_settings [4] and wpm / 2.0 <= wpm_settings [5]: self.speed_tip['text'] = "Speak a lot faster" self.speed_tip.config(fg='#ff0000') else: self.speed_tip['text'] = "Please speak at a consistent pace" self.speed_tip.config(fg='black') # self.text.see(1) # print(self.scrollb.get()) # os.system("python3 plot.py 0 150 300 {} rect2.png 140".format(str.join(',',past_wpm_str))) # # print("Done computing...") img2 = ImageTk.PhotoImage(Image.open("rect1.png")) self.Artwork.configure(image=img2) self.Artwork.image = img2 num_words = realtime_interpreter.get_word_number()
filename = sys.argv[1] print "Got data file", filename with open(filename, 'rb') as f: r = pickle.load(f) os.system('mkdir -p ' + r.output) plot.plot_init() for i in range(len(r.names)): f, ax = plot.run_plot(r.X, r.Y, r.Zs[i], r.names[i]) ax.set_xlabel(r.xlabel) ax.set_ylabel(r.ylabel) if r.xticks != []: ax.set_xticks(r.xticks) if r.yticks != []: ax.set_yticks(r.yticks) if r.xticklabels != []: ax.set_xticklabels(r.xticklabels, rotation=90, ha='right') if r.yticklabels != []: ax.set_yticklabels(r.yticklabels) #xticklabels = ax.get_xticklabels() #xticklabels[0].set_visible(False) plot.save_plot(f, r.output + r.names[i])
def __init__(self, pool, args): start = args.start end = args.end gain = args.gain dwell = args.dwell nfft = args.fft lo = args.lo index = args.index remote = args.remote directory, filename = os.path.split(args.file) _null, ext = os.path.splitext(args.file) self.stepsTotal = 0 self.steps = 0 self.spectrum = {} self.settings = Settings(load=False) error = None if end <= start: error = "Start should be lower than end" elif dwell <= 0: error = "Dwell should be positive" elif nfft <= 0: error = "FFT bins should be positive" elif ext != ".rfs" and ext != ".csv": error = "File extension should be .rfs or .csv" else: device = Device() if remote is None: self.settings.devices = get_devices() count = len(self.settings.devices) if index > count - 1: error = "Device not found ({0} devices in total):\n".format(count) for device in self.settings.devices: error += "\t{0}: {1}\n".format(device.index, device.name) else: device.isDevice = False url = urlparse('//' + remote) if url.hostname is not None: device.server = url.hostname else: error = "Invalid hostname" if url.port is not None: device.port = url.port else: device.port = 1234 self.settings.devices.append(device) index = len(self.settings.devices) - 1 if error is not None: print "Error: {0}".format(error) exit(1) if end - 1 < start: end = start + 1 if remote is None: gain = nearest(gain, self.settings.devices[index].gains) self.settings.start = start self.settings.stop = end self.settings.dwell = calc_real_dwell(dwell) self.settings.nfft = nfft self.settings.devices[index].gain = gain self.settings.devices[index].lo = lo print "{0} - {1}MHz".format(start, end) print "{0}dB Gain".format(gain) print "{0}s Dwell".format(self.settings.dwell) print "{0} FFT points".format(nfft) print "{0}MHz LO".format(lo) if remote is not None: print remote else: print self.settings.devices[index].name self.scan(self.settings, index, pool) if ext == ".rfs": scanInfo = ScanInfo() scanInfo.setFromSettings(self.settings) save_plot(directory, filename, scanInfo, self.spectrum) else: export_plot(directory, filename, self.spectrum) print "Done"
comb = (lr, drop, reg, size) histories[comb] = model.fit_generator(train_generator, steps_per_epoch=TRAINING_STEPS, epochs=EPOCHS, validation_data=val_generator, validation_steps=VALIDATION_STEPS, callbacks=[es_val_loss]) # update best combination of hyperparameters based on validation loss if minimum > min(histories[comb].history['val_loss']): minimum = min(histories[comb].history['val_loss']) best_comb = comb # save plots save_path = './plots/' + '_'.join(str(comb[i]) for i in range(len(comb))) + '.pdf' save_plot(save_path, histories[comb].history) # storying histories for later usages with open('./histories/'+'_'.join(str(label) for label in comb), 'wb') as fd: pickle.dump(histories[comb].history, fd) print('Trained from scratch with: lr={}, dropout={}, regularization term={}, dense size={}'. format(lr, drop, reg, size)) print('The best combination of hyperparameters is found to be: {}'.format(best_comb)) print('The corresponding metrics are: val_loss={} and val_categorical_accuracy={}'. format(minimum, histories[best_comb].history['val_categorical_accuracy'][np.argmin(histories[best_comb].history['val_loss'])])) lr, drop, reg, size = best_comb ### Train the best model ###
import plot as plt import scipy.optimize as optimization from numpy import * k = 13 path = "h_125.dat" data = array(plt.parse(path)) f = lambda x, a, b, c, d: a*exp(-b*x**c) + d fig, ax = plt.new_plot(title="K-means, %d Clusters" % k, xaxis="Time [ms]", yaxis="K-means distortion") p0 = [2.7, 1., 1.1, .25] p, e = optimization.curve_fit(f, data[:,0], data[:,1], p0) print p X = linspace(0, max(data[:,0]), 100) plt.dot(data[:,0]*.005, data[:,1], "H = 50 mT") plt.add(X*.005, f(X, p[0], p[1], p[2], p[3]), "Exponential fit") plt.save_plot(fig, ax, path[:-4]+".png")
import plot as plt from numpy import * k = 13 path = "h1000.dat" data = array(plt.parse(path)) blur = 15 smoothed = array(data[:,1]) for i in range(blur, len(smoothed)-blur): for j in range(-blur, blur): smoothed[i] += data[i+j,1] smoothed[i] /= (2*blur) fig, ax = plt.new_plot(title="K-means, %d Clusters" % k, xaxis="Time [ms]", yaxis="K-means distortion") plt.add(arange(len(smoothed))*.001, smoothed, "K-Means Cluster Distortion Smoothed") plt.dot(arange(len(data))*.001, data[:,1], "K-Means Cluster Distortion") plt.save_plot(fig, ax, "plt1.png")