示例#1
0
    def test_structure_to_hoomdsimulation(self, ethane):
        import hoomd
        from foyer.forcefield import Forcefield

        from mbuild.formats.hoomd_simulation import create_hoomd_simulation

        ff = Forcefield(name="oplsaa")
        structure = ff.apply(ethane)
        sim = hoomd.context.SimulationContext()
        with sim:
            create_hoomd_simulation(structure, 2.5)

            sim_forces = hoomd.context.current.forces
            pair_force = import_("hoomd.md.pair")
            charge_force = import_("hoomd.md.charge")
            special_pair_force = import_("hoomd.md.special_pair")
            bond_force = import_("hoomd.md.bond")
            angle_force = import_("hoomd.md.angle")
            dihedral_force = import_("hoomd.md.dihedral")

            assert isinstance(sim_forces[0], pair_force.lj)
            assert isinstance(sim_forces[1], charge_force.pppm)
            assert isinstance(sim_forces[2], pair_force.ewald)
            assert isinstance(sim_forces[3], special_pair_force.lj)
            assert isinstance(sim_forces[4], special_pair_force.coulomb)
            assert isinstance(sim_forces[5], bond_force.harmonic)
            assert isinstance(sim_forces[6], angle_force.harmonic)
            assert isinstance(sim_forces[7], dihedral_force.opls)
def simulate(parametrized_structure, **kwargs):
    """ Simulate in Hoomd 

    Parameters
    ----------
    parametrized_structure : parmed.Structure
    **kwargs : kwargs for run_hoomd_simulation
    
    """
    from mbuild.formats.hoomd_simulation import create_hoomd_simulation
    create_hoomd_simulation(parametrized_structure,
                            ref_distance=10,
                            ref_energy=1 / 4.184,
                            r_cut=1.4)
    run_hoomd_simulation(**kwargs)
示例#3
0
    def test_hoomdsimulation_restart(self):
        import gsd.hoomd
        import hoomd
        from foyer.forcefield import Forcefield

        from mbuild.formats.hoomd_simulation import create_hoomd_simulation

        box = mb.Compound()
        box.add(mb.Compound(name="Ar", pos=[1, 1, 1]))
        box.add(mb.Compound(name="Ar", pos=[1, 1, 1]))
        ff = Forcefield(forcefield_files=get_fn("lj.xml"))
        structure = ff.apply(box)
        structure.box = [10, 10, 10, 90, 90, 90]
        sim = hoomd.context.SimulationContext()
        with sim:
            hoomd_obj, ref_vals = create_hoomd_simulation(
                structure, 2.5, restart=get_fn("restart.gsd"))
            sim_forces = hoomd.context.current.forces
            pair_force = import_("hoomd.md.pair")

            assert isinstance(sim_forces[0], pair_force.lj)

        snap = hoomd_obj[0]
        with gsd.hoomd.open(get_fn("restart.gsd")) as f:
            rsnap = f[0]
        assert np.array_equal(snap.particles.position,
                              rsnap.particles.position)
示例#4
0
    def test_lj_to_hoomdsimulation(self):
        import hoomd
        from foyer.forcefield import Forcefield

        from mbuild.formats.hoomd_simulation import create_hoomd_simulation

        box = mb.Compound()
        box.add(mb.Compound(name="Ar", pos=[1, 1, 1]))
        box.add(mb.Compound(name="Ar", pos=[1, 1, 1]))
        ff = Forcefield(forcefield_files=get_fn("lj.xml"))
        structure = ff.apply(box)
        structure.box = [10, 10, 10, 90, 90, 90]
        sim = hoomd.context.SimulationContext()
        with sim:
            create_hoomd_simulation(structure, 2.5)
            sim_forces = hoomd.context.current.forces
            pair_force = import_("hoomd.md.pair")

            assert isinstance(sim_forces[0], pair_force.lj)
示例#5
0
def build_run_measure_hoomd(structure, **kwargs):
    """ Build and run a HOOMD simulation from a parmed.Structure """
    hoomd.util.quiet_status()
    hoomd.context.initialize("--msg-file=hoomd.out")
    create_hoomd_simulation(structure, **kwargs)

    all_group = hoomd.group.all()
    # Arbitrary small simulation
    hoomd.md.integrate.mode_standard(dt=0.0000001)
    hoomd.md.integrate.nve(all_group)
    hoomd.run(1)

    hoomd_force_groups = get_hoomd_force_groups()
    energies = {
        'hoomd': {
            key: get_hoomd_energy(key, hoomd_force_groups, all_group)
            for key in hoomd_force_groups
        }
    }
    df = pd.DataFrame.from_dict(energies, orient='index')

    return df
