def _test_potential(self, typ, twoD, **params): box = hoomd.data.boxdim(L=80, dimensions=(2 if twoD else 3)); snap = hoomd.data.make_snapshot(N=4, box=box); if hoomd.comm.get_rank() == 0: snap.particles.position[0] = (0, 0, 0); snap.particles.position[1] = (1, 0, 0); snap.particles.position[2] = (0, 2 + 2**(1./6), 0); snap.particles.position[3] = (1, 2 + 2**(1./6), 0); snap.particles.typeid[:] = [1, 0, 1, 0]; snap.particles.types = ['A', 'B']; system = hoomd.init.read_snapshot(snap); nl = hoomd.md.nlist.cell(); potential = typ(nlist=nl, **params); nve = hoomd.md.integrate.nve(group=hoomd.group.all()); mode = hoomd.md.integrate.mode_standard(dt=0); if twoD: vertices = [[0, 1], [0, -1]]; potential.setParams('A', vertices, center=False); else: vertices = [[0, 1, 0], [0, -1, 0]]; faces = [[0, 1]]; potential.setParams('A', vertices, faces, center=False); hoomd.run(1); for p in system.particles: self.assertAlmostEqual(p.net_energy, 0.5); potential.disable();
def test_convex_spheropolyhedron(self): self.system = hoomd.init.create_lattice(unitcell=hoomd.lattice.sc(10), n=(2, 1, 1)) self.addCleanup(hoomd.context.initialize, "--mode=cpu") hoomd.option.set_notice_level(0) self.addCleanup(self.del_system) self.mc = hoomd.hpmc.integrate.convex_spheropolyhedron(seed=10) self.addCleanup(self.del_mc) shape_vertices = np.array([[-2, -1, -1], [-2, -1, 1], [-2, 1, -1], [-2, 1, 1], [2, -1, -1], [2, -1, 1], [2, 1, -1], [2, 1, 1]]) shape_sweep_radius = 0.1 self.mc.shape_param.set("A", vertices=shape_vertices, sweep_radius=shape_sweep_radius) self.system.particles[0].position = (0, 0, 0) self.system.particles[0].orientation = (1, 0, 0, 0) self.system.particles[1].position = (2, 0, 0) self.system.particles[1].orientation = (1, 0, 0, 0) hoomd.context.current.sorter.set_params(grid=8) gsd_writer = hoomd.dump.gsd(filename=self.fn_gsd, group=hoomd.group.all(), period=1) gsd_writer.dump_state(self.mc) hoomd.run(1, quiet=True) with open(self.fn_gsd, 'rb') as gsdfile: gsd_reader = garnett.gsdhoomdfilereader.GSDHOOMDFileReader() traj = gsd_reader.read(gsdfile) shape = traj[0].shapedef['A'] assert shape.shape_class == 'spoly3d' assert np.array_equal(shape.vertices, shape_vertices) assert np.isclose(shape.rounding_radius, shape_sweep_radius)
def Minimize(snap): system.restore_snapshot(snap) fire.cpp_integrator.reset() while not(fire.has_converged()): hoomd.run(100) eIS=analyzer.query('potential_energy') return eIS
def series(warmup=100000, repeat=20, steps=10000, limit_hours=None): R""" Perform a series of benchmark runs. Args: warmup (int): Number of time steps to ```hoomd.run``` to warm up the benchmark repeat (int): Number of times to repeat the benchmark *steps*. steps (int): Number of time steps to ```hoomd.run``` at each benchmark point. limit_hours (float): Limit each individual ```hoomd.run``` length to this time. :py:meth:`series()` executes *warmup* time steps. After that, it calls ``run(steps)``, *repeat* times and returns a list containing the average TPS for each of those runs. """ # check if initialization has occurred if not hoomd.init.is_initialized(): raise RuntimeError("Cannot tune r_buff before initialization\n") tps_list = [] if warmup > 0: hoomd.run(warmup) for i in range(0, repeat): hoomd.run(steps, limit_hours=limit_hours) tps_list.append(hoomd.context.current.system.getLastTPS()) return tps_list
def test_period(self): def my_callback(timestep): self.test_index += 1 hoomd.analyze.callback(callback=my_callback, period=10) hoomd.run(100) self.assertEqual(self.test_index, 10)
def do_templating(kT=4.0, steps=1e4, cooling_steps=2e3, dump_period=2000): #Turn on the "templating" potential to form spheres in half-loop configuration #Initially I had used kT=1.0 and epsilon=-10, which worked fine. #But I found it much faster to increase to kT=4.0 and epsilon=-80 gsd_dump.set_period(dump_period) nl_gauss = hoomd.md.nlist.cell() gauss = hoomd.md.pair.gauss(r_cut=lattice_constant / 2, nlist=nl_gauss) gauss_width = lattice_constant / 4 gauss.pair_coeff.set('B', 'T', epsilon=-80.0, sigma=gauss_width, r_cut=0.6 * lattice_constant) gauss.pair_coeff.set(['A', 'T'], 'T', epsilon=0.0, sigma=2.0, r_cut=False) gauss.pair_coeff.set(['A', 'B'], ['A', 'B'], epsilon=0.0, sigma=2.0, r_cut=False) gauss.set_params(mode="xplor") integrator = hoomd.md.integrate.langevin(kT=kT, group=groupAB, seed=inp.se) hoomd.run(steps) #1e4 looks complete. #This may not be necessary, but this gives time for Temperature to equilibrate #before turning off the Gaussian templating potential integrator.set_params(kT=inp.kT) hoomd.run(cooling_steps) gauss.disable() integrator.disable()
def test_force_output(self): Ne = 5 c = hoomd.context.initialize() model_dir = build_examples.lj_force_output(Ne ** 2 - 1, self.tmp) with hoomd.htf.tfcompute(model_dir) as tfcompute: rcut = 3.0 system = hoomd.init.create_lattice( unitcell=hoomd.lattice.sq(a=2.0), n=[Ne, Ne]) c.sorter.disable() nlist = hoomd.md.nlist.cell(check_period=1) hoomd.md.integrate.mode_standard(dt=0.01) lj = hoomd.md.pair.lj(r_cut=rcut, nlist=nlist) lj.pair_coeff.set('A', 'A', epsilon=1.0, sigma=1.0) lj2 = hoomd.md.pair.lj(r_cut=rcut, nlist=nlist) lj2.pair_coeff.set('A', 'A', epsilon=4.0, sigma=0.8) hoomd.md.integrate.nve(group=hoomd.group.all( )).randomize_velocities(seed=1, kT=0.8) tfcompute.attach(nlist, r_cut=rcut, period=100, save_period=1) tfcompute.set_reference_forces(lj) hoomd.run(300) # now load checkpoint and check error variables = hoomd.htf.load_variables( model_dir, ['error']) assert abs(variables['error']) < 1e-5 # now check difference between particle forces and # forces from htf lj_forces = np.array([lj.forces[j].force for j in range(Ne**2)]) lj_energy = np.array([lj.forces[j].energy for j in range(Ne**2)]) np.testing.assert_allclose(tfcompute.get_forces_array( )[:, :3], lj_forces) np.testing.assert_allclose(tfcompute.get_forces_array( )[:, 3], lj_energy)
def test_out_of_bounds(self): slit = mpcd.integrate.slit(group=self.group, H=3.8) with self.assertRaises(RuntimeError): hoomd.run(1) slit.set_params(H=3.85) hoomd.run(1)
def test_step_moving_wall(self): md.integrate.mode_standard(dt=0.3) mpcd.integrate.slit(group=self.group, H=4., boundary="no_slip", V=1.0) # change velocity of lower particle so it is translating relative to wall snap = self.s.take_snapshot() if hoomd.comm.get_rank() == 0: snap.particles.velocity[1] = [-2., -1., -1.] self.s.restore_snapshot(snap) # run one step and check bounce back of particles hoomd.run(1) snap = self.s.take_snapshot() if hoomd.comm.get_rank() == 0: # the first particle is matched exactly to the wall speed, and so it will translate at # same velocity along +x. It will bounce back in y and z to where it started. # (vx stays the same, and vy and vz flip.) np.testing.assert_array_almost_equal(snap.particles.position[0], [-4.75, -4.95, 3.85]) np.testing.assert_array_almost_equal(snap.particles.velocity[0], [1., 1., -1.]) # the second particle has y and z velocities flip again, and since it started closer, # it moves relative to original position. np.testing.assert_array_almost_equal(snap.particles.position[1], [-0.4, -0.1, -3.9]) np.testing.assert_array_almost_equal(snap.particles.velocity[1], [0., 1., 1.])
def run_md(self): first_target_temperature = self.temp_prof.temperature_profile[0][1] self.set_initial_particle_velocities(first_target_temperature) hoomd.run(self.md_time) if self.profile_run: hoomd.run( int(self.md_time * 0.1), profile=True ) # run 10% of the simulation time to calculate performance if self.nl_tuning: print( '-----------------Disabling bonding and starting neighbourlist tuning-------------------' ) self.get_curing_percentage() if self.bond: if self.use_dybond_plugin: self.dybond_updater.disable() else: self.bond_callback.disable self.nl.tune(warmup=20000, r_min=0.01, r_max=2.00, jumps=10, steps=5000, set_max_check_period=False) deprecated.dump.xml(group=hoomd.group.all(), filename=os.path.join(self.output_dir, 'final.hoomdxml'), all=True)
def test_set_params(self): def callback(timestep): return numpy.random.rand(2, 3) with hoomd.hdf5.File(self.tmp_file, "a") as h5file: ana = hoomd.hdf5.log(h5file, quantities=['test1', 'test2', 'test3'], matrix_quantities=["mtest1", "mtest2"], period=10) ana.register_callback("mtest1", callback, matrix=True) ana.register_callback("mtest2", callback, matrix=True) #hdf5 logger does not support changing the number of logged quantities on the fly. # ana.set_params(quantities = ['test1']); # hoomd.run(100); # ana.set_params(quantities = ['test2', 'test3']) # hoomd.run(100); # ana.set_params(quantities = [u'test4', u'test5']) # hoomd.run(100); # ana.set_params(matrix_quantities = []) # hoomd.run(100); ana.set_params(matrix_quantities=["mtest1"]) hoomd.run(100) ana.set_params(matrix_quantities=["mtest1"]) hoomd.run(100)
def test_step(self): mpcd.integrator(dt=0.1) bulk = mpcd.stream.bulk(period=1) # run 1 step and check updated velocity k0 = 2. * np.pi / 10. f = mpcd.force.sine(F=2., k=k0) bulk.set_force(f) hoomd.run(1) snap = self.s.take_snapshot() if hoomd.context.current.device.comm.rank == 0: np.testing.assert_array_almost_equal(snap.particles.position[0], (1.1, -1.2, 0.2)) np.testing.assert_array_almost_equal( snap.particles.velocity[0], (1. + 0.5 * 0.1 * 2. * np.sin(k0 * 0.2), -2.0, 2.)) # remove force and stream freely bulk.remove_force() hoomd.run(1) snap = self.s.take_snapshot() if hoomd.context.current.device.comm.rank == 0: np.testing.assert_array_almost_equal( snap.particles.velocity[0], (1. + 0.5 * 0.1 * 2. * np.sin(k0 * 0.2), -2.0, 2.))
def series(warmup=100000, repeat=20, steps=10000, limit_hours=None): R""" Perform a series of benchmark runs. Args: warmup (int): Number of time steps to :py:meth:`hoomd.run()` to warm up the benchmark repeat (int): Number of times to repeat the benchmark *steps*. steps (int): Number of time steps to :py:meth:`hoomd.run()` at each benchmark point. limit_hours (float): Limit each individual :py:meth:`hoomd.run()` length to this time. :py:meth:`series()` executes *warmup* time steps. After that, it calls ``run(steps)``, *repeat* times and returns a list containing the average TPS for each of those runs. """ # check if initialization has occurred if not hoomd.init.is_initialized(): hoomd.context.msg.error("Cannot tune r_buff before initialization\n"); tps_list = []; if warmup > 0: hoomd.run(warmup); for i in range(0,repeat): hoomd.run(steps, limit_hours=limit_hours); tps_list.append(hoomd.context.current.system.getLastTPS()); return tps_list;
def test_simple(self): def cb(step): self.a = step; self.a = -1; hoomd.run(10, callback=cb); self.assertEqual(self.a, 10);
def test_access(self): model = build_examples.SimplePotential(32) tfcompute = htf.tfcompute(model) rcut = 3 # create a system with a few types cell = hoomd.lattice.unitcell( N=3, a1=[6, 0, 0], a2=[0, 6, 0], a3=[0, 0, 6], position=[[2, 2, 2], [1, 3, 1], [3, 1, 1]], type_name=['A', 'B', 'C']) system = hoomd.init.create_lattice(unitcell=cell, n=5) nlist = hoomd.md.nlist.cell(check_period=1) hoomd.md.integrate.mode_standard(dt=0.005) hoomd.md.integrate.nve(group=hoomd.group.all()) tfcompute.attach(nlist, r_cut=rcut) hoomd.run(1) tfcompute.get_virial_array() tfcompute.get_forces_array() pa = tfcompute.get_positions_array() nl = tfcompute.get_nlist_array() # make sure we get the 3 types self.assertEqual(len(np.unique(nl[:, :, 3].astype(np.int))), 3) self.assertEqual(len(np.unique(pa[:, 3].astype(np.int))), 3)
def test_force_output(self): Ne = 5 c = hoomd.context.initialize('') model = build_examples.LJModel(32, output_forces=False) model.compile(loss='MeanSquaredError') tfcompute = htf.tfcompute(model) rcut = 3.0 system = hoomd.init.create_lattice( unitcell=hoomd.lattice.sq(a=2.0), n=[Ne, Ne]) c.sorter.disable() nlist = hoomd.md.nlist.cell(check_period=1) hoomd.md.integrate.mode_standard(dt=0.01) lj = hoomd.md.pair.lj(r_cut=rcut, nlist=nlist) lj.pair_coeff.set('A', 'A', epsilon=1.0, sigma=1.0) lj2 = hoomd.md.pair.lj(r_cut=rcut, nlist=nlist) lj2.pair_coeff.set('A', 'A', epsilon=4.0, sigma=0.8) hoomd.md.integrate.nve(group=hoomd.group.all( )).randomize_velocities(seed=1, kT=0.8) tfcompute.attach(nlist, train=True, r_cut=rcut, period=100) tfcompute.set_reference_forces(lj) hoomd.run(300) error = model.metrics[0].result().numpy() assert abs(error) < 1e-5 # now check difference between particle forces and # forces from htf lj_forces = np.array([lj.forces[j].force for j in range(Ne**2)]) lj_energy = np.array([lj.forces[j].energy for j in range(Ne**2)]) np.testing.assert_allclose(tfcompute.get_forces_array( )[:, :3], lj_forces) np.testing.assert_allclose(tfcompute.get_forces_array( )[:, 3], lj_energy)
def test_lj_energy(self): model = build_examples.LJModel(32) tfcompute = htf.tfcompute(model) N = 3 * 3 NN = N - 1 T = 10 rcut = 5.0 system = hoomd.init.create_lattice( unitcell=hoomd.lattice.sq(a=4.0), n=[3, 3]) nlist = hoomd.md.nlist.cell(check_period=1) hoomd.md.integrate.mode_standard(dt=0.001) hoomd.md.integrate.nve(group=hoomd.group.all( )).randomize_velocities(seed=1, kT=0.8) log = hoomd.analyze.log(filename=None, quantities=['potential_energy', 'kinetic_energy'], period=1) tfcompute.attach(nlist, r_cut=rcut) energy = [] for i in range(T): hoomd.run(250) energy.append(log.query('potential_energy' ) + log.query('kinetic_energy')) if i > 1: np.testing.assert_allclose(energy[-1], energy[-2], atol=1e-3)
def test_force_matching(self): model_dir = build_examples.lj_force_matching(NN=15) # calculate lj forces with a leading coeff with hoomd.htf.tensorflowcompute.tfcompute(model_dir) as tfcompute: hoomd.context.initialize() N = 16 NN = N - 1 rcut = 7.5 system = hoomd.init.create_lattice( unitcell=hoomd.lattice.sq(a=4.0), n=[4, 4]) nlist = hoomd.md.nlist.cell(check_period=1) lj = hoomd.md.pair.lj(r_cut=rcut, nlist=nlist) lj.pair_coeff.set('A', 'A', epsilon=1.0, sigma=1.0) hoomd.md.integrate.mode_standard(dt=0.005) hoomd.md.integrate.nve( group=hoomd.group.all()).randomize_velocities(kT=2, seed=2) tfcompute.attach(nlist, r_cut=rcut, save_period=10) hoomd.run(1e2) input_nlist = tfcompute.get_nlist_array() variables = hoomd.htf.load_variables( model_dir, checkpoint=10, names=['loss', 'lj-epsilon', 'lj-sigma'], feed_dict=dict({'nlist-input:0': input_nlist})) new_variables = hoomd.htf.load_variables( model_dir, checkpoint=-1, names=['loss', 'lj-epsilon', 'lj-sigma'], feed_dict=dict({'nlist-input:0': input_nlist})) loss = variables['loss'] new_loss = new_variables['loss'] assert loss != new_loss assert new_variables['lj-epsilon'] != 0.9 assert new_variables['lj-sigma'] != 1.1
def test_with_file(self): if hoomd.context.current.device.comm.rank == 0: tmp = tempfile.mkstemp(suffix='.test.h5') self.tmp_file = tmp[1] else: self.tmp_file = "invalid" with hoomd.hdf5.File(self.tmp_file, "a") as h5file: log = hoomd.hdf5.log( h5file, quantities=['potential_energy', 'kinetic_energy'], period=10) hoomd.run(11) t0 = log.query('timestep') U0 = log.query('potential_energy') K0 = log.query('kinetic_energy') hoomd.run(2) t1 = log.query('timestep') U1 = log.query('potential_energy') K1 = log.query('kinetic_energy') self.assertEqual(int(t0), 10) self.assertNotEqual(K0, 0) self.assertNotEqual(U0, 0) self.assertEqual(int(t1), 10) self.assertEqual(U0, U1) self.assertEqual(K0, K1)
def test_period(self): def cb(step): self.a = step; self.a = -1; hoomd.run(10, callback=cb, callback_period=7); self.assertEqual(self.a, 7);
def test_with_file(self): if hoomd.comm.get_rank() == 0: tmp = tempfile.mkstemp(suffix='.test.h5'); self.tmp_file = tmp[1]; else: self.tmp_file = "invalid"; with hoomd.hdf5.File(self.tmp_file,"a") as h5file: log = hoomd.hdf5.log(h5file, quantities = ['potential_energy', 'kinetic_energy'], period = 10); hoomd.run(11); t0 = log.query('timestep'); U0 = log.query('potential_energy'); K0 = log.query('kinetic_energy'); hoomd.run(2); t1 = log.query('timestep'); U1 = log.query('potential_energy'); K1 = log.query('kinetic_energy'); self.assertEqual(int(t0), 10) self.assertNotEqual(K0, 0); self.assertNotEqual(U0, 0); self.assertEqual(int(t1), 10) self.assertEqual(U0, U1); self.assertEqual(K0, K1);
def test_nlist_compare(self): rcut = 5.0 c = hoomd.context.initialize() # disable sorting if c.sorter is not None: c.sorter.disable() # want to have a big enough system so that we actually have a cutoff system = hoomd.init.create_lattice(unitcell=hoomd.lattice.bcc(a=4.0), n=[4, 4, 4]) model_dir = build_examples.custom_nlist(16, rcut, system) with hoomd.htf.tfcompute(model_dir) as tfcompute: nlist = hoomd.md.nlist.cell() lj = hoomd.md.pair.lj(r_cut=rcut, nlist=nlist) lj.pair_coeff.set('A', 'A', epsilon=1.0, sigma=1.0) hoomd.md.integrate.mode_standard(dt=0.001) hoomd.md.integrate.nve( group=hoomd.group.all()).randomize_velocities(seed=1, kT=0.8) tfcompute.attach(nlist, r_cut=rcut, save_period=10, batch_size=None) # add lj so we can hopefully get particles mixing hoomd.run(100) variables = hoomd.htf.load_variables(model_dir, ['hoomd-r', 'htf-r']) # the two nlists need to be sorted to be compared nlist = variables['hoomd-r'] cnlist = variables['htf-r'] for i in range(nlist.shape[0]): ni = np.sort(nlist[i, :]) ci = np.sort(cnlist[i, :]) np.testing.assert_array_almost_equal(ni, ci, decimal=5)
def test_spheres_2d(self): self.system = hoomd.init.create_lattice( unitcell=hoomd.lattice.sq(a=10), n=2) self.addCleanup(hoomd.context.initialize, "--mode=cpu") hoomd.option.set_notice_level(0) self.addCleanup(self.del_system) self.mc = hoomd.hpmc.integrate.sphere(d=0.2, seed=10) self.addCleanup(self.del_mc) diameter_A = 0.75 self.mc.shape_param.set("A", diameter=diameter_A, orientable=True) self.system.particles[0].position = (0, 0, 0) self.system.particles[1].position = (2, 0, 0) hoomd.context.current.sorter.set_params(grid=8) gsd_writer = hoomd.dump.gsd(filename=self.fn_gsd, group=hoomd.group.all(), period=1) gsd_writer.dump_state(self.mc) hoomd.run(1, quiet=True) with open(self.fn_gsd, 'rb') as gsdfile: gsd_reader = garnett.gsdhoomdfilereader.GSDHOOMDFileReader() traj = gsd_reader.read(gsdfile) shape = traj[0].shapedef['A'] assert shape.shape_class == 'sphere' assert np.isclose(shape.diameter, diameter_A) self.assertEqual(shape.orientable, True) assert traj[-1].box.dimensions == 2 assert np.isclose(traj[-1].box.Lz, 1)
def test_compute_pairwise_potential(self): model_dir = build_examples.lj_rdf(9 - 1) with hoomd.htf.tfcompute(model_dir) as tfcompute: hoomd.context.initialize() rcut = 2.5 system = hoomd.init.create_lattice( unitcell=hoomd.lattice.sq(a=4.0), n=[3, 3]) nlist = hoomd.md.nlist.cell() lj = hoomd.md.pair.lj(r_cut=rcut, nlist=nlist) lj.pair_coeff.set('A', 'A', epsilon=1.0, sigma=1.0) hoomd.md.integrate.mode_standard(dt=0.001) hoomd.md.integrate.nve( group=hoomd.group.all()).randomize_velocities(seed=1, kT=0.8) tfcompute.attach(nlist, r_cut=rcut, save_period=10, batch_size=None) # add lj so we can hopefully get particles mixing hoomd.run(100) potentials = tfcompute.get_forces_array()[3] r = np.linspace(0.5, 1.5, 5) potential, *forces = htf.compute_pairwise_potential( model_dir, r, 'energy') np.testing.assert_equal(len(potential), len(r), 'Potentials not calculated correctly')
def test_embed(self): """Test momentum conservation for AT solvent + embedded particles.""" self.at.embed(hoomd.group.all()) # initial momentum of both should be zero slv = self.solvent.take_snapshot() slt = self.solute.take_snapshot() if hoomd.context.current.device.comm.rank == 0: slv_p0 = np.sum(slv.particles.velocity, axis=0) slt_p0 = self.density * np.sum(slt.particles.velocity, axis=0) np.testing.assert_allclose(slv_p0, [0, 0, 0], atol=1.e-6) np.testing.assert_allclose(slt_p0, [0, 0, 0], atol=1.e-6) hoomd.run(100) # each group should not have zero momentum, but total momentum should be zero slv = self.solvent.take_snapshot() slt = self.solute.take_snapshot() if hoomd.context.current.device.comm.rank == 0: slv_p1 = np.sum(slv.particles.velocity, axis=0) slt_p1 = self.density * np.sum(slt.particles.velocity, axis=0) self.assertFalse(np.allclose(slv_p1, [0, 0, 0])) self.assertFalse(np.allclose(slt_p1, [0, 0, 0])) np.testing.assert_allclose(slv_p1 + slt_p1, [0, 0, 0], atol=1.e-3)
def setup_system(self, cls, shape_params, expected_shapespec, filename, dim): if dim == 2: system = hoomd.init.create_lattice( unitcell=hoomd.lattice.sq(a=5.50), n=5) elif dim == 3: system = hoomd.init.create_lattice( unitcell=hoomd.lattice.sc(a=5.50), n=5) snapshot = system.take_snapshot(all=True) bindex = np.random.choice(range(5**dim), int(0.5 * 5**dim), replace=False) if hoomd.context.current.device.comm.rank == 0: snapshot.particles.types = ['A', 'B'] snapshot.particles.typeid[bindex] = 1 hoomd.context.initialize() system = hoomd.init.read_snapshot(snapshot) obj = cls(seed=123) obj.shape_param.set('A', **shape_params["A"]) obj.shape_param.set('B', **shape_params["B"]) dumper = dump.gsd(filename=filename, group=group.all(), period=1, overwrite=True) dumper.dump_shape(obj) steps = 5 hoomd.run(steps) reader = _hoomd.GSDReader(hoomd.context.current.device.cpp_exec_conf, filename, 0, False) if hoomd.context.current.device.comm.rank == 0: for i in range(steps): shape_spec = parse_shape_spec(reader.readTypeShapesPy(i)) self.assertEqual(shape_spec[0], expected_shapespec[0]) self.assertEqual(shape_spec[1], expected_shapespec[1])
def test_ellipsoid(self): self.system = hoomd.init.create_lattice(unitcell=hoomd.lattice.sc(10), n=(2, 1, 1)) self.addCleanup(hoomd.context.initialize, "--mode=cpu") hoomd.option.set_notice_level(0) self.addCleanup(self.del_system) self.mc = hoomd.hpmc.integrate.ellipsoid(seed=10) self.addCleanup(self.del_mc) a = 0.5 b = 0.25 c = 0.125 self.mc.shape_param.set("A", a=a, b=b, c=c) self.system.particles[0].position = (0, 0, 0) self.system.particles[1].position = (2, 0, 0) hoomd.context.current.sorter.set_params(grid=8) gsd_writer = hoomd.dump.gsd(filename=self.fn_gsd, group=hoomd.group.all(), period=1) gsd_writer.dump_state(self.mc) hoomd.run(1, quiet=True) with open(self.fn_gsd, 'rb') as gsdfile: gsd_reader = garnett.gsdhoomdfilereader.GSDHOOMDFileReader() traj = gsd_reader.read(gsdfile) shape = traj[0].shapedef['A'] assert shape.shape_class == 'ellipsoid' assert np.isclose(shape.a, a) assert np.isclose(shape.b, b) assert np.isclose(shape.c, c)
def setup_system(self, cls, shape_params, expected_shapespec, filename, dim): if dim == 2: system = hoomd.init.create_lattice( unitcell=hoomd.lattice.sq(a=5.50), n=5) elif dim == 3: system = hoomd.init.create_lattice( unitcell=hoomd.lattice.sc(a=5.50), n=5) snapshot = system.take_snapshot(all=True) bindex = np.random.choice(range(5**dim), int(0.5 * 5**dim), replace=False) if comm.get_rank() == 0: snapshot.particles.types = ['A', 'B'] snapshot.particles.typeid[bindex] = 1 hoomd.context.initialize() system = hoomd.init.read_snapshot(snapshot) md.integrate.mode_standard(dt=0.001) obj = cls(nlist=md.nlist.cell(), radius=.5) obj.setParams('A', **shape_params["A"]) obj.setParams('B', **shape_params["B"]) md.integrate.nvt(group=group.all(), kT=1.0, tau=0.5) dumper = dump.gsd(filename=filename, group=group.all(), period=1, overwrite=True) dumper.dump_shape(obj) steps = 5 hoomd.run(steps) reader = _hoomd.GSDReader(hoomd.context.exec_conf, filename, 0, False) if comm.get_rank() == 0: for i in range(steps): shape_spec = parse_shape_spec(reader.readTypeShapesPy(i)) self.assertEqual(shape_spec[0], expected_shapespec[0]) self.assertEqual(shape_spec[1], expected_shapespec[1])
def test_model_load(self): ''' Saves model after training and then uses if for inference ''' model = build_examples.TrainableGraph(16, output_forces=False) model.compile( optimizer=tf.keras.optimizers.Nadam(0.01), loss='MeanSquaredError') tfcompute = htf.tfcompute(model) rcut = 5.0 system = hoomd.init.create_lattice( unitcell=hoomd.lattice.sq(a=4.0), n=[3, 3]) nlist = hoomd.md.nlist.cell(check_period=1) hoomd.md.integrate.mode_standard(dt=0.005) hoomd.md.integrate.nve(group=hoomd.group.all( )).randomize_velocities(kT=2, seed=2) tfcompute.attach(nlist, train=True, r_cut=rcut) hoomd.run(5) model.save(os.path.join(self.tmp, 'test-model')) model = tf.keras.models.load_model( os.path.join(self.tmp, 'test-model')) infer_model = build_examples.TrainableGraph(16, output_forces=True) infer_model.set_weights(model.get_weights()) tfcompute.disable() tfcompute = htf.tfcompute(infer_model) tfcompute.attach(nlist, r_cut=rcut) hoomd.run(5)
def EvolveOneStep(verbose=True): with simT: hoomd.run(1) eT = PotEn(modeStandard, analyzerStandard, dt=dt) if verbose: print("t: ", t, "E(T) = ", eT, end='\t') snapT = systemT.take_snapshot(dtype='double') return snapT, eT
def Eee_from_gsd(fpath, table_path, width, height, step = 1): """ Return interaction energy along a trajectory in gsd file located at fpath; table - interaction pair force object """ import hoomd import hoomd.md hoomd.context.initialize('--mode=cpu') #hoomd = imp.reload(hoomd) system = hoomd.init.read_gsd(fpath, frame = 0) dt = 0.001 all = hoomd.group.all(); hoomd.md.integrate.mode_standard(dt=dt); langevin = hoomd.md.integrate.langevin(group=all, kT=0.1, seed=987); snapshot = system.take_snapshot(all=True) print(fpath) Eee = [] with gsd.fl.GSDFile(fpath, 'rb') as f_gsd: n_frames = f_gsd.nframes n_p = f_gsd.read_chunk(frame=0, name='particles/N') box = f_gsd.read_chunk(frame=0, name='configuration/box') table = hoomd.md.pair.table2D(width, height, 0.5*box[0], 0.5*box[1]) table.set_from_file(table_path) pos = np.zeros((n_frames, n_p[0])) pos_frame = f_gsd.read_chunk(frame=0, name='particles/position') for j_frame in range(0, n_frames, step): pos_frame = f_gsd.read_chunk(frame=j_frame, name='particles/position') snapshot.particles.position[:] = pos_frame[:] system.restore_snapshot(snapshot) hoomd.run(1, quiet=True) Eee.append(table.get_energy(hoomd.group.all())) return np.array(Eee)
def test_with_file(self): if hoomd.comm.get_rank() == 0: tmp = tempfile.mkstemp(suffix='.test.log') self.tmp_file = tmp[1] else: self.tmp_file = "invalid" log = hoomd.analyze.log( quantities=['potential_energy', 'kinetic_energy'], period=10, filename=self.tmp_file) hoomd.run(11) t0 = log.query('timestep') U0 = log.query('potential_energy') K0 = log.query('kinetic_energy') hoomd.run(2) t1 = log.query('timestep') U1 = log.query('potential_energy') K1 = log.query('kinetic_energy') self.assertEqual(int(t0), 10) self.assertNotEqual(K0, 0) self.assertNotEqual(U0, 0) self.assertEqual(int(t1), 10) self.assertEqual(U0, U1) self.assertEqual(K0, K1)
def _test_potential(self, typ, twoD, **params): box = hoomd.data.boxdim(L=80, dimensions=(2 if twoD else 3)) snap = hoomd.data.make_snapshot(N=4, box=box) if hoomd.context.current.device.comm.rank == 0: snap.particles.position[0] = (0, 0, 0) snap.particles.position[1] = (3.5, 0, 0) snap.particles.position[2] = (0, 5 + 2**(1. / 6), 0) snap.particles.position[3] = (3.5, 5 + 2**(1. / 6), 0) snap.particles.typeid[:] = [1, 0, 1, 0] snap.particles.types = ['A', 'B'] system = hoomd.init.read_snapshot(snap) nl = hoomd.md.nlist.cell() potential = typ(nlist=nl, **params) nve = hoomd.md.integrate.nve(group=hoomd.group.all()) mode = hoomd.md.integrate.mode_standard(dt=0) if twoD: vertices = [[2.5, 2.5], [-2.5, 2.5], [-2.5, -2.5], [2.5, -2.5]] potential.setParams('A', vertices, center=False) else: vertices = [[-2.5, 2.5, 2.5], [-2.5, -2.5, 2.5], [-2.5, -2.5, -2.5], [-2.5, 2.5, -2.5]] faces = [[0, 1, 2, 3]] potential.setParams('A', vertices, faces, center=False) hoomd.run(1) for p in system.particles: self.assertAlmostEqual(p.net_energy, 0.5) potential.disable()
def test_phase(self): def callback(timestep): return numpy.random.rand(2,3) with hoomd.hdf5.File(self.tmp_file, "a") as h5file: ana = hoomd.hdf5.log(h5file,quantities = ['test1', 'test2', 'test3'],matrix_quantities=["mtest1","mtest2"], period = 10,phase=0); ana.register_callback("mtest1",callback,matrix=True) ana.register_callback("mtest2",callback,matrix=True) hoomd.run(100);
def test_with_simulation_run(self): nl = md.nlist.cell() lj = md.pair.lj(r_cut=3.0, nlist=nl) lj.pair_coeff.set('A', 'A', epsilon=1.0, sigma=1.0) md.integrate.mode_standard(dt=0.01) md.integrate.nvt(group=hoomd.group.all(), kT=1.0, tau=1.0) hoomd.run(10) hoomd.meta.dump_metadata() hoomd.run(10) hoomd.meta.dump_metadata()
def test_cancel(self): def cb(step): self.a = step; if step == 3: return -1; else: return 0; self.a = -1; hoomd.run(10, callback=cb, callback_period=1); self.assertEqual(self.a, 3);
def test_y(self): constraint_vec = [0,1,0] oneD = hoomd.md.constrain.oneD(group=hoomd.group.type('A'), constraint_vector=constraint_vec) hoomd.md.force.constant(fx=1, fy=0, fz=0, group=hoomd.group.type('A')) hoomd.run(1e2) self.final = self.system.take_snapshot(particles=True) pos_diff = np.asarray(self.final.particles.position) - np.asarray(self.initial.particles.position) dots = np.dot(pos_diff,np.asarray(constraint_vec))/(np.linalg.norm(pos_diff,axis=1)*np.linalg.norm(np.asarray(constraint_vec))) tolerance = 1e-3 assert(np.abs(np.abs(dots).sum() - self.final.particles.N)<tolerance)
def test_phase(self): def my_callback(timestep): self.test_index += 1 def out_of_phase_cb(timestep): self.test_index_2 += 1 hoomd.analyze.callback(callback=my_callback, period=10, phase=10) hoomd.analyze.callback(callback=out_of_phase_cb, period = 10) hoomd.run(9) hoomd.run(89) self.assertEqual(self.test_index, 9) self.assertEqual(self.test_index_2, 10)
def test_set_params(self): ana = hoomd.analyze.log(quantities = ['test1', 'test2', 'test3'], period = 10, filename=self.tmp_file); ana.set_params(quantities = ['test1']); hoomd.run(100); ana.set_params(delimiter = ' '); hoomd.run(100); ana.set_params(quantities = ['test2', 'test3'], delimiter=',') hoomd.run(100); ana.set_params(quantities = [u'test4', u'test5'], delimiter=',') hoomd.run(100);
def _test_potential(self, typ, twoD, **params): box = hoomd.data.boxdim(L=80, dimensions=(2 if twoD else 3)); snap = hoomd.data.make_snapshot(N=4, box=box); dz = (0 if twoD else 2.5); if hoomd.comm.get_rank() == 0: snap.particles.position[0] = (0, 0, 0); snap.particles.position[1] = (6, 2.5, dz); snap.particles.position[2] = (0, 5 + 2**(1./6), 0); snap.particles.position[3] = (6, 2.5 + 5 + 2**(1./6), dz); system = hoomd.init.read_snapshot(snap); nl = hoomd.md.nlist.cell(); potential = typ(nlist=nl, **params); nve = hoomd.md.integrate.nve(group=hoomd.group.all()); mode = hoomd.md.integrate.mode_standard(dt=0); # there is cross-interaction between two of the particles the # way they are arranged, so the energies are not all the same if twoD: vertices = [[2.5, 2.5], [-2.5, 2.5], [-2.5, -2.5], [2.5, -2.5]]; potential.setParams('A', vertices, center=False); expected_energies = [1, 2, 2, 1]; else: # cube of edge length 5 vertices = list(itertools.product(*(3*[[-2.5,2.5]]))); faces = [[4, 0, 2, 6], [1, 0, 4, 5], [5, 4, 6, 7], [2, 0, 1, 3], [6, 2, 3, 7], [3, 1, 5, 7]]; potential.setParams('A', vertices, faces, center=False); expected_energies = [2, 4, 4, 2]; hoomd.run(1); for (p, U) in zip(system.particles, expected_energies): self.assertAlmostEqual(p.net_energy, U); potential.disable(); del potential; del system;
def test(self): log = hoomd.analyze.log(quantities = ['potential_energy', 'kinetic_energy'], period = 10, filename=None); hoomd.run(102); t0 = log.query('timestep'); U0 = log.query('potential_energy'); K0 = log.query('kinetic_energy'); hoomd.run(2); t1 = log.query('timestep'); U1 = log.query('potential_energy'); K1 = log.query('kinetic_energy'); self.assertEqual(int(t0), 102) self.assertNotEqual(K0, 0); self.assertNotEqual(U0, 0); self.assertEqual(int(t1), 104) self.assertNotEqual(U0, U1); self.assertNotEqual(K0, K1);
def test_gravity(self): """This test simulates a sedimentation experiment by using an elongated box in the z-dimension and adding an effective gravitational potential with a wall. Note that it is technically probabilistic in nature, but we use enough particles and a strong enough gravitational potential that the probability of particles rising in the simulation is vanishingly small.""" from hoomd import hpmc, jit import numpy as np # Just creating a simple cubic lattice # is fine here. system = hoomd.init.create_lattice(hoomd.lattice.sc( 1), n=5) mc = hpmc.integrate.sphere(80391, d=0.1, a=0.1) mc.overlap_checks.set('A', 'A', False) mc.shape_param.set('A', diameter=1) # Expand system, add walls, and add gravity hoomd.update.box_resize(Lx=system.box.Lx*1.5, Ly = system.box.Ly*1.5, Lz=system.box.Lz*20, scale_particles=False, period=None) wall = hpmc.field.wall(mc) wall.add_plane_wall([0, 0, 1], [0, 0, -system.box.Lz/2]) gravity_field = hoomd.jit.external.user(mc=mc, code="return 1000*(r_i.z + box.getL().z/2);") comp = hpmc.field.external_field_composite(mc, [wall, gravity_field]) snapshot = system.take_snapshot() if hoomd.comm.get_rank() == 0: old_avg_z = np.mean(snapshot.particles.position[:, 2]) log = hoomd.analyze.log(filename=None, quantities=['external_field_jit'], period=None); hoomd.run(1) original_energy = log.query('external_field_jit') hoomd.run(1e3) snapshot = system.take_snapshot() if hoomd.comm.get_rank() == 0: self.assertLess(np.mean(snapshot.particles.position[:, 2]), old_avg_z) if hoomd.comm.get_rank() == 0: self.assertLess(log.query('external_field_jit'), original_energy)
def run_test_1(self, name, dim): filename = "{}.gsd".format(name) mc_cls = hoomd.hpmc.integrate.__dict__[name] if dim == 3: self.system = init.read_snapshot(self.snapshot3d) else: self.system = init.read_snapshot(self.snapshot2d) self.mc = mc_cls(seed=2398) self.mc.shape_param.set('A', **self.params[name]['first']) self.gsd = hoomd.dump.gsd(filename, group=hoomd.group.all(), period=1, overwrite=True); self.gsd.dump_state(self.mc) hoomd.run(5); self.mc.shape_param.set('A', **self.params[name]['second']); self.mc.set_params(a=self.a, d=self.d); hoomd.run(5); self.gsd.disable(); self.gsd = None; with self.assertRaises(RuntimeError): self.mc.restore_state();
def test_set_params(self): def callback(timestep): return numpy.random.rand(2, 3) with hoomd.hdf5.File(self.tmp_file,"a") as h5file: ana = hoomd.hdf5.log(h5file,quantities = ['test1', 'test2', 'test3'], matrix_quantities=["mtest1","mtest2"], period = 10); ana.register_callback("mtest1", callback, matrix=True) ana.register_callback("mtest2", callback, matrix=True) #hdf5 logger does not support changing the number of logged quantities on the fly. # ana.set_params(quantities = ['test1']); # hoomd.run(100); # ana.set_params(quantities = ['test2', 'test3']) # hoomd.run(100); # ana.set_params(quantities = [u'test4', u'test5']) # hoomd.run(100); # ana.set_params(matrix_quantities = []) # hoomd.run(100); ana.set_params(matrix_quantities = ["mtest1"]) hoomd.run(100); ana.set_params(matrix_quantities = ["mtest1"]) hoomd.run(100);
def run_test(self, latticep, latticeq, k, kalt, q, qalt, uein, snapshot_s, eng_check, a = 0.0, d = 0.0): self.remove_drift = None; self.lattice = hpmc.field.lattice_field(self.mc, position = latticep, orientation=latticeq, k = k, q=q); eng = self.lattice.get_energy(); self.assertAlmostEqual(eng, 0.0); self.system.restore_snapshot(snapshot_s) hoomd.run(1, quiet=True); self.assertEqual(self.mc.count_overlaps(), 0); eng=self.lattice.get_energy(); avg=self.lattice.get_average_energy(); self.assertAlmostEqual(round(eng,3), eng_check); if uein: self.remove_drift = hpmc.update.remove_drift(self.mc, self.lattice, period=1000); self.lattice.set_params(k=kalt, q=qalt); self.mc.set_params(d=d, a=a); hoomd.run(5000, quiet=True); self.lattice.reset(); hoomd.run(5000, quiet=True); snap = self.system.take_snapshot(particles=True); eng=self.lattice.get_energy(); avg = self.lattice.get_average_energy(); sigma = self.lattice.get_sigma_energy(); if hoomd.comm.get_rank() == 0: diff = (np.array(latticep) - snap.particles.position[:]); box = self.system.box; for i in range(diff.shape[0]): diff[i] = box.min_image(diff[i]); diff = np.array(diff).flatten(); if len(latticeq) == len(latticep): diffq = (np.array(latticeq) - snap.particles.orientation[:]).flatten(); leng = kalt*diff.dot(diff) + qalt*diffq.dot(diffq); else: leng = kalt*diff.dot(diff); self.assertLess(abs(leng-eng)/eng, 0.001); # the difference is <0.1%. self.assertLess(abs(avg-uein), sigma);
'N' ], period=1000 ) # Set integration parameters md.integrate.mode_standard(dt=0.001) npt = md.integrate.npt( group=center, kT=2.0, tau=5, P=13.5, tauP=5 ) hoomd.run(10000) # Increase step size and decrease Nose-Hoover imaginary mass md.integrate.mode_standard(dt=0.005) npt.set_params(tau=1, tauP=1) # To monitor the Simulation in real time you need to output an xml file to read # into vmd as the initial configuration. # xml = deprecated.dump.xml(filename="out.xml", group=hoomd.group.all(), all=True) # xml.write("out.xml") # Send snapshots to VMD in real time using port 4321 sending snapshots # every 100 timesteps (approx 20 per second on artemis) # hoomd.analyze.imd( port=4321, period=200,) hoomd.run(100000)
def tune(self, start, stop, step, tsteps, quiet=False): """ Tune the sorting period. Args: start (int): Start of tuning interval to scan (inclusive). stop (int): End of tuning interval to scan (inclusive). step (int): Spacing between tuning points. tsteps (int): Number of timesteps to run at each tuning point. quiet (bool): Quiet the individual run calls. Returns: int: The optimal sorting period from the scanned range. The optimal sorting period for the MPCD particles is determined from a sequence of short runs. The sorting period is first set to *start*. The TPS value is determined for a run of length *tsteps*. This run is repeated 3 times, and the median TPS of the runs is saved. The sorting period is then incremented by *step*, and the process is repeated until *stop* is reached. The period giving the fastest TPS is determined, and the sorter period is updated to this value. The results of the scan are also reported as output, and the fastest sorting period is also returned. Note: A short warmup run is **required** before calling :py:meth:`tune()` in order to ensure the runtime autotuners have found optimal kernel launch parameters. Examples:: # warmup run hoomd.run(5000) # tune sorting period sorter.tune(start=5, stop=50, step=5, tsteps=1000) """ hoomd.util.print_status_line() # hide calls to set_period, etc. hoomd.util.quiet_status() # scan through range of sorting periods and log TPS periods = range(start, stop+1, step) tps = [] for p in periods: cur_tps = [] self.set_period(period=p) for i in range(0,3): hoomd.run(tsteps, quiet=quiet) cur_tps.append(hoomd.context.current.system.getLastTPS()) # save the median tps cur_tps.sort() tps.append(cur_tps[1]) # determine fastest period and set it on the sorter fastest = tps.index(max(tps)) opt_period = periods[fastest] self.set_period(period=opt_period) # tuning is done, restore status lines hoomd.util.unquiet_status() # output results hoomd.context.msg.notice(2, '--- sort.tune() statistics\n') hoomd.context.msg.notice(2, 'Optimal period = {0}\n'.format(opt_period)) hoomd.context.msg.notice(2, ' period = ' + str(periods) + '\n') hoomd.context.msg.notice(2, ' TPS = ' + str(tps) + '\n') return opt_period
def test_period(self): def my_callback(timestep): self.test_index += 1 hoomd.analyze.callback(callback=my_callback, period=10) hoomd.run(100); self.assertEqual(self.test_index, 10)
def run(self, num_comp_cycles=1): ## construct exponentially growing pressure variant # \param num_comp_steps number of steps in pressure variant # \param pmin minimum pressure # \param pmax maximum pressure # \returns P pressure variant for use in NPT updater def makePvariant(num_comp_steps, pmin, pmax): num_points = 101 # number of points defining the curve interval = num_comp_steps / num_points pressures=np.logspace(np.log10(pmin), np.log10(pmax), num_points) P = hoomd.variant.linear_interp(points = [(i*interval, prs) for i,prs in enumerate(pressures)]) return P num_comp_cycles = int(num_comp_cycles) dim = self.dim pmin = self.pmin pmax = self.pmax allowShearing = self.allowShearing num_comp_steps = self.num_comp_steps tot_pvol = self.tot_pvol (Lx, Ly, Lz, xy, xz, yz) = self.box_params relax = self.relax refine_steps = self.refine_steps quiet = self.quiet tuner_period = self.tuner_period log_file = self.log_file ptypes = self.ptypes pf_tol = self.pf_tol self.mclog.enable() # Since a logger will output on the current step and then every period steps, we need to take one step # to get the logger in sync with our for loop. hoomd.run(1, quiet=True) # # set up NPT npt_updater # Lscale = 0.001 Ascale = A3scale = 0.01 if (dim==2): A3scale=0.0 self.npt_updater.set_betap(pmin) self.npt_updater.length(delta=Lscale) if allowShearing: self.npt_updater.shear(delta=A3scale, reduce=0.6) #calculate initial packing fraction volume = Lx*Ly if dim==2 else Lx*Ly*Lz last_eta = tot_pvol / volume hoomd.context.msg.notice(5,'Starting eta = {}. '.format(last_eta)) hoomd.context.msg.notice(5,'Starting volume = {}. '.format(volume)) hoomd.context.msg.notice(5,'overlaps={}.\n'.format(self.mc.count_overlaps())) for i in range(num_comp_cycles): hoomd.context.msg.notice(5,'Compressor sweep {}. '.format(i)) # if not first sweep, relax the system if i != 0: # set box volume to original hoomd.update.box_resize(Lx = Lx, Ly = Ly, Lz = Lz, period=None) # reset tunables self.npt_updater.set_betap(pmin) self.npt_updater.length(delta=Lscale) if allowShearing: self.npt_updater.shear(delta=A3scale) self.mc.set_params(d=0.1, a=0.01) noverlaps = self.mc.count_overlaps() if noverlaps != 0: hoomd.util.quiet_status() hoomd.context.msg.warning("Tuner cannot run properly if overlaps exist in the system. Expanding box...\n") while noverlaps != 0: hoomd.context.msg.notice(5,"{} overlaps at step {}... ".format(noverlaps, hoomd.get_step())) Lx *= 1.0+Lscale Ly *= 1.0+Lscale Lz *= 1.0+Lscale hoomd.update.box_resize(Lx = Lx, Ly = Ly, Lz = Lz, period=None) noverlaps = self.mc.count_overlaps() hoomd.util.unquiet_status() #randomize the initial configuration #initial box, no shear pretuning_steps = relax hoomd.run(pretuning_steps, quiet=quiet) # update pressure variant P = makePvariant(num_comp_steps, pmin, pmax) self.npt_updater.set_betap(P) # determine number of iterations for tuner loops loop_length = 0 for tuner in self.tuners: loop_length += int(tuner_period) #num_iterations = (num_comp_steps) // loop_length num_iterations = (num_comp_steps - pretuning_steps) // loop_length # run short loops with tuners until pressure is maxed out for j in range(num_iterations): for tuner in self.tuners: hoomd.run(tuner_period, quiet=quiet) tuner.update() #calculate packing fraction for zeroth iteration hoomd.context.msg.notice(5,"Checking eta at step {0}. ".format(hoomd.get_step())) L = hoomd.context.current.system_definition.getParticleData().getGlobalBox().getL() volume = L.x * L.y if dim==2 else L.x*L.y*L.z eta = tot_pvol / volume hoomd.context.msg.notice(5,'eta = {}, '.format(eta)) hoomd.context.msg.notice(5,"volume: {0}\n".format(volume)) step = hoomd.get_step() last_step = step j = 0 max_eta_checks = 100 # If packing has not converged, iterate until it does. Run at least one iteration last_eta = 0.0 while (eta - last_eta) > pf_tol: hoomd.run(refine_steps, quiet=quiet) # check eta hoomd.context.msg.notice(5,"Checking eta at step {0}. ".format(hoomd.get_step())) #calculate the new packing fraction L = hoomd.context.current.system_definition.getParticleData().getGlobalBox().getL() volume = L.x * L.y if dim==2 else L.x*L.y*L.z last_eta = eta eta = tot_pvol / volume hoomd.context.msg.notice(5,"eta: {0}, ".format(eta)) hoomd.context.msg.notice(5,"volume: {0}\n".format(volume)) last_step = step step = hoomd.get_step() # Check if we've gone too far if j == max_eta_checks: hoomd.context.msg.notice(5,"Eta did not converge in {0} iterations. Continuing to next cycle anyway.\n".format(max_eta_checks)) j += 1 hoomd.context.msg.notice(5,"Step: {step}, Packing fraction: {eta}, ".format(step=last_step, eta=last_eta)) hoomd.context.msg.notice(5,'overlaps={}\n'.format(self.mc.count_overlaps())) self.eta_list.append(last_eta) #take a snapshot of the system snap = snapshot() self.mc.setup_pos_writer(snap) self.snap_list.append(snap) self.mclog.disable() return (self.eta_list,self.snap_list)
def test_phase(self): deprecated.analyze.msd(period = 10, filename=self.tmp_file, groups=[hoomd.group.all()], phase=0); hoomd.run(100);
def test_variable(self): deprecated.analyze.msd(period = lambda n: n*10, filename=self.tmp_file, groups=[hoomd.group.all()]); hoomd.run(100);
def test_set_params(self): ana = deprecated.analyze.msd(period = 10, filename=self.tmp_file, groups=[hoomd.group.all()]); ana.set_params(delimiter = ' '); hoomd.run(100);
import hoomd import hoomd.md # initialize hoomd.context.initialize() kT = float(hoomd.option.get_user()[0]) # specify potential nl = hoomd.md.nlist.cell() lj = hoomd.md.pair.lj(r_cut=2.5, nlist=nl) lj.pair_coeff.set('A', 'A', epsilon=1.0, sigma=1.0) # define integrator all = hoomd.group.all(); hoomd.md.integrate.mode_standard(dt=0.005) hoomd.md.integrate.langevin(group=all, kT=kT, seed=42) # write output hoomd.analyze.log(filename="log-output.log", quantities=['potential_energy'], period=100, overwrite=True) hoomd.dump.gsd("trajectory.gsd", period=2e3, group=all, overwrite=True) # run simulation hoomd.run(1e4)
def tune_cell_width(self, warmup=200000, min_width=None, max_width=None, jumps=20, steps=5000): R""" Make a series of short runs to determine the fastest performing bin width. Args: warmup (int): Number of time steps to run() to warm up the benchmark min_width (float): Minimum cell bin width to try max_width (float): Maximum cell bin width to try jumps (int): Number of different bin width to test steps (int): Number of time steps to run() at each point :py:class:`tune_cell_width()` executes *warmup* time steps. Then it sets the nlist *cell_width* value to *min_width* and runs for *steps* time steps. The TPS value is recorded, and the benchmark moves on to the next *cell_width* value completing at *max_width* in *jumps* jumps. Status information is printed out to the screen, and the optimal *cell_width* value is left set for further runs() to continue at optimal settings. Each benchmark is repeated 3 times and the median value chosen. In total, ``(warmup + 3*jump*steps)`` time steps are run. Returns: The optimal cell width. """ hoomd.util.print_status_line() # check if initialization has occurred if not hoomd.init.is_initialized(): hoomd.context.msg.error("Cannot tune r_buff before initialization\n"); if self.cpp_nlist is None: hoomd.context.msg.error('Bug in hoomd: cpp_nlist not set, please report\n') raise RuntimeError('Error tuning neighbor list') min_cell_width = min_width if min_cell_width is None: min_cell_width = 0.5*self.cpp_nlist.getMinRList() max_cell_width = max_width if max_cell_width is None: max_cell_width = self.cpp_nlist.getMaxRList() # quiet the tuner starting here so that the user doesn't see all of the parameter set and run calls hoomd.util.quiet_status(); # make the warmup run hoomd.run(warmup); # initialize scan variables dr = (max_cell_width - min_cell_width) / (jumps - 1); width_list = []; tps_list = []; # loop over all desired cell width points for i in range(0,jumps): # set the current cell width cw = min_cell_width + i * dr; hoomd.util.quiet_status(); self.set_cell_width(cell_width=cw) hoomd.util.unquiet_status(); # run the benchmark 3 times tps = []; hoomd.run(steps); tps.append(hoomd.context.current.system.getLastTPS()) hoomd.run(steps); tps.append(hoomd.context.current.system.getLastTPS()) hoomd.run(steps); tps.append(hoomd.context.current.system.getLastTPS()) # record the median tps of the 3 tps.sort(); tps_list.append(tps[1]); width_list.append(cw); # find the fastest cell width fastest = tps_list.index(max(tps_list)); fastest_width = width_list[fastest]; # set the fastest cell width self.set_cell_width(cell_width=fastest_width) # all done with the parameter sets and run calls (mostly) hoomd.util.unquiet_status(); # notify the user of the benchmark results hoomd.context.msg.notice(2, "cell width = " + str(width_list) + '\n'); hoomd.context.msg.notice(2, "tps = " + str(tps_list) + '\n'); hoomd.context.msg.notice(2, "Optimal cell width: " + str(fastest_width) + '\n'); # return the results to the script return fastest_width
def tune(self, warmup=200000, r_min=0.05, r_max=1.0, jumps=20, steps=5000, set_max_check_period=False, quiet=False): R""" Make a series of short runs to determine the fastest performing r_buff setting. Args: warmup (int): Number of time steps to run() to warm up the benchmark r_min (float): Smallest value of r_buff to test r_max (float): Largest value of r_buff to test jumps (int): Number of different r_buff values to test steps (int): Number of time steps to run() at each point set_max_check_period (bool): Set to True to enable automatic setting of the maximum nlist check_period quiet (bool): Quiet the individual run() calls. :py:meth:`tune()` executes *warmup* time steps. Then it sets the nlist *r_buff* value to *r_min* and runs for *steps* time steps. The TPS value is recorded, and the benchmark moves on to the next *r_buff* value completing at *r_max* in *jumps* jumps. Status information is printed out to the screen, and the optimal *r_buff* value is left set for further :py:func:`hoomd.run()` calls to continue at optimal settings. Each benchmark is repeated 3 times and the median value chosen. Then, *warmup* time steps are run again at the optimal *r_buff* in order to determine the maximum value of check_period. In total, ``(2*warmup + 3*jump*steps)`` time steps are run. Note: By default, the maximum check_period is **not** set for safety. If you wish to have it set when the call completes, call with the parameter *set_max_check_period=True*. Returns: (optimal_r_buff, maximum check_period) """ hoomd.util.print_status_line(); # check if initialization has occurred if not hoomd.init.is_initialized(): hoomd.context.msg.error("Cannot tune r_buff before initialization\n"); if self.cpp_nlist is None: hoomd.context.msg.error('Bug in hoomd: cpp_nlist not set, please report\n') raise RuntimeError('Error tuning neighbor list') # quiet the tuner starting here so that the user doesn't see all of the parameter set and run calls hoomd.util.quiet_status(); # start off at a check_period of 1 self.set_params(check_period=1) # make the warmup run hoomd.run(warmup, quiet=quiet); # initialize scan variables dr = (r_max - r_min) / (jumps - 1); r_buff_list = []; tps_list = []; # loop over all desired r_buff points for i in range(0,jumps): # set the current r_buff r_buff = r_min + i * dr; self.set_params(r_buff=r_buff); # run the benchmark 3 times tps = []; hoomd.run(steps, quiet=quiet); tps.append(hoomd.context.current.system.getLastTPS()) hoomd.run(steps, quiet=quiet); tps.append(hoomd.context.current.system.getLastTPS()) hoomd.run(steps, quiet=quiet); tps.append(hoomd.context.current.system.getLastTPS()) # record the median tps of the 3 tps.sort(); tps_list.append(tps[1]); r_buff_list.append(r_buff); # find the fastest r_buff fastest = tps_list.index(max(tps_list)); fastest_r_buff = r_buff_list[fastest]; # set the fastest and rerun the warmup steps to identify the max check period self.set_params(r_buff=fastest_r_buff); hoomd.run(warmup, quiet=quiet); # all done with the parameter sets and run calls (mostly) hoomd.util.unquiet_status(); # notify the user of the benchmark results hoomd.context.msg.notice(2, "r_buff = " + str(r_buff_list) + '\n'); hoomd.context.msg.notice(2, "tps = " + str(tps_list) + '\n'); hoomd.context.msg.notice(2, "Optimal r_buff: " + str(fastest_r_buff) + '\n'); hoomd.context.msg.notice(2, "Maximum check_period: " + str(self.query_update_period()) + '\n'); # set the found max check period if set_max_check_period: hoomd.util.quiet_status(); self.set_params(check_period=self.query_update_period()); hoomd.util.unquiet_status(); # return the results to the script return (fastest_r_buff, self.query_update_period());
def test(self): with hoomd.hdf5.File(self.tmp_file,"a") as h5file: hoomd.hdf5.log(h5file, quantities = ['test1', 'test2', 'test3'], period = 10); hoomd.run(100);
def test_phase(self): hoomd.analyze.log(quantities = ['test1', 'test2', 'test3'], period = 10, filename=self.tmp_file, phase=0); hoomd.run(100);
def test_variable(self): ana = hoomd.analyze.log(quantities = ['test1', 'test2', 'test3'], period = lambda n: n*10, filename=self.tmp_file); hoomd.run(100);