def sample(job): "Sample system for the specified number of steps." hoomd.context.initialize('--mode=cpu') with job: hoomd.init.read_gsd(filename='init.gsd', restart='restart.gsd') mc = hoomd.hpmc.integrate.convex_polygon(restore_state=True, seed=job.sp.seed) d = hoomd.dump.gsd("trajectory.gsd", period=500, group=hoomd.group.all()) d.dump_state(mc) restart = hoomd.dump.gsd("restart.gsd", period=500, group=hoomd.group.all(), truncate=True) restart.dump_state(mc) hoomd.analyze.log(filename="log.dat", quantities=['volume'], period=100) boxmc = hoomd.hpmc.update.boxmc(mc, betaP=job.sp.betaP, seed=job.sp.seed) boxmc.ln_volume(delta=0.001, weight=1) hoomd.run_upto(job.doc.steps + 1) restart.write_restart()
def sample(job): "Sample operation." import logging import hoomd from hoomd import md if hoomd.context.exec_conf is None: hoomd.context.initialize('') with job: with hoomd.context.SimulationContext(): hoomd.init.read_gsd('init.gsd', restart='restart.gsd') group = hoomd.group.all() gsd_restart = hoomd.dump.gsd( 'restart.gsd', truncate=True, period=100, phase=0, group=group) lj = md.pair.lj(r_cut=job.sp.r_cut, nlist=md.nlist.cell()) lj.pair_coeff.set('A', 'A', epsilon=job.sp.epsilon, sigma=job.sp.sigma) md.integrate.mode_standard(dt=0.005) md.integrate.npt( group=group, kT=job.sp.kT, tau=job.sp.tau, P=job.sp.p, tauP=job.sp.tauP) hoomd.analyze.log('dump.log', ['volume'], 100, phase=0) try: hoomd.run_upto(5000) except hoomd.WalltimeLimitReached: logging.warning("Reached walltime limit.") finally: gsd_restart.write_restart() job.document['sample_step'] = hoomd.get_step()
(20e6, box_dims[0] * np.sqrt(2)), (40e6, box_dims[0])]) ly_variant = hoomd.variant.linear_interp([(0, box_dims[1]), (20e6, box_dims[1] * np.sqrt(2)), (40e6, box_dims[1])]) lz_variant = hoomd.variant.linear_interp([(0, box_dims[2]), (20e6, box_dims[2] / 2), (40e6, box_dims[2])]) temp_variant = hoomd.variant.linear_interp([(0, 500 * kb), (20e6, 500 * kb), (40e6, 405 * kb)]) hoomd.update.box_resize(Lx=lx_variant, Ly=ly_variant, Lz=lz_variant) hoomd.md.integrate.mode_standard(dt=0.02) nvt_integrator = hoomd.md.integrate.nvt(group=all, kT=temp_variant, tau=1) hoomd.run_upto(40e6) nvt_integrator.disable() # NPT with annealing temp_variant = hoomd.variant.linear_interp([(40e6, 450 * kb), (60e6, 305 * kb)]) hoomd.md.integrate.mode_standard(dt=0.02) npt_integrator = hoomd.md.integrate.npt(group=all, couple='xy', kT=temp_variant, tau=1, P=atm, tauP=10) hoomd.run_upto(60e6) gsd_restart.write_restart()
group=groupall, dynamic=['momentum'], overwrite=True) do_template_relaxing(steps=2000, dump_period=200) do_disordering(kT=5.0, steps=1e4, dump_period=2000) do_templating(kT=4.0, steps=1e4, cooling_steps=2000, dump_period=2000) gsd_dump.disable() setup_steps = 24000 #sum of all steps in the previous four lines. Automate? #This is the final "annealing" phase. groupAB_not_pinned = get_particles_not_pinned() gsd_dump = hoomd.dump.gsd(filestringbase + filestring + '.gsd', period=final_dump_period, phase=(setup_steps - 1) % final_dump_period + 1, group=groupall, dynamic=['momentum'], overwrite=False) restart_dump = hoomd.dump.gsd(restart_filename, period=restart_period, phase=(setup_steps - 1) % restart_period + 1, group=groupall, dynamic=['momentum'], truncate=True) if not restarting_from_file: gsd_dump.write_restart() restart_dump.write_restart() integrator = hoomd.md.integrate.langevin(kT=inp.kT, group=groupAB_not_pinned, seed=inp.se) hoomd.run_upto(setup_steps + inp.ts + 1)
def quench( self, n_steps, kT=None, pressure=None, shrink_kT=None, shrink_steps=None, shrink_period=None, walls=True, ): """""" if walls and pressure: raise ValueError( "Wall potentials can only be used with the NVT ensemble") hoomd_args = f"--single-mpi --mode={self.mode}" sim = hoomd.context.initialize(hoomd_args) with sim: objs, refs = create_hoomd_simulation(self.system_pmd, self.ref_distance, self.ref_mass, self.ref_energy, self.r_cut, self.auto_scale, nlist=self.nlist) hoomd_system = objs[1] init_snap = objs[0] _all = hoomd.group.all() hoomd.md.integrate.mode_standard(dt=self.dt) hoomd.dump.gsd( "sim_traj.gsd", period=self.gsd_write, group=_all, phase=0, dynamic=["momentum"], overwrite=False, ) hoomd.analyze.log( "sim_traj.log", period=self.log_write, quantities=self.log_quantities, header_prefix="#", overwrite=True, phase=0, ) if len([i for i in (shrink_kT, shrink_steps) if i is None]) == 1: raise ValueError( "Both of shrink_kT and shrink_steps need to be given") if shrink_kT and shrink_steps: integrator = hoomd.md.integrate.nvt(group=_all, kT=shrink_kT, tau=self.tau_kt) integrator.randomize_velocities(seed=self.seed) x_variant = hoomd.variant.linear_interp([ (0, init_snap.box.Lx), (shrink_steps, self.target_box[0] * 10) ]) y_variant = hoomd.variant.linear_interp([ (0, init_snap.box.Ly), (shrink_steps, self.target_box[1] * 10) ]) z_variant = hoomd.variant.linear_interp([ (0, init_snap.box.Lz), (shrink_steps, self.target_box[2] * 10) ]) box_updater = hoomd.update.box_resize(Lx=x_variant, Ly=y_variant, Lz=z_variant, period=shrink_period) # Update wall origins during shrinking if walls: wall_origin = (init_snap.box.Lx / 2, 0, 0) normal_vector = (-1, 0, 0) wall_origin2 = (-init_snap.box.Lx / 2, 0, 0) normal_vector2 = (1, 0, 0) walls = wall.group( wall.plane(origin=wall_origin, normal=normal_vector, inside=True), wall.plane(origin=wall_origin2, normal=normal_vector2, inside=True), ) wall_force = wall.lj(walls, r_cut=2.5) wall_force.force_coeff.set(init_snap.particles.types, sigma=1.0, epsilon=1.0, r_extrap=0) step = 0 start = time.time() while step < shrink_steps: hoomd.run_upto(step + shrink_period) current_box = hoomd_system.box walls.del_plane([0, 1]) walls.add_plane((current_box.Lx / 2, 0, 0), normal_vector) walls.add_plane((-current_box.Lx / 2, 0, 0), normal_vector2) step += shrink_period print(f"Finished step {step} of {shrink_steps}") print( f"Shrinking is {round(step / shrink_steps, 5) * 100}% complete" ) print(f"time elapsed: {time.time() - start}") else: hoomd.run_upto(shrink_steps) box_updater.disable() gsd_restart = hoomd.dump.gsd("restart.gsd", period=self.gsd_write, group=_all, truncate=True, phase=0, dynamic=["momentum"]) # Run the primary simulation if pressure: try: # Not defined if no shrink step integrator.disable() except NameError: pass integrator = hoomd.md.integrate.npt(group=_all, tau=self.tau_kt, tauP=self.tau_p, P=pressure, kT=kT) elif not pressure: try: integrator except NameError: integrator = hoomd.md.integrate.nvt(group=_all, tau=self.tau_kt, kT=kT) integrator.randomize_velocities(seed=self.seed) try: hoomd.run(n_steps) except hoomd.WalltimeLimitReached: pass finally: gsd_restart.write_restart()
def anneal( self, kT_init=None, kT_final=None, pressure=None, step_sequence=None, schedule=None, walls=True, shrink_kT=None, shrink_steps=None, shrink_period=None, ): if walls and pressure: raise ValueError( "Wall potentials can only be used with the NVT ensemble") if not schedule: temps = np.linspace(kT_init, kT_final, len(step_sequence)) temps = [np.round(t, 1) for t in temps] schedule = dict(zip(temps, step_sequence)) # Get hoomd stuff set: hoomd_args = f"--single-mpi --mode={self.mode}" sim = hoomd.context.initialize(hoomd_args) with sim: objs, refs = create_hoomd_simulation(self.system_pmd, self.ref_distance, self.ref_mass, self.ref_energy, self.r_cut, self.auto_scale, nlist=self.nlist) hoomd_system = objs[1] init_snap = objs[0] _all = hoomd.group.all() hoomd.md.integrate.mode_standard(dt=self.dt) hoomd.dump.gsd( "sim_traj.gsd", period=self.gsd_write, group=_all, phase=0, dynamic=["momentum"], overwrite=False, ) hoomd.analyze.log( "sim_traj.log", period=self.log_write, quantities=self.log_quantities, header_prefix="#", overwrite=True, phase=0, ) if shrink_kT and shrink_steps: integrator = hoomd.md.integrate.nvt(group=_all, tau=self.tau_kt, kT=shrink_kT) integrator.randomize_velocities(seed=self.seed) x_variant = hoomd.variant.linear_interp([ (0, self.reduced_init_L), (shrink_steps, self.target_box[0] * 10) ]) y_variant = hoomd.variant.linear_interp([ (0, self.reduced_init_L), (shrink_steps, self.target_box[1] * 10) ]) z_variant = hoomd.variant.linear_interp([ (0, self.reduced_init_L), (shrink_steps, self.target_box[2] * 10) ]) box_updater = hoomd.update.box_resize(Lx=x_variant, Ly=y_variant, Lz=z_variant, period=shrink_period) if walls: wall_origin = (init_snap.box.Lx / 2, 0, 0) normal_vector = (-1, 0, 0) wall_origin2 = (-init_snap.box.Lx / 2, 0, 0) normal_vector2 = (1, 0, 0) walls = wall.group( wall.plane(origin=wall_origin, normal=normal_vector, inside=True), wall.plane(origin=wall_origin2, normal=normal_vector2, inside=True)) wall_force = wall.lj(walls, r_cut=2.5) wall_force.force_coeff.set(init_snap.particles.types, sigma=1.0, epsilon=1.0, r_extrap=0) step = 0 while step < shrink_steps: hoomd.run_upto(step + shrink_period) current_box = hoomd_system.box walls.del_plane([0, 1]) walls.add_plane((current_box.Lx / 2, 0, 0), normal_vector) walls.add_plane((-current_box.Lx / 2, 0, 0), normal_vector2) step += shrink_period else: hoomd.run_upto(shrink_steps) box_updater.disable() gsd_restart = hoomd.dump.gsd("restart.gsd", period=self.gsd_write, group=_all, truncate=True, phase=0, dynamic=["momentum"]) if pressure: try: integrator.disable() except NameError: pass integrator = hoomd.md.integrate.npt(group=_all, tau=self.tau_kt, tauP=self.tau_p, P=pressure, kT=1) elif not pressure: try: integrator except NameError: integrator = hoomd.md.integrate.nvt(group=_all, tau=self.tau_kt, kT=1) for kT in schedule: n_steps = schedule[kT] integrator.set_params(kT=kT) integrator.randomize_velocities(seed=self.seed) print(f"Running @ Temp = {kT} kT") print(f"Running for {n_steps} steps") try: hoomd.run(n_steps) except hoomd.WalltimeLimitReached: pass finally: gsd_restart.write_restart()
sigma=LJsigma(sigma, sigmat), alpha=0.0) # interactions of the b particles lj.pair_coeff.set('b', 'b', epsilon=e_repulsion, sigma=LJsigma(sigma, sigma), alpha=0.0) lj.pair_coeff.set('b', 't', epsilon=e_repulsion, sigma=LJsigma(sigma, sigmat), alpha=0.0) # interactions of the t particles lj.pair_coeff.set('t', 't', epsilon=e_repulsion, sigma=LJsigma(sigmat, sigmat), alpha=0.0) # trajectory output all = hoomd.group.all() hoomd.dump.gsd(filename=run_gsd, period=gsd_freq, group=all, phase=0) # integrator setup and run hoomd.md.integrate.mode_standard(dt=dt) hoomd.md.integrate.langevin(group=all, kT=1.0, seed=integrate_seed) hoomd.run_upto(run_length)
def production( snapshot: Snapshot, context: hoomd.context.SimulationContext, sim_params: SimulationParams, dynamics: bool = True, simulation_type: str = "liquid", ) -> None: """Initialise and run a hoomd npt simulation for data collection. This is a utility function to run a simulation designed for the collection of data. This is particularly true when the `dynamics` argument is `True`, with a separate sequence of data points on an exponential sequence being collected. Args: snapshot: The configuration from which to start the production simulation context: Simulation context in which to run the simulation. sim_params: The parameters of the simulation which are to be set. dynamics: Whether to output an exponential series of configurations to make calculating dynamics properties easier. simulation_type: The type of simulation to run. Currently only `"liquid"` is supported. """ if sim_params.num_steps is None or sim_params.num_steps < 0: raise ValueError( "The number of steps has to be a positive number, found {sim_params.num_steps}" ) if sim_params.output_interval is None or sim_params.output_interval < 0: raise ValueError( "The number of steps between output configurations needs to be a positive integer," "found {sim_params.output_interval}") if not isinstance(context, hoomd.context.SimulationContext): raise ValueError( "The context needs to be a `hoomd.context.SimulationContext' instance", f"found {type(context)}", ) if simulation_type not in ["liquid"]: raise ValueError("Supported simulation types are (liquid)," "found {simulation_type}") sys = initialise_snapshot(snapshot, context, sim_params) with context: logger.debug("Run metadata: %s", sys.get_metadata()) group = get_group(sys, sim_params) set_integrator(sim_params, group, simulation_type="liquid") set_thermo( sim_params.filename(prefix="thermo"), thermo_period=sim_params.output_interval, rigid=sim_params.molecule.rigid, ) set_dump( group, sim_params.filename(prefix="dump"), dump_period=sim_params.output_interval, ) if dynamics: iterator = GenerateStepSeries( sim_params.num_steps, num_linear=sim_params.num_linear, max_gen=sim_params.max_gen, gen_steps=sim_params.gen_steps, ) # Zeroth step curr_step = iterator.next() assert curr_step == 0 dumpfile = dump_frame(group, sim_params.filename(prefix="trajectory")) for curr_step in iterator: hoomd.run_upto(curr_step, quiet=True) dumpfile.write_restart() else: hoomd.run(sim_params.num_steps) dump_frame(group, sim_params.filename())
def main(): parser = argparse.ArgumentParser( prog='rhaco-run-hoomd', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-T', '--temperature', type=float, default=633, required=False, help='''The desired temperature of the simulation in kelvin (this will be rescaled to produce a reduced temperature that conforms with Foyer's default units (kcal/mol and angstroems).\n''') parser.add_argument('-r', '--run_time', type=float, default=1E7, required=False, help='''The number of timesteps to run the MD simulation for.\n''') parser.add_argument('-s', '--timestep', type=float, default=1E-3, required=False, help='''The integration timestep to use when running the NVT MD simulation.\n''') parser.add_argument('-t', '--tau', type=float, default=1E-2, required=False, help='''The thermostat coupling to use when running the NVT MD simulation.\n''') parser.add_argument('-o', '--omit_lj', type=parse_interactions, default=[], required=False, help='''A list of lj interactions to omit from the rhaco-generated input hoomdxml (useful when using EAM).\n If unspecified, all interactions are considered''') parser.add_argument('-e', '--energy_scale_unit', type=float, default=1.0, required=False, help='''The energy scaling unit rhaco should use to set the correct temperature, and LJ epsilons in kcal/mol. Default is Foyer's default unit (1.0 kcal/mol). A useful alternative is 23.060541945329334 kcal/mol, which corresponds to 1 eV, which is the energy scaling unit for EAM. Be careful with this, it WILL frack everything up.''') parser.add_argument('-d', '--distance_scale_unit', type=float, default=1.0, required=False, help='''The distance scaling unit rhaco should use to set the correct LJ sigmas in angstroems. Default is Foyer's default unit (1.0 angstroem, same as EAM). Be careful with this, it WILL frack everything up.''') args, file_list = parser.parse_known_args() # Foyer gives parameters in terms of kcal/mol for energies and angstroems # for distances. Convert these to reduced units for HOOMD using the # following conversion, and print a string to inform the user it has been # done. reduced_temperature = args.temperature * BOLTZMANN * AVOGADRO / ( KCAL_TO_J * args.energy_scale_unit) timestep_SI = args.timestep * np.sqrt( AMU_TO_KG * (ANG_TO_M * args.distance_scale_unit)**2 * AVOGADRO / (KCAL_TO_J * args.energy_scale_unit)) print("Using the units of <DISTANCE> =", args.distance_scale_unit, "Angstroem," " <ENERGY> =", args.energy_scale_unit, "kcal/mol, and <MASS> = 1 amu," " the input temperature of", args.temperature, "K corresponds to" " {:.2E}".format(reduced_temperature), "in dimensionless HOOMD kT units, and the input timestep", args.timestep, "corresponds to {:.2E} s.".format(timestep_SI)) for file_name in file_list: hoomd.context.initialize("") # Get the integration groups by ignoring anything that has the X_ # prefix to the atom type, and rename the types for the forcefield system = hoomd.deprecated.init.read_xml(filename=file_name) snapshot = system.take_snapshot() renamed_snapshot, catalyst, gas = rename_types(snapshot) # Then, restore the snapshot system.restore_snapshot(renamed_snapshot) system, log_quantities = set_coeffs(file_name, system, args.omit_lj, args.distance_scale_unit, args.energy_scale_unit) hoomd.md.integrate.mode_standard(dt=args.timestep) integrator = hoomd.md.integrate.nvt(group=gas, tau=args.tau, kT=reduced_temperature) try: # Use HOOMD 2.3's randomize_velocities integrator.randomize_velocities(seed=42) except AttributeError: # Using a previous version of HOOMD - use the old initialization # function instead snapshot = system.take_snapshot() initialized_snapshot = initialize_velocities( snapshot, reduced_temperature, gas) system.restore_snapshot(initialized_snapshot) hoomd.dump.gsd(filename=".".join(file_name.split(".")[:-1]) + "_traj.gsd", period=max([int(args.run_time / 500), 1]), group=hoomd.group.all(), overwrite=True) hoomd.analyze.log(filename='.'.join(file_name.split('.')[:-1]) + ".log", quantities=log_quantities, period=max([int(args.run_time / 10000), 1]), header_prefix='#', overwrite=True) ## Now incrementally ramp the charges #for chargePhase in range(chargeIncrements + 1): # print("Incrementing charge phase", chargePhase, "of", # chargeIncrements + 1) # for atom in system.particles: # oldCharge = copy.deepcopy(atom.charge) # atom.charge = charges[atom.type] * (chargePhase / # float(chargeIncrements)) # hoomd.run(chargeTimesteps) # Get the initial box size dynamically hoomd.run_upto(args.run_time) hoomd.dump.gsd(filename=".".join(file_name.split(".")[:-1]) + "_final.gsd", period=None, group=hoomd.group.all(), overwrite=True)
def __call__(self, sim): with sim.context: hoomd.run_upto(self.step)
def run(self): if hoomd.context.exec_conf is None: hoomd_args = f"--single-mpi --mode={self.mode}" hoomd.context.initialize(hoomd_args) with hoomd.context.SimulationContext(): # TODO Robust restart logic when reading in rigid bodies if os.path.isfile("restart.gsd"): system = hoomd.init.read_gsd(filename=None, restart="restart.gsd") else: system = init_wrapper(self.input_xml) nl = hoomd.md.nlist.cell() logging.info("Setting coefs") hoomd.util.quiet_status() system = set_coeffs(self.input_xml, system, nl, self.e_factor) hoomd.util.unquiet_status() integrator_mode = hoomd.md.integrate.mode_standard(dt=self.dt) rigid = hoomd.group.rigid_center() nonrigid = hoomd.group.nonrigid() both_group = hoomd.group.union("both", rigid, nonrigid) all_particles = hoomd.group.all() integrator = hoomd.md.integrate.nvt( group=both_group, tau=self.tau, kT=self.shrink_kT_reduced ) hoomd.dump.gsd( filename="trajectory.gsd", period=self.gsd_write, group=all_particles, overwrite=False, phase=0, ) gsd_restart = hoomd.dump.gsd( "restart.gsd", period=self.gsd_write, group=all_particles, truncate=True, phase=0, ) log_quantities = [ "temperature", "pressure", "volume", "potential_energy", "kinetic_energy", "pair_lj_energy", "bond_harmonic_energy", "angle_harmonic_energy", ] hoomd.analyze.log( "trajectory.log", quantities=log_quantities, period=self.log_write, header_prefix="#", overwrite=False, phase=0, ) integrator.randomize_velocities(seed=42) if self.target_length is None: self.target_length = system.box.Lx size_variant = hoomd.variant.linear_interp( [(0, system.box.Lx), (self.shrink_time, self.target_length)], zero=0 ) box_resize = hoomd.update.box_resize(L=size_variant) hoomd.run_upto(self.shrink_time) box_resize.disable() # After shrinking, reset velocities and change temp integrator.set_params(kT=self.kT) integrator.randomize_velocities(seed=42) integrator_mode.set_params(dt=self.dt) try: hoomd.run_upto(self.n_steps + 1, limit_multiple=self.gsd_write) except hoomd.WalltimeLimitReached: pass finally: gsd_restart.write_restart() hoomd.deprecated.dump.xml( group=hoomd.group.all(), filename="final.xml", all=True )
with hoomd.context.SimulationContext(): hoomd.init.read_gsd(filename='init.gsd', restart='restart.gsd') print("tstep", hoomd.get_step()) lj = md.pair.lj(r_cut=sp['r_cut'], nlist=md.nlist.cell()) lj.pair_coeff.set('A', 'A', epsilon=sp['epsilon'], sigma=sp['sigma']) group = hoomd.group.all() md.integrate.mode_standard(dt=0.01) md.integrate.nvt(group, kT=sp['kT'], tau=sp['tau']) gsd_restart = hoomd.dump.gsd(filename='restart.gsd', group=group, truncate=True, period=100) hoomd.dump.gsd(filename='dump.gsd', group=group, truncate=False, period=100) hoomd.dump.dcd(filename='dump.dcd', group=group, period=100) with restart_pos('dump.pos'): hoomd.deprecated.dump.pos(filename='dump.pos', period=100) hoomd.run_upto(1000) gsd_restart.write_restart()
def run_steps(self, scope, storage, context): hoomd.run_upto(scope['cumulative_steps'])