def create_images(results, axis_range=4.0, scalefactor=40.0): """ Batch creates plots (.png) of the particle's positions and write them to images.""" x = results.positions.x.value_in(units.RSun) y = results.positions.y.value_in(units.RSun) z = results.positions.z.value_in(units.RSun) totalsteps = len(x) nr_particles = len(x[0]) times = results.time end_time = times[-1].value_in(units.day) widget = drawwidget("Generating images") pbar = pb.ProgressBar(widgets=widget, maxval=totalsteps).start() for i in range(totalsteps): fig = plt.figure(figsize=(8, 8), dpi=300) ax1 = fig.add_subplot(111) size = (scalefactor * z[i]) / axis_range**2 ax1.scatter(x[i], y[i], s=size, edgecolor='b', facecolor='w') ax1.set_title("Particles:%i Steps:%i End-time:%f days t:%f days"%(nr_particles, totalsteps,\ end_time, times[i].value_in(units.day))) ax1.set_xlim((-1) * axis_range, axis_range) ax1.set_ylim((-1) * axis_range, axis_range) ax1.set_xlabel('RSun') ax1.set_ylabel('RSun') zerostring = zeroes(i) plt.savefig("images/" + zerostring + str(i) + ".png", dpi=120) fig.clf() plt.close() pbar.update(i) pbar.finish()
def __call__(self, block_num, block_size, total_size): if not self.pbar: self.pbar = progressbar.ProgressBar(maxval=total_size) self.pbar.start() downloaded = block_num * block_size if downloaded < total_size: self.pbar.update(downloaded) else: self.pbar.finish()
def __call__(self) -> None: try: while 1: user_input = input('scan white DUT label -> ') parsed = self.dut_label_pattern.findall(user_input) if not parsed: print('scan invalid') continue dut_id = int(parsed[0]) if not self.get_result_from_id(dut_id): print(f'DUT #{dut_id} did not pass the light test.') continue shipment_id = self.associate_id_with_shipment_label(dut_id) user_input = input( f'apply power to light, then scan black PSU label #{shipment_id} -> ' ) if user_input.upper() != f'[PSU#|WDPB:001-{shipment_id:04d}]': print('scan invalid') continue print('\nwaiting for startup...\n') self.progress = progressbar.ProgressBar(maxval=self.num_steps) self.progress.start() for i in range(1, self.num_steps + 1): sleep(.1) self.progress.update(i) print() print('\nerasing test firmware...\n') self.progress = progressbar.ProgressBar(maxval=5) self.progress.start() for i in range(1, 6): self.ftdi.ser.send_ascii('U') sleep(1.) self.progress.update(i) print() print(f'\nwhite #{dut_id} / black #{shipment_id} done.\n') except KeyboardInterrupt: pass
help="Calculate standard deviation of simulated values.") parser.add_argument("--mean", action='store_true', help="Calculate mean of simulated values") args = parser.parse_args() i = args.iterations if args.iterations else 10000 samples = args.samples if args.samples else 1 exp0_1_simulations = [] exp_inf_simulations = [] if args.verbose: print("[+] Calculating integral of e^-(x^2) by Monte Carlo.") print("[+] Running algorithm %d times" % samples) pro = progress.ProgressBar() for _ in pro(range(samples)): exp0_1_simulations.append(integral(0, 1, lambda x: e**-(x**2), i)) exp_inf_simulations.append(integral(-inf, inf, lambda x: e**-(x**2), i)) sleep(0.00001) m01 = mean(exp0_1_simulations) minf = mean(exp_inf_simulations) if args.standard_deviation: sd01 = stdev(exp0_1_simulations) sdinf = stdev(exp_inf_simulations) scipy_int01 = quad(lambda x: e**-(x**2), 0, 1)[0] scipy_inf = quad(lambda x: e**-(x**2), -inf, +inf)[0]
preprocessed_train = load_py2(pth1) class_info_train = load_py2(pth2) filenames_train = load_py2(pth3) pth1 = "/hdd1/flowers102/char-cnn-rnn-preprocessed/test/char-CNN-RNN-embeddings.pickle" pth2 = "/hdd1/flowers102/char-cnn-rnn-preprocessed/test/class_info.pickle" pth3 = "/hdd1/flowers102/char-cnn-rnn-preprocessed/test/filenames.pickle" preprocessed_test = load_py2(pth1) class_info_test = load_py2(pth2) filenames_test = load_py2(pth3) all_preprocessed = preprocessed_train + preprocessed_test all_class_info = class_info_train + class_info_test all_filenames = filenames_train + filenames_test p2save = "/hdd1/diploma_outputs/outputs/char-cnn-rnn-emb.hdf5" f = h5.File(p2save, "w") embeddings = f.create_group("embeddings") bar = progressbar.ProgressBar() names = list(zip(all_filenames, all_preprocessed)) for name, data in bar(names): name = name.decode("utf-8") dset_name = name.split("/")[-1] embeddings.create_dataset(name=dset_name, data=data) f.close() print("ok")
def main(): parser = ArgumentParser() parser.add_argument('-o', '--out_dir', default='investigation/tmp_figures') parser.add_argument('-d', '--result_dir', required=True) parser.add_argument('-r', '--runs', required=True) args = parser.parse_args() out_dir = args.out_dir result_dir = args.result_dir run_ids = args.runs.split(',') bar = progressbar.ProgressBar(widgets=[ ' Loading Runs: ', Percentage(), ' ', Bar(), ' ', ETA() ], maxval=len(run_ids)).start() runs = [] for i, run_id in enumerate(run_ids): try: runs.append( (run_id, *load_run(f'{result_dir}/{run_id}', 'run', 'metrics'))) except FileNotFoundError: print(f'No run found for id {run_id}! Ignoring.', file=sys.stderr) except NoResultsFoundException: print(f'No results found for run {run_id}! Ignoring.', file=sys.stderr) bar.update(i + 1) bar.finish() if os.path.isdir(out_dir): shutil.rmtree(out_dir) os.makedirs(out_dir) bar = progressbar.ProgressBar(widgets=[ 'Calculating Rollouts: ', Percentage(), ' ', Bar(), ' ', ETA() ], maxval=len(runs)).start() data = [] for i, (run_id, config, result, _) in enumerate(runs): _, (obs_rollouts, _), _ = compute_rollout(config, result, config.N) data.append((run_id, config, result, obs_rollouts)) bar.update(i + 1) bar.finish() print('Computing energies.') runs_energies = compute_energies(data) print('Creating plots.') for (run_id, config, _, _), energies in zip(data, runs_energies): domain = np.arange(config.T) * config.h for n, (true_kinetic_energy, true_potential_energy, pred_kinetic_energy, pred_potential_energy) in enumerate(energies): with SubplotsAndSave(out_dir, f'energy-R{run_id}-N{n}-total', place_legend_outside=True) as (fig, ax): ax.plot(domain, true_kinetic_energy + true_potential_energy, color='tuda:blue', label='Truth', zorder=1) ax.plot(domain, pred_kinetic_energy + pred_potential_energy, color='tuda:orange', label='Rollout', zorder=2) ax.axvline((config.T_train - 1) * config.h, color='tuda:red', ls='dotted', label='Prediction Boundary', zorder=3) if config.N > 1: ax.set_title('Sequence %d' % (n + 1)) ax.set_xlabel(r'$t$') ax.set_ylabel('Total Energy') with SubplotsAndSave(out_dir, f'energy-R{run_id}-N{n}-kinetic', place_legend_outside=True) as (fig, ax): ax.plot(domain, true_kinetic_energy, color='tuda:blue', label='Truth', zorder=1) ax.plot(domain, pred_kinetic_energy, color='tuda:orange', label='Rollout', zorder=2) ax.axvline((config.T_train - 1) * config.h, color='tuda:red', ls='dotted', label='Prediction Boundary', zorder=3) if config.N > 1: ax.set_title('Sequence %d' % (n + 1)) ax.set_xlabel(r'$t$') ax.set_ylabel('Kinetic Energy') with SubplotsAndSave(out_dir, f'energy-R{run_id}-N{n}-potential', place_legend_outside=True) as (fig, ax): ax.plot(domain, true_potential_energy, color='tuda:blue', label='Truth', zorder=1) ax.plot(domain, pred_potential_energy, color='tuda:orange', label='Rollout', zorder=2) ax.axvline((config.T_train - 1) * config.h, color='tuda:red', ls='dotted', label='Prediction Boundary', zorder=3) if config.N > 1: ax.set_title('Sequence %d' % (n + 1)) ax.set_xlabel(r'$t$') ax.set_ylabel('Potential Energy')
def FirmwareSetup(self, msg: FirmwareSetup) -> None: print('\nprogramming firmware...\n') self.progress = progressbar.ProgressBar(maxval=msg.n) self.progress.start()
print('Bitwise sort: ' + str(sort_bitwise(array))) print('Time: ' + "%s seconds" % ((time() - st) / iterations).__round__(4)) results_bitwise.append((time() - st) / iterations) def make_str(array): string = '' for i in array: string += str(i.__round__(4)) + ' ' string += '\n' return string tt = time() bar = progressbar.ProgressBar(maxval=total).start() if not logs: print('Sort in progress: ') for p in range(interval, total, interval): if logs: print('========== New iteration (' + str(p) + ') ==========') bar.update(p) array = [] if object_type == 'objects': for o in range(0, p): array.append(Objects(randint(0, 100))) elif object_type == 'string': for o in range(0, p): array.append(''.join(choice(ascii_letters) for _ in range(10))) else: for o in range(0, p):
def run_hydrodynamics(N=100, Mtot=1|units.MSun, Rvir=1|units.RSun, t_end=0.5|units.day, n_steps=10,\ vx = 0 |(units.RSun/units.day),\ vy = 0 |(units.RSun/units.day),\ vz = 0 |(units.RSun/units.day),\ plummer1=None, plummer2=None,\ bodyname = None): """ Runs the hydrodynamics simulation and returns a HydroResults instance. FUNCTION WALKTHROUGH: In the following explanation 'plummer1' and 'plummer2' are assumed to be hdf5 files written by the function write_set_to_file(). Case 1: If 'plummer1' and 'plummer2' are filenames of hdf5 files, then these two plummer spheres will be smashed together. Case 2: If only plummer1 is supplied, then it will evolve plummer1 with t_end timerange and n_steps steps. Case 3: If no plummers spheres are supplied, then it will generate a new plummer sphere using the default/supplied initial conditions. OUTPUT FILES: If 'results_out' is specified, the HydroResult instance is written to file in HDF5 format. This however does not use write_set_to_file() which writes the entire Particles class and its attributes to file at each dt, but uses write_to_hdf5() from the 'support' module which is tailored to writing HydroResults instances to file. This HDF5 contains all necessary data to plot the required plots of the assignment. In addition, the last snapshot of the Particles instance is written to file using write_set_to_file(), the latter file is written to the 'bodies' directory. Only the last snapshot is written to file because the history of a Particle set is not of interest when reloading them to smash plummer spheres. """ converter = nbody_system.nbody_to_si(Mtot, Rvir) fi = Fi(converter) if plummer1 and plummer2: eta_smash = 0.3 | units.day if plummer1 == plummer2: bodies1 = read_set_from_file(plummer1, format='hdf5') bodies2 = bodies1.copy() bodies2.key += 1 else: bodies1 = read_set_from_file(plummer1, format='hdf5') bodies2 = read_set_from_file(plummer2, format='hdf5') bodies1.move_to_center() bodies2.move_to_center() if vx.value_in(vx.unit) == 0 and vy.value_in(vy.unit) == 0 \ and vz.value_in(vz.unit) == 0: bodies1.x += -1 | units.RSun bodies2.x += 1 | units.RSun else: bodies1.x += (-1) * vx * eta_smash bodies2.x += 1 * vx * eta_smash bodies1.vx += vx bodies2.vx += (-1) * vx bodies1.vy += vy bodies2.vy += (-1) * vy bodies1.vz += vz bodies2.vz += (-1) * vz bodies1.add_particles(bodies2) bodies = bodies1 elif plummer1 or plummer2: if plummer1: bodies = read_set_from_file(plummer1) else: bodies = read_set_from_file(plummer2) bodies.move_to_center() else: bodies = new_plummer_gas_model(N, convert_nbody=converter) fi.gas_particles.add_particles(bodies) fi_to_framework = fi.gas_particles.new_channel_to(bodies) fi.parameters.self_gravity_flag = True data = {'lagrangianradii':AdaptingVectorQuantity(),\ 'angular_momentum':AdaptingVectorQuantity(),\ 'time':AdaptingVectorQuantity(),\ 'positions':AdaptingVectorQuantity(),\ 'kinetic_energy':AdaptingVectorQuantity(),\ 'potential_energy':AdaptingVectorQuantity(),\ 'total_energy':AdaptingVectorQuantity() } mass_fractions = [0.10, 0.25, 0.50, 0.75] setattr(data['lagrangianradii'], 'mf', mass_fractions) data['radius_initial'], data['densities_initial'] = radial_density(\ fi.particles.x, fi.particles.mass, N=10, dim=1) timerange = numpy.linspace(0, t_end.value_in(t_end.unit),\ n_steps) | t_end.unit data['time'].extend(timerange) fi.parameters.timestep = t_end / (n_steps + 1) widget = drawwidget("Evolving") pbar = pb.ProgressBar(widgets=widget, maxval=len(timerange)).start() for i, t in enumerate(timerange): fi.evolve_model(t) data['kinetic_energy'].append(fi.kinetic_energy) data['potential_energy'].append(fi.potential_energy) data['total_energy'].append(fi.total_energy) data['positions'].append(fi.particles.position) data['angular_momentum'].append(fi.gas_particles.\ total_angular_momentum()) data['lagrangianradii'].append(fi.particles.LagrangianRadii(\ unit_converter=converter,\ mf=mass_fractions)[0]) if t == timerange[-1] and bodyname: if os.path.dirname(bodyname) == '': filename = "bodies/" + bodyname fi_to_framework.copy() write_set_to_file(bodies.savepoint(t), filename, "hdf5") pbar.update(i) pbar.finish() data['radius_final'], data['densities_final'] = radial_density(\ fi.particles.x, fi.particles.mass, N=10, dim=1) fi.stop() results = HydroResults(data) return results