示例#6
0
    def run(self):
        """Run the simulation."""
        hoomd_args = f"--single-mpi --mode={self.mode}"
        sim = hoomd.context.initialize(hoomd_args)

        with sim:
            hoomd.util.quiet_status()
            # mbuild units are nm, amu
            hoomd_objects, ref_values = create_hoomd_simulation(
                self.system, auto_scale=True, restart=self.restart)
            self.ref_values = ref_values
            snap = hoomd_objects[0]
            hoomd.util.unquiet_status()

            if self.target_length is not None:
                self.target_length /= ref_values.distance

            if self.e_factor != 1:
                print("Scaling LJ coeffs by e_factor")
                hoomd.util.quiet_status()
                # catch all instances of LJ pair
                ljtypes = [
                    i for i in sim.forces if isinstance(i, hoomd.md.pair.lj)
                    or isinstance(i, hoomd.md.special_pair.lj)
                ]

                for lj in ljtypes:
                    pair_list = lj.get_metadata()["pair_coeff"].get_metadata()
                    for pair_dict in pair_list:
                        # Scale the epsilon values by e_factor
                        try:
                            a, b, new_dict = set_coeffs(
                                pair_dict, self.e_factor)
                            lj.pair_coeff.set(a, b, **new_dict)
                        except ValueError:
                            # if the pair has not been defined,
                            # it will not have a dictionary object
                            # instead it will be a string (e.g. "ca-ca")
                            # and will fail when trying to make the new_dict
                            pass
                hoomd.util.unquiet_status()

            integrator_mode = hoomd.md.integrate.mode_standard(dt=self.dt)
            all_particles = hoomd.group.all()
            try:
                integrator = hoomd.md.integrate.nvt(group=both,
                                                    tau=self.tau,
                                                    kT=self.shrink_kT_reduced)
            except NameError:
                # both does not exist
                integrator = hoomd.md.integrate.nvt(group=all_particles,
                                                    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,
                dynamic=["momentum"],
            )
            gsd_restart = hoomd.dump.gsd(
                "restart.gsd",
                period=self.gsd_write,
                group=all_particles,
                truncate=True,
                phase=0,
                dynamic=["momentum"],
            )
            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,
            )
            if self.restart is None:
                integrator.randomize_velocities(seed=42)

            if self.target_length is not None:
                # Run the shrink step
                final_length = self.target_length.to("Angstrom").value
                final_box = (self.shrink_steps, final_length)
                size_variant = hoomd.variant.linear_interp(
                    [(0, snap.box.Lx), final_box], zero=0)
                box_resize = hoomd.update.box_resize(L=size_variant)
                hoomd.run_upto(self.shrink_steps)
                box_resize.disable()
                self.n_steps += self.shrink_steps

            # 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:
                print("Walltime limit reached")
                pass
            finally:
                gsd_restart.write_restart()
                print("Restart file written")
示例#7
0
    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()
示例#8
0
    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()
示例#9
0
    def test_compound_to_hoomdsimulation(self, ethane):
        from mbuild.formats.hoomd_simulation import create_hoomd_simulation

        with pytest.raises(ValueError):
            create_hoomd_simulation(ethane, 2.5)
示例#10
0
    def test_bad_input_to_hoomdsimulation(self):
        from mbuild.formats.hoomd_simulation import create_hoomd_simulation

        with pytest.raises(ValueError):
            create_hoomd_simulation("fake_object", 2)
示例#11
0
                               n_compounds=2000,
                               box=mb.Box(lengths=[8, 8, 8]))

hoomd.context.initialize("")
box_arr = [8, 8, 8]
wrap_xyz = meth_box.xyz - 1 * np.floor_divide(meth_box.xyz, box_arr) * box_arr
meth_box.xyz = wrap_xyz
struc = meth_box.to_parmed()
meth_box.save('meth_box.hoomdxml', forcefield_name='trappe-ua', overwrite=True)
ff = foyer.Forcefield(name='trappe-ua')
param = ff.apply(struc)
#for atom in param.atoms:
#atom.charge = 0

from mbuild.formats.hoomd_simulation import create_hoomd_simulation
create_hoomd_simulation(param, ref_distance=10, ref_energy=1 / 4.184)
nl = hoomd.md.nlist.cell()
nl.reset_exclusions(['1-2', '1-3', '1-4'])

all = hoomd.group.all()

#fire = md.integrate.mode_minimize_fire(dt=0.002)
#nve = md.integrate.nve(group=all, limit = 0.01)
#while not fire.has_converged():
#    print([a.get_energy(all) for a in hoomd.context.current.forces])
#    hoomd.run(1000)
#nve.disable()

md.integrate.mode_standard(dt=0.002)
nvt = md.integrate.nvt(group=all, kT=2.286476462, tau=1)
hoomd.analyze.log(filename="analyze2.log",