예제 #1
0
 def __init__(self, initfilepath, potfilepath, poscar):
     # self.lmp = lammps()
     self.initpath = initfilepath
     self.potentialpath = potfilepath
     self.poscar = poscar
     # self.scel = tokens[0]
     # self.id = tokens[1]
     self.pylmp = PyLammps()
     self.configurename = None
     # self.clex = clex
     self.labels_dict = {}
     self.num_types_cell = None
     self.atoms_num = {}
     self.total_atoms = 0
     self.atoms = None
     self.atom_types = None
     self.cart_coors = None
     self.lattice = None
     self.basis_vec = None
     self.basis_sites = None
     self.cos_alpha = None
     self.cos_beta = None
     self.cos_gamma = None
     self.xlo = None
     self.xhi = None
     self.ylo = None
     self.yhi = None
     self.zlo = None
     self.zhi = None
     self.xy = None
     self.yz = None
     self.xz = None
     self.properties = {}
     self.json_props = None
     self.relaxed_energy = None
예제 #2
0
    def setUp(self):
        machine = None
        if 'LAMMPS_MACHINE_NAME' in os.environ:
            machine = os.environ['LAMMPS_MACHINE_NAME']
        self.pylmp = PyLammps(
            name=machine,
            cmdargs=['-nocite', '-log', 'none', '-echo', 'screen'])
        self.pylmp.units("lj")
        self.pylmp.atom_style("atomic")
        self.pylmp.atom_modify("map array")

        if 'LAMMPS_CMAKE_CACHE' in os.environ:
            self.cmake_cache = {}

            with open(os.environ['LAMMPS_CMAKE_CACHE'], 'r') as f:
                for line in f:
                    line = line.strip()
                    if not line or line.startswith('#') or line.startswith(
                            '//'):
                        continue
                    parts = line.split('=')
                    key, value_type = parts[0].split(':')
                    if len(parts) > 1:
                        value = parts[1]
                        if value_type == "BOOL":
                            value = (value.upper() == "ON")
                    else:
                        value = None
                    self.cmake_cache[key] = value
예제 #3
0
    def test_default_settings(self):
        L = PyLammps()

        # verify default settings
        self.assertEqual(L.system.natoms, 0)
        self.assertEqual(L.system.ntypes, 0)
        self.assertEqual(L.system.style, 'none')
        self.assertEqual(L.system.units, 'lj')
        self.assertEqual(L.system.kspace_style, 'none')
        self.assertEqual(L.system.atom_style, 'atomic')
        self.assertEqual(L.system.atom_map, 'none')

        # now explicitly set them and check if nothing changed
        L.units('lj')
        L.boundary("p p p")
        L.lattice("none 1.0")
        L.atom_style("atomic")

        self.assertEqual(L.system.natoms, 0)
        self.assertEqual(L.system.ntypes, 0)
        self.assertEqual(L.system.style, 'none')
        self.assertEqual(L.system.units, 'lj')
        self.assertEqual(L.system.kspace_style, 'none')
        self.assertEqual(L.system.atom_style, 'atomic')
        self.assertEqual(L.system.atom_map, 'none')
예제 #4
0
 def setUp(self):
     self.L = PyLammps()
     self.L.units('real')           # default, use reduced units
     self.L.atom_style('atomic')  # default, point particles with mass and type
     self.L.boundary('p p p')     # default, periodic boundaries in 3-d
     self.L.processors('* * *')   # default, automatic domain decomposition
     self.L.newton('on')          # default, use newton's 3rd law for ghost particles
예제 #5
0
def objFuncLammps(obj):
    from lammps import PyLammps, lammps
    sim = lammps()
    PyLmps = PyLammps(ptr=sim)
    sim.command("atom_style atomic")
    sim.command("region box block -10 10 -10 10 -10 10")
    sim.command("boundary p p p")
    sim.command("create_box 1 box")
    sim.command("pair_style lj/cut 2.5")
    sim.command("pair_coeff * * 1.0 1.0 2.5")
    sim.command("mass 1 1.0")
    coords = obj.getfeature()
    for atom in coords:
        sim.command("create_atoms %s single %s %s %s" % (tuple(atom)))
#    sim.command("read_data %s"%( obj.getffFile() ) )
#    sim.command("minimize 0.0 1.0e-8 1000000 10000000")
    sim.command("run 0")
    #    print "run 0"
    #    PyLmps.run(1, "pre no post no")
    eng = PyLmps.eval("pe")
    #    val = exp(-eng/(1.987e-3*300))
    val = exp(-2 * eng)
    print(val, eng)
    #    sim.command("quit ")
    return val, eng
예제 #6
0
파일: lammps.py 프로젝트: alberlab/igm-dev
 def initLammps(self):
     """
     setup lammps python interface, log file
     """
     if self.cfg["optimization/kernel_opts/lammps/keep_logs"]:
         self.Lmp = PyLammps(cmdargs=["-log",os.path.join(self.tmp_dir, self.runid+".log")])
     else:
         self.Lmp = PyLammps(cmdargs=["-log","none"])
     self.Lmp.atom_style("bond")
     self.Lmp.boundary('s','s','s')
예제 #7
0
    def test_create_box(self):
        L = PyLammps()
        L.units('real')
        L.lattice('fcc', 3.5)
        L.region("a block", 0, 1, 0, 1, 0, 1)
        L.create_box(1, 'a')

        self.assertEqual(L.system.dimensions, 3)
        self.assertEqual(L.system.orthogonal_box, [3.5, 3.5, 3.5])
        self.assertEqual(L.system.boundaries, 'p,p p,p p,p')
        self.assertEqual(L.system.xlo, 0.0)
        self.assertEqual(L.system.ylo, 0.0)
        self.assertEqual(L.system.zlo, 0.0)
        self.assertEqual(L.system.xhi, 3.5)
        self.assertEqual(L.system.yhi, 3.5)
        self.assertEqual(L.system.zhi, 3.5)
예제 #8
0
 def __init__(
     self,
     cell: tuple,
 ):
     """
     Args:
         cell: (lattice, frac_coords, symbol)
     """
     self._lammps = PyLammps()
     self._initial_cell = cell
예제 #9
0
def requench(lmpcuts, minstyle="cg"):
    """[summary]

    [description]

    Parameters
    ----------
    lmpcuts : {[type]}
        [description]
    minstyle : {str}, optional
        [description] (the default is "cg", which [default_description])

    Returns
    -------
    [type]
        [description]
    """
    lmp = lammps()
    pylmp = PyLammps(ptr=lmp)
    lmp.command("log {} append".format(lmpcuts.output_lmplog))

    lmp.file(lmpcuts.settings_file)

    # change dielectric
    if lmpcuts.dielectric is not None:
        lmp.command("dielectric {}".format(lmpcuts.dielectric))

    # read restart file from previous run
    lmpcuts.load_system(lmp)
    lmpcuts.thermo(lmp)
    lmp.command("fix ic_prevention all momentum 100 linear 1 1 1 angular rescale")
    lmp.command("fix integrator all nvt temp {0} {1} 0.1".format(lmpcuts.tstart, lmpcuts.tstop))
    lmpcuts.dump(lmp, unwrap=True)

    if lmpcuts.pc_file is not None:
        lmp.file(lmpcuts.pc_file)

    lmp.command("reset_timestep 0")
    lmp.command("run {}".format(lmpcuts.runsteps))
    lmpcuts.minimize(lmp, style=minstyle)
    lmpcuts.unfix_undump(pylmp, lmp)
    lmp.command("write_restart {}".format(lmpcuts.output_lmprst))
    lmp.command("clear")
    lmp.close()

    # check if aggregate is intact after requenching
    md_sys = aglmp.read_lmpdat(lmpcuts.input_lmpdat, lmpcuts.output_dcd)
    aggregate_ok = md_sys.check_aggregate(frame_id=-1)
    return aggregate_ok
예제 #10
0
    def test_read_restart(self):
        L = self.L
        pe = L.eval("pe")

        L.write_restart('/tmp/test_read_restart.restart')
        del L

        L2 = PyLammps()
        L2.read_restart('/tmp/test_read_restart.restart')
        L2.run(0)
        os.remove('/tmp/test_read_restart.restart')

        self.assertEqual(L2.system.natoms, 2)
        self.assertEqual(L2.atoms[0].position, (-1.0, 0.0, 0.0))
        self.assertEqual(L2.atoms[1].position,  (1.0, 0.0, 0.0))
        self.assertEqual(L2.eval("pe"), pe)
예제 #11
0
def nose_hoover_md(lmpcuts, group="all"):
    """
    """
    lmp = lammps()
    pylmp = PyLammps(ptr=lmp)
    lmp.command("log {} append".format(lmpcuts.output_lmplog))

    if lmpcuts.gpu is True:
        lmpcuts.use_gpu(lmp, neigh=False)

    lmp.file(lmpcuts.settings_file)

    # change dielectric
    if lmpcuts.dielectric is not None:
        lmp.command("dielectric {}".format(lmpcuts.dielectric))

    lmpcuts.load_system(lmp)
    lmpcuts.thermo(lmp)
    lmp.command("fix ic_prevention all momentum 100 linear 1 1 1 angular rescale")
    lmpcuts.dump(lmp, unwrap=True)

    if lmpcuts.pc_file is not None:
        lmp.file(lmpcuts.pc_file)

    # minimize cut box if not done already
    if lmpcuts.input_lmprst is None or os.path.isfile(lmpcuts.input_lmprst):
        lmpcuts.minimize(lmp, style="cg")

    lmp.command("reset_timestep 0")

    try:
        lmp.command("run {}".format(lmpcuts.runsteps))
    except:
        # prevent deadlock by not nicely ending the whole program if more
        # than one rank is used
        if size > 1:
            MPI.COMM_WORLD.Abort()

    lmpcuts.unfix_undump(pylmp, lmp)
    #lmp.command("reset_timestep 0")
    lmp.command("write_restart {}".format(lmpcuts.output_lmprst))
    lmp.command("clear")
    lmp.close()
예제 #12
0
#!/usr/bin/env python

#from mpi4py import MPI
from lammps import lammps, PyLammps

# FOR FURTHER READING:
#       http://lammps.sandia.gov/doc/tutorial_pylammps.html#pylammps-tutorial

lmp = lammps()
L = PyLammps(ptr=lmp)

# process one line at a time
with open("OUT.in", "r") as f_in:
    for line in f_in:
        lmp.command(line)

#lmp.file("OUT.in")
#me = MPI.COMM_WORLD.Get_rank()
#nprocs = MPI.COMM_WORLD.Get_size()
#print "Proc %d out of %d procs has" % (me,nprocs),lmp
#MPI.Finalize()  # shutdown mpi properly
예제 #13
0
def _anneal(lmpcuts, pe_atm_idxs, ensemble, group="all", keyword="iso"):
    """Helper function for the annealing step of the kawska-zahn approach.

    This function calls lammps to execute the simulation for the annealing
    part of the kawska-zahn approach.

    Parameters
    ----------
    lmpcuts : {[type]}
        [description]
    pe_atm_idxs : {list of int}
        List of atom indices for the solvate atoms. Needed to compute the potential
        energy of the solvate atoms only.
    ensemble : {[type]}
        [description]
    group : {str}, optional
        [description] (the default is "all", which [default_description])
    keyword : {str}, optional
        [description] (the default is "iso", which [default_description])
    """
    lmp = lammps()
    pylmp = PyLammps(ptr=lmp)
    lmp.command("log {} append".format(lmpcuts.output_lmplog))

    # caveat: only possible with neigh no if calculating pe/atom on the graphics card
    if lmpcuts.gpu is True:
        lmpcuts.use_gpu(lmp, neigh=False)

    lmp.file(lmpcuts.settings_file)

    # change dielectric
    if lmpcuts.dielectric is not None:
        lmp.command("dielectric {}".format(lmpcuts.dielectric))

    lmpcuts.load_system(lmp)

    lmp.command("fix ic_prevention all momentum 100 linear 1 1 1 angular rescale")
    lmpcuts.dump(lmp, unwrap=True)

    if lmpcuts.pc_file is not None:
        lmp.file(lmpcuts.pc_file)

    # distribute the available cores if we have lots of vacuum in our box
    lmp.command("comm_style tiled")
    lmp.command("balance 1.0 rcb")

    # compute potential energy of the solvate (pair, bond, ...)
    # in order to compute the pe of the solvent, the solvent atom-ids must be
    # known
    pe_atm_ids = [i + 1 for i in pe_atm_idxs]
    atm_ids_str = " ".join(map(str, pe_atm_ids))
    lmp.command("group resname_atoms id {}".format(atm_ids_str))
    lmp.command("compute pe_per_atom_solvate resname_atoms pe/atom")
    lmp.command("compute pe_solvate_complete resname_atoms reduce sum c_pe_per_atom_solvate")

    if "c_pe_solvate_complete" not in lmpcuts.thermargs:
        lmpcuts.thermargs.append("c_pe_solvate_complete")

    lmpcuts.thermo(lmp, hb_group="resname_atoms")
    lmpcuts.fix_hoover(lmp, group, ensemble, keyword)

    # reset the timestep in order to have a consistent number of steps in the
    # log- and dcd-file (steps may differ after e.g. a minimization)
    lmp.command("reset_timestep 0")

    lmp.command("run {}".format(lmpcuts.runsteps))
    lmpcuts.unfix_undump(pylmp, lmp)
    # not sure if resetting the timestep is necessary
    #

    # write restart file only if equilibrated (so definitely not here!)
    lmp.command("write_restart {}".format(lmpcuts.inter_lmprst))
    lmp.command("clear")
    lmp.close()
예제 #14
0
    def test_morse_potential(self):
        L = PyLammps()
        L.file(IncludeTests.ATOMS_SETUP_FILE)

        # set different non-bonded potential
        L.pair_style('morse', 5.0)
        L.pair_coeff(1, 1, 1.0, 5.0, 1.12)

        L.velocity('all create', 1.0, 54321, 'mom no rot no')

        # import time integration setting from include file
        L.file(IncludeTests.VERLET_CONFIG_FILE)

        L.thermo(10)         # thermo output every 10 steps

        L.run(100)
예제 #15
0
def create_voids(lmpcuts, lmpdat_solvate, dcd_solvate=None, dcd_solvent=None):
    """
    """
    # solvate with molecule radii and cogs
    solvate_sys = aglmp.read_lmpdat(lmpdat_solvate, dcd_solvate, frame_idx_start=-2, frame_idx_stop=-1)
    radii_mol, cogs_mol = _molecules_radii(solvate_sys)
    indent_strs = _fix_indent_ids(radii_mol, cogs_mol, "molecule", scale_start=10, scale_stop=15)

    # load solution system (last frame only)
    solvent_sys = aglmp.read_lmpdat(lmpcuts.input_lmpdat, dcd_solvent, frame_idx_start=-2, frame_idx_stop=-1)
    solution_sys = mdu.merge_systems([solvate_sys, solvent_sys])
    solution_sys.reset_cells()

    # check solvate atoms with too close contacts to solvent atoms
    close_atoms = _check_clashes(solution_sys, solvate_sys, solvent_sys)
    cogs_atoms = [solvate_sys.ts_coords[-1][i] for i in close_atoms]
    radii_atoms = [mde.elements_mass_radii[round(solvate_sys.atm_types[solvate_sys.atoms[i].atm_key].weigh, 1)] for i in close_atoms]

    # gather close atoms and remember which were close
    all_close_atoms = []
    all_radii_atoms = []
    all_cogs_atoms = []

    all_close_atoms.extend(close_atoms)
    all_radii_atoms.extend(radii_atoms)
    all_cogs_atoms.extend(cogs_atoms)

    # load lammps and lammps settings
    lmp = lammps()
    pylmp = PyLammps(ptr=lmp)
    lmp.command("log {}".format(lmpcuts.output_lmplog))

    if lmpcuts.gpu is True:
        lmpcuts.use_gpu(lmp)

    lmp.file(lmpcuts.settings_file)

    # change dielectric
    if lmpcuts.dielectric is not None:
        lmp.command("dielectric {}".format(lmpcuts.dielectric))

    lmpcuts.load_system(lmp)
    lmpcuts.thermo(lmp)
    lmp.command("fix ic_prevention all momentum 100 linear 1 1 1 angular rescale")
    lmpcuts.dump(lmp, unwrap=True)

    if lmpcuts.pc_file is not None:
        lmp.file(lmpcuts.pc_file)

    #lmpcuts.fix_berendsen(lmp, group="all", ensemble="nve", keyword="iso")
    lmpcuts.fix_berendsen(lmp, group="all", ensemble="npt", keyword="iso", integrator="nve/limit 0.2")
    #lmp.command("unfix integrator")
    #lmp.command("fix limit_movement all nve/limit 0.05")
    _lmp_indent(lmp, indent_strs, lmpcuts.runsteps, keep_last_fixes=True)

    factor_start = 10
    factor_stop = factor_start + 1

    if close_atoms != []:
        # move solvent molecules away from close solvate atoms
        for _ in range(5):
            indent_strs = _fix_indent_ids(all_radii_atoms, all_cogs_atoms, "atom", scale_start=factor_start, scale_stop=factor_stop)
            _lmp_indent(lmp, indent_strs, lmpcuts.runsteps, keep_last_fixes=False)
            close_atoms = _check_clashes(solution_sys, solvate_sys, solvent_sys, lmpcuts.output_dcd)

            # add new close atoms to present ones or stop indenting
            if close_atoms == []:
                break

            # add further close atoms to present ones
            for atm_idx in close_atoms:
                #print(close_atoms)
                if atm_idx not in all_close_atoms:
                    all_close_atoms.append(atm_idx)
                    all_radii_atoms.append(mde.elements_mass_radii[round(solvate_sys.atm_types[solvate_sys.atoms[i].atm_key].weigh, 1)])
                    all_cogs_atoms.append(solvate_sys.ts_coords[-1][atm_idx])

            # dynamically grow sphere around atoms
            factor_start += 1
            factor_stop = factor_start + 1

    lmpcuts.unfix_undump(pylmp, lmp)
    lmp.command("write_restart {}".format(lmpcuts.output_lmprst))
    lmp.command("clear")
    lmp.close()

    return close_atoms == []
예제 #16
0
def quench(lmpcuts, lmpdat_main, runs=20, split=None):
    """
    """
    # check how many cores are used, leave the list empty if it is only one
    try:
        other_ranks = list(range(lmpcuts.ncores))[1:]
    except ValueError:
        other_ranks = []

    def _check_success():
        """
        Check aggregation state and close lammps instance properly.
        """
        if rank == 0:
            quench_sys = aglmp.read_lmpdat(lmpcuts.input_lmpdat, dcd=lmpcuts.output_dcd)
            succeeded = quench_sys.check_aggregate()

            # send data to the other ranks
            for other_rank in other_ranks:
                comm.send(succeeded, dest=other_rank)

        else:
            succeeded = comm.recv(source=0)

        #print(succeeded)
        #succeeded = comm.bcast(succeeded, 0)

        # stop trying if it was
        if succeeded is True:
            # write restart file
            lmpcuts.unfix_undump(pylmp, lmp)
            lmp.command("reset_timestep 0")
            lmp.command("write_restart {}".format(lmpcuts.output_lmprst))
            lmp.command("clear")
            lmp.close()

        return succeeded

    def _run(steps):
        """
        Helper function for running and catching an exception when anything
        goes wrong.
        """
        try:
            lmp.command("run {}".format(steps))
        except:
            # prevent deadlock by not nicely ending the whole program if more
            # than one rank is used
            if size > 1:
                MPI.COMM_WORLD.Abort()

    natoms_main_sys = get_natms(lmpdat_main)

    lmp = lammps(comm=split)
    pylmp = PyLammps(ptr=lmp)
    lmp.command("log {} append".format(lmpcuts.output_lmplog))

    if lmpcuts.gpu is True:
        lmpcuts.use_gpu(lmp, neigh=False)

    lmp.file(lmpcuts.settings_file)

    # change dielectric
    if lmpcuts.dielectric is not None:
        lmp.command("dielectric {}".format(lmpcuts.dielectric))

    lmpcuts.load_system(lmp)

    #lmp.command("velocity all create {} {} mom yes rot yes dist gaussian".format(lmpcuts.tstart, np.random.randint(29847587)))
    lmp.command("fix ic_prevention all momentum 100 linear 1 1 1 angular rescale")
    lmpcuts.dump(lmp, unwrap=True)
    lmpcuts.thermo(lmp)

    if lmpcuts.pc_file is not None:
        lmp.file(lmpcuts.pc_file)

    # distribute the available cores if we have lots of vacuum in our box
    lmp.command("comm_style tiled")
    lmp.command("balance 1.0 rcb")

    # define the atoms that may move during the simulation
    lmp.command("group grp_add_sys id > {}".format(natoms_main_sys))
    #lmp.command("group grp_main_sys id <= {}".format(natoms_main_sys))
    #lmp.command("fix freeze grp_main_sys setforce {0} {0} {0}".format(0.0))

    # pre-optimization
    lmp.command("min_style cg")
    lmp.command("min_modify dmax 0.5")
    lmp.command("minimize 1.0e-5 1.0e-8 10000 100000")

    # set an additional push to the added atoms that should be docked
    # towards the origin at (0/0/0)
    # (prevents losing atoms due to being localized outside the cutoff)
    if rank == 0:
        prep_sys = aglmp.read_lmpdat(lmpcuts.input_lmpdat)
        cog = agm.get_cog(prep_sys.ts_coords[-1][natoms_main_sys + 1:])
        cog /= np.linalg.norm(cog, axis=0)  # unit vector
        # make vector show towards the center (0/0/0)
        cog_force = cog * -1

        for other_rank in other_ranks:
            comm.send(cog_force, dest=other_rank)

    else:
        cog_force = comm.recv(source=0)

    #cog_force = comm.bcast(cog_force, 0)
    # barostatting, thermostatting only for atoms that will be docked
    lmp.command("fix integrator grp_add_sys nvt temp {0} {1} 0.1".format(lmpcuts.tstart, lmpcuts.tstop))
    quench_success = False

    # runs attempts to dock the molecule
    for _ in range(runs):
        # minimize and check if that is enough for docking
        lmp.command("min_style quickmin")
        lmp.command("minimize 1.0e-5 1.0e-8 10000 100000")

        lmp.command("min_style cg")
        lmp.command("minimize 1.0e-5 1.0e-8 10000 100000")

        # check aggregate, i.e. docking was a success
        quench_success = _check_success()

        if quench_success is True:
            break

        del quench_success
        # perform a little molecular dynamics simulation with
        # half of the lmpcuts.runsteps
        _run(int(lmpcuts.runsteps))

        # check aggregate, i.e. docking was a success
        quench_success = _check_success()

        if quench_success is True:
            break

        del quench_success
        # give 'to-be-docked' molecules a little push if minimization was not
        # sufficient for aggregation
        addforce_cmd = "fix push grp_add_sys addforce {c[0]} {c[1]} {c[2]} every 1"
        addforce_cmd = addforce_cmd.format(c=cog_force)
        lmp.command(addforce_cmd)
        #import time
        #time.sleep(30)

        # set force does not work
        #lmp.command("fix push grp_add_sys setforce {0} {0} {0}".format(*cog))
        _run(1)

        # remove pushing force
        lmp.command("unfix push")

        # run the 2nd half of the simulation with push 'grp_add_sys'
        _run(int(lmpcuts.runsteps * 0.5))

        # stop to-be-docked molecules from moving
        #lmp.command("velocity grp_add_sys set 0.0 0.0 0.0")
        #lmp.command("fix freeze grp_add_sys setforce {0} {0} {0}".format(0.0))

        _run(int(lmpcuts.runsteps * 0.25))

    return quench_success
예제 #17
0
 def test_change_system(self):
     L = PyLammps()
     L.units('real')
     L.atom_style('charge')
     self.assertEqual(L.system.units, 'real')
     self.assertEqual(L.system.atom_style, 'charge')
예제 #18
0
class PythonPyLammps(unittest.TestCase):
    def setUp(self):
        machine = None
        if 'LAMMPS_MACHINE_NAME' in os.environ:
            machine = os.environ['LAMMPS_MACHINE_NAME']
        self.pylmp = PyLammps(
            name=machine,
            cmdargs=['-nocite', '-log', 'none', '-echo', 'screen'])
        self.pylmp.units("lj")
        self.pylmp.atom_style("atomic")
        self.pylmp.atom_modify("map array")

        if 'LAMMPS_CMAKE_CACHE' in os.environ:
            self.cmake_cache = {}

            with open(os.environ['LAMMPS_CMAKE_CACHE'], 'r') as f:
                for line in f:
                    line = line.strip()
                    if not line or line.startswith('#') or line.startswith(
                            '//'):
                        continue
                    parts = line.split('=')
                    key, value_type = parts[0].split(':')
                    if len(parts) > 1:
                        value = parts[1]
                        if value_type == "BOOL":
                            value = (value.upper() == "ON")
                    else:
                        value = None
                    self.cmake_cache[key] = value

    def tearDown(self):
        self.pylmp.close()
        del self.pylmp

    def test_version(self):
        self.assertGreaterEqual(self.pylmp.version(), 20200824)

    def test_create_atoms(self):
        self.pylmp.region("box block", 0, 2, 0, 2, 0, 2)
        self.pylmp.create_box(1, "box")

        x = [1.0, 1.0, 1.0, 1.0, 1.0, 1.5]

        types = [1, 1]

        self.assertEqual(
            self.pylmp.lmp.create_atoms(2, id=None, type=types, x=x), 2)
        self.assertEqual(self.pylmp.system.natoms, 2)
        self.assertEqual(len(self.pylmp.atoms), 2)
        numpy.testing.assert_array_equal(self.pylmp.atoms[0].position,
                                         tuple(x[0:3]))
        numpy.testing.assert_array_equal(self.pylmp.atoms[1].position,
                                         tuple(x[3:6]))
        self.assertEqual(self.pylmp.last_run, None)

    def test_write_script(self):
        outfile = 'in.test_write_script'
        self.pylmp.write_script(outfile)
        self.assertTrue(os.path.exists(outfile))
        os.remove(outfile)

    def test_runs(self):
        self.pylmp.lattice("fcc", 0.8442),
        self.pylmp.region("box block", 0, 4, 0, 4, 0, 4)
        self.pylmp.create_box(1, "box")
        self.pylmp.create_atoms(1, "box")
        self.pylmp.mass(1, 1.0)
        self.pylmp.velocity("all create", 1.44, 87287, "loop geom")
        self.pylmp.pair_style("lj/cut", 2.5)
        self.pylmp.pair_coeff(1, 1, 1.0, 1.0, 2.5)
        self.pylmp.neighbor(0.3, "bin")
        self.pylmp.neigh_modify("delay 0 every 20 check no")
        self.pylmp.fix("1 all nve")
        self.pylmp.variable("fx atom fx")
        self.pylmp.run(10)

        self.assertEqual(len(self.pylmp.runs), 1)
        self.assertEqual(self.pylmp.last_run, self.pylmp.runs[0])
        self.assertEqual(len(self.pylmp.last_run.thermo.Step), 2)
        self.assertEqual(len(self.pylmp.last_run.thermo.Temp), 2)
        self.assertEqual(len(self.pylmp.last_run.thermo.E_pair), 2)
        self.assertEqual(len(self.pylmp.last_run.thermo.E_mol), 2)
        self.assertEqual(len(self.pylmp.last_run.thermo.TotEng), 2)
        self.assertEqual(len(self.pylmp.last_run.thermo.Press), 2)

    def test_info_queries(self):
        self.pylmp.lattice("fcc", 0.8442),
        self.pylmp.region("box block", 0, 4, 0, 4, 0, 4)
        self.pylmp.create_box(1, "box")
        self.pylmp.variable("a equal 10.0")
        self.pylmp.variable("b string value")
        self.assertEqual(self.pylmp.variables['a'].value, 10.0)
        self.assertEqual(self.pylmp.variables['b'].value, 'value')
        self.assertEqual(len(self.pylmp.variables), 2)
        self.assertEqual(self.pylmp.system.units, 'lj')
        self.assertEqual(self.pylmp.system.atom_style, 'atomic')
        self.assertEqual(self.pylmp.system.ntypes, 1)
        self.assertEqual(self.pylmp.system.natoms, 0)
        self.assertEqual(self.pylmp.communication.comm_style, 'brick')
        self.assertEqual(self.pylmp.communication.comm_layout, 'uniform')
        self.assertEqual(self.pylmp.communication.nprocs, 1)
        self.assertEqual(len(self.pylmp.computes), 3)
        self.assertEqual(self.pylmp.computes[0]['name'], 'thermo_temp')
        self.assertEqual(self.pylmp.computes[0]['style'], 'temp')
        self.assertEqual(self.pylmp.computes[0]['group'], 'all')
        self.assertEqual(self.pylmp.computes[1]['name'], 'thermo_press')
        self.assertEqual(self.pylmp.computes[1]['style'], 'pressure')
        self.assertEqual(self.pylmp.computes[1]['group'], 'all')
        self.assertEqual(self.pylmp.computes[2]['name'], 'thermo_pe')
        self.assertEqual(self.pylmp.computes[2]['style'], 'pe')
        self.assertEqual(self.pylmp.computes[2]['group'], 'all')
        self.assertEqual(len(self.pylmp.dumps), 0)
        self.pylmp.fix('one', 'all', 'nve')
        self.assertEqual(len(self.pylmp.fixes), 1)
        self.assertEqual(self.pylmp.fixes[0]['name'], 'one')
        self.assertEqual(self.pylmp.fixes[0]['style'], 'nve')
        self.assertEqual(self.pylmp.fixes[0]['group'], 'all')
        self.pylmp.group('none', 'empty')
        self.assertEqual(len(self.pylmp.groups), 2)
예제 #19
0
def run_lammps(lammps_in: str, output: str):
    Lbin = PyLammps(cmdargs=["-l", output])
    Lbin.file(lammps_in)
예제 #20
0
    def test_run_post_no_pre_no(self):
        L = PyLammps()
        L.file(IncludeTests.ATOMS_SETUP_FILE)

        # set non-bonded potential
        L.pair_style('lj/cut', 5.0)
        L.pair_coeff(1, 1, 1.0, 1.0)

        # set different non-bonded potential
        L.velocity('all create', 1.0, 54321, 'mom no rot no')

        # import time integration setting from include file
        L.file(IncludeTests.VERLET_CONFIG_FILE)

        L.minimize(1.0e-10, 1.0e-10, 100, 1000)

        L.reset_timestep(0)  # set timestep counter to zero

        L.thermo(10)         # thermo output every 10 steps

        L.run(100, 'post no') # don't print post run information

        L.run(100, 'pre no')  # don't to pre-run preparation (not needed, if no change)
예제 #21
0
    def test_change_potential(self):
        L = PyLammps()
        L.file(IncludeTests.ATOMS_SETUP_FILE)

        # set non-bonded potential
        L.pair_style('lj/cut', 5.0)
        L.pair_coeff(1, 1, 1.0, 1.0)

        # set different non-bonded potential
        L.velocity('all create', 1.0, 54321, 'mom no rot no')

        # import time integration setting from include file
        L.file(IncludeTests.VERLET_CONFIG_FILE)

        L.minimize(1.0e-10, 1.0e-10, 100, 1000)

        L.reset_timestep(0)  # set timestep counter to zero

        L.thermo(10)         # thermo output every 10 steps

        L.run(100, 'post no')

        # continue run with different potential
        L.pair_style('morse', 5.0)
        L.pair_coeff(1, 1, 1.0, 5.0, 1.12)

        L.run(100)
예제 #22
0
# coding: utf8
from lammps import lammps, PyLammps
lmp = lammps()
L = PyLammps(ptr=lmp)
import time
from mpi4py import MPI
import scipy.io
import numpy as np
from numpy import linalg as LA
import math, random
from shutil import copyfile


# Function definitions:
def getcoords_old(
):  # slow, but doesn't need additional lammps python interface
    nPart1 = 0
    nPart2 = 0
    nPartsub = 0

    coords1 = []
    coords2 = []
    coordssub = []
    indices1 = []
    indices2 = []
    indicessub = []
    print("get coords...")
    startt = time.time()
    for i in range(L.system.natoms):
        atype = L.atoms[i].type
        if atype == 1:
예제 #23
0
    def test_real_units(self):
        L = PyLammps()
        L.units('real') # angstrom, kcal/mol, femtoseconds
        L.atom_style('atomic')
        L.boundary('p p p')

        L.lattice('none', 1.0)

        # create simulation cell
        L.region('r1 block', -15.0, 15.0, -15.0, 15.0, -15.0, 15.0)
        L.create_box(1, 'r1')

        # argon
        L.mass(1, 39.948002)
        L.pair_style('lj/cut', 8.5)
        L.pair_coeff(1, 1, 0.2379, 3.405)

        L.timestep(10.0)

        L.create_atoms(1, 'single', -1.0, 0.0, 0.0)
        L.create_atoms(1, 'single',  1.0, 0.0, 0.0)

        L.velocity('all create', 250.0, 54321, 'mom no rot no')

        L.minimize(1.0e-10, 1.0e-10, 100, 1000)

        L.reset_timestep(0)

        L.thermo(100)
        L.fix('f1 all nve')
        L.run(1000)
예제 #24
0
class RealUnitsLatticeBoxTests(unittest.TestCase):
    def setUp(self):
        self.L = PyLammps()
        self.L.units('real')           # default, use reduced units
        self.L.atom_style('atomic')  # default, point particles with mass and type
        self.L.boundary('p p p')     # default, periodic boundaries in 3-d
        self.L.processors('* * *')   # default, automatic domain decomposition
        self.L.newton('on')          # default, use newton's 3rd law for ghost particles

    def assertAlmostEqualList(self, a_list, b_list):
        for a, b in zip(a_list, b_list):
            self.assertAlmostEqual(a, b, places=3)

    def test_real_none_box(self):
        self.L.lattice('none', 1.0)

        self.L.region('r1 block', -5.0, 5.0, -5.0, 5.0, -5.0, 5.0, 'units box')
        self.L.create_box(1, 'r1')

        self.assertEqual(self.L.system.orthogonal_box, [10, 10, 10])
        self.assertEqual(self.L.system.xlo, -5.0)
        self.assertEqual(self.L.system.ylo, -5.0)
        self.assertEqual(self.L.system.zlo, -5.0)
        self.assertEqual(self.L.system.xhi, 5.0)
        self.assertEqual(self.L.system.yhi, 5.0)
        self.assertEqual(self.L.system.zhi, 5.0)

    def test_real_sc_box(self):
        self.L.lattice('sc', 1.0)

        self.L.region('r1 block', -5.0, 5.0, -5.0, 5.0, -5.0, 5.0, 'units box')
        self.L.create_box(1, 'r1')

        self.assertEqual(self.L.system.orthogonal_box, [10, 10, 10])
        self.assertEqual(self.L.system.xlo, -5.0)
        self.assertEqual(self.L.system.ylo, -5.0)
        self.assertEqual(self.L.system.zlo, -5.0)
        self.assertEqual(self.L.system.xhi, 5.0)
        self.assertEqual(self.L.system.yhi, 5.0)
        self.assertEqual(self.L.system.zhi, 5.0)

    def test_real_fcc_box(self):
        self.L.lattice('fcc', 1.0)

        self.L.region('r1 block', -5.0, 5.0, -5.0, 5.0, -5.0, 5.0, 'units box')
        self.L.create_box(1, 'r1')

        self.assertEqual(self.L.system.orthogonal_box, [10, 10, 10])
        self.assertEqual(self.L.system.xlo, -5.0)
        self.assertEqual(self.L.system.ylo, -5.0)
        self.assertEqual(self.L.system.zlo, -5.0)
        self.assertEqual(self.L.system.xhi, 5.0)
        self.assertEqual(self.L.system.yhi, 5.0)
        self.assertEqual(self.L.system.zhi, 5.0)

    def test_real_bcc_box(self):
        self.L.lattice('bcc', 1.0)

        self.L.region('r1 block', -5.0, 5.0, -5.0, 5.0, -5.0, 5.0, 'units box')
        self.L.create_box(1, 'r1')

        self.assertEqual(self.L.system.orthogonal_box, [10, 10, 10])
        self.assertEqual(self.L.system.xlo, -5.0)
        self.assertEqual(self.L.system.ylo, -5.0)
        self.assertEqual(self.L.system.zlo, -5.0)
        self.assertEqual(self.L.system.xhi, 5.0)
        self.assertEqual(self.L.system.yhi, 5.0)
        self.assertEqual(self.L.system.zhi, 5.0)

    def test_real_none_lattice(self):
        self.L.lattice('none', 1.0)

        self.L.region('r1 block', -5.0, 5.0, -5.0, 5.0, -5.0, 5.0, 'units lattice')
        self.L.create_box(1, 'r1')

        self.assertEqual(self.L.system.orthogonal_box, [10, 10, 10])
        self.assertEqual(self.L.system.xlo, -5.0)
        self.assertEqual(self.L.system.ylo, -5.0)
        self.assertEqual(self.L.system.zlo, -5.0)
        self.assertEqual(self.L.system.xhi, 5.0)
        self.assertEqual(self.L.system.yhi, 5.0)
        self.assertEqual(self.L.system.zhi, 5.0)

    def test_real_sc_lattice(self):
        self.L.lattice('sc', 1.0)

        self.L.region('r1 block', -5.0, 5.0, -5.0, 5.0, -5.0, 5.0, 'units lattice')
        self.L.create_box(1, 'r1')

        self.assertEqual(self.L.system.orthogonal_box, [10, 10, 10])
        self.assertAlmostEqual(self.L.system.xlo, -5.0)
        self.assertAlmostEqual(self.L.system.ylo, -5.0)
        self.assertAlmostEqual(self.L.system.zlo, -5.0)
        self.assertAlmostEqual(self.L.system.xhi, 5.0)
        self.assertAlmostEqual(self.L.system.yhi, 5.0)
        self.assertAlmostEqual(self.L.system.zhi, 5.0)

    def test_real_fcc_lattice(self):
        self.L.lattice('fcc', 1.0)

        self.L.region('r1 block', -5.0, 5.0, -5.0, 5.0, -5.0, 5.0, 'units lattice')
        self.L.create_box(1, 'r1')

        lattice_spacing = 1.0

        self.assertAlmostEqualList(self.L.system.orthogonal_box, [10*lattice_spacing, 10*lattice_spacing, 10*lattice_spacing])
        self.assertAlmostEqual(self.L.system.xlo, -5.0 * lattice_spacing, places=3)
        self.assertAlmostEqual(self.L.system.ylo, -5.0 * lattice_spacing, places=3)
        self.assertAlmostEqual(self.L.system.zlo, -5.0 * lattice_spacing, places=3)
        self.assertAlmostEqual(self.L.system.xhi,  5.0 * lattice_spacing, places=3)
        self.assertAlmostEqual(self.L.system.yhi,  5.0 * lattice_spacing, places=3)
        self.assertAlmostEqual(self.L.system.zhi,  5.0 * lattice_spacing, places=3)

    def test_real_bcc_lattice(self):
        self.L.lattice('bcc', 1.0)

        self.L.region('r1 block', -5.0, 5.0, -5.0, 5.0, -5.0, 5.0, 'units lattice')
        self.L.create_box(1, 'r1')

        lattice_spacing = 1.0

        self.assertAlmostEqualList(self.L.system.orthogonal_box, [10*lattice_spacing, 10*lattice_spacing, 10*lattice_spacing])
        self.assertAlmostEqual(self.L.system.xlo, -5.0 * lattice_spacing, places=3)
        self.assertAlmostEqual(self.L.system.ylo, -5.0 * lattice_spacing, places=3)
        self.assertAlmostEqual(self.L.system.zlo, -5.0 * lattice_spacing, places=3)
        self.assertAlmostEqual(self.L.system.xhi,  5.0 * lattice_spacing, places=3)
        self.assertAlmostEqual(self.L.system.yhi,  5.0 * lattice_spacing, places=3)
        self.assertAlmostEqual(self.L.system.zhi,  5.0 * lattice_spacing, places=3)
예제 #25
0
run_args = rods.Rod_params()  # any object with __dict__ would do
if mpi_rank == 0:
    execfile(args.run_file, {
        '__builtins__': None,
        'True': True,
        'False': False,
        'None': None
    }, vars(run_args))
run_args = mpi_comm.bcast(run_args, root=0)

out_freq = args.output_freq if args.output_freq != None else run_args.mc_every

if mpi_rank == 0:
    py_lmp = PyLammps(cmdargs=['-echo', 'both'],
                      comm=mpi_comm,
                      verbose=args.verbose)
else:
    py_lmp = PyLammps(cmdargs=['-echo', 'both'], comm=mpi_comm)
py_lmp.log('"' + log_path + '"')

rod_params = rods.Rod_params()
if mpi_rank == 0:
    rod_params.from_file(args.cfg_file)
rod_params = mpi_comm.bcast(rod_params, root=0)

# CREATE BASE OBJECTS
model = rods.Rod_model(rod_params)
simulation = rods.Simulation(py_lmp, model, run_args.temp, seed, output_folder)

py_lmp.units("lj")
예제 #26
0
#!/usr/bin/env python3
from lammps import PyLammps, lammps
import numpy as np
import sys

l = lammps()
lmp = PyLammps(ptr=l)


lmp.units("lj")
lmp.atom_style("atomic")
lmp.lattice("fcc", 0.8442)
lmp.region("box", "block", 0, 4, 0, 4, 0, 4)
lmp.create_box(1, "box")
lmp.create_atoms(1, "box")
lmp.mass(1, 1.0)


lmp.velocity("all", "create", 10, 87287)
lmp.pair_style("lj/cut", 2.5)
lmp.pair_coeff(1, 1, 1.0, 1.0, 2.5)
lmp.neighbor(0.3, "bin")
lmp.neigh_modify("delay", 0, "every", 20, "check no")

lmp.fix("1 all nve")
a = l.extract_fix("2",2,2)
print(a.contents)
#nlocal = l.extract_global("nlocal",0) 
#print(nlocal)
#lmp.fix("2 all addforce 1.0 0.0 0.0")
예제 #27
0
def md_simulation(lmpcuts, group, style, ensemble, keyword_min=None, keyword=None, unwrap_dcd=True):
    """
    Perform an md simulation.
    """
    lmp = lammps()
    pylmp = PyLammps(ptr=lmp)
    lmp.command("log {} append".format(lmpcuts.output_lmplog))

    if lmpcuts.gpu is True:
        lmpcuts.use_gpu(lmp, neigh=True)

    lmp.file(lmpcuts.settings_file)

    # change dielectric
    if lmpcuts.dielectric is not None:
        lmp.command("dielectric {}".format(lmpcuts.dielectric))

    lmpcuts.load_system(lmp)

    lmpcuts.thermo(lmp)
    lmpcuts.dump(lmp, unwrap=unwrap_dcd)

    if lmpcuts.pc_file is not None:
        lmp.file(lmpcuts.pc_file)

    # distribute the available cores; option must be set after loading pair coeffs!
    lmp.command("comm_style tiled")
    lmp.command("balance 1.0 rcb")

    # pre-minimize system before running the actual simulation
    if lmpcuts.input_lmprst is None or os.path.isfile(lmpcuts.input_lmprst):
        #lmp.command("min_modify line quadratic")
        lmpcuts.minimize(lmp, style="cg", keyword=keyword_min)

    # barostatting, thermostatting
    lmp.command("fix ic_prevention all momentum {} linear 1 1 1 angular rescale".format(lmpcuts.momentum_steps))

    # set the group
    if group != "all":
        lmp.command(group)
        groupname = group.split()[1]
    else:
        groupname = "all"

    if style.lower() == "berendsen":
        lmpcuts.fix_berendsen(lmp, groupname, ensemble, keyword)
    elif style.lower() == "nose_hoover":
        lmpcuts.fix_hoover(lmp, groupname, ensemble, keyword)
    elif style.lower() == "langevin":
        lmpcuts.fix_langevin(lmp, groupname, ensemble, keyword)
    else:
        raise Warning("Style not (yet) implemented!")

    lmp.command("reset_timestep 0")

    try:
        lmp.command("run {}".format(lmpcuts.runsteps))
    except:
        # prevent deadlock by not nicely ending the whole program if more
        # than one rank is used
        if size > 1:
            MPI.COMM_WORLD.Abort()

    #lmp.command("run {}".format(lmpcuts.runsteps))
    #lmpcuts.minimize(lmp, style="cg", keyword=keyword_min)
    lmpcuts.unfix_undump(pylmp, lmp)
    lmp.command("write_restart {}".format(lmpcuts.output_lmprst))
    lmp.command("clear")
    lmp.close()
예제 #28
0
    def setUp(self):
        L = PyLammps()
        L.units('lj')
        L.atom_style('atomic')
        L.boundary('p p p')
        L.atom_modify("map array")

        L.region('r1 block', -5.0, 5.0, -5.0, 5.0, -5.0, 5.0)
        L.create_box(1, 'r1')

        L.mass(1, 1.0)

        L.create_atoms(1, 'single', -1.0, 0.0, 0.0)
        L.create_atoms(1, 'single',  1.0, 0.0, 0.0)

        L.pair_style('lj/cut', 5.0)
        L.pair_coeff(1, 1, 1.0, 1.0)

        L.run(0)
        self.L = L
예제 #29
0
    def test_use_data_file(self):
        L = PyLammps()
        L.units('real') # angstrom, kcal/mol, femtoseconds
        L.atom_style('atomic')
        L.boundary('p p p')

        L.lattice('none', 1.0)

        # create simulation cell
        L.region('r1 block', -15.0, 15.0, -15.0, 15.0, -15.0, 15.0)
        L.create_box(1, 'r1')

        # argon
        L.mass(1, 39.948002)
        L.pair_style('lj/cut', 8.5)
        L.pair_coeff(1, 1, 0.2379, 3.405)

        L.timestep(10.0)

        L.create_atoms(1, 'single', -1.0, 0.0, 0.0)
        L.create_atoms(1, 'single',  1.0, 0.0, 0.0)

        L.velocity('all create', 250.0, 54321, 'mom no rot no')

        L.minimize(1.0e-10, 1.0e-10, 100, 1000)

        L.reset_timestep(0)

        L.thermo(100)
        L.fix('f1 all nve')
        L.run(1000)

        L.write_restart('run.restart')
        L.write_data('run.data')

        L2 = PyLammps()
        L2.units('real')           # angstrom, kcal/mol, femtoseconds
        L2.atom_style('atomic')
        L2.boundary('p p p')

        L2.pair_style('lj/cut', 8.5)
        L2.read_data('run.data')

        L2.timestep(10.0)

        L2.thermo(100)
        L2.fix('f1 all nve')
        L2.run(1000)

        # reset status. forget all settings. delete system
        L2.clear()

        L2.read_restart('run.restart')

        L2.thermo(100)
        L2.fix('f1 all nve')
        L2.run(1000)

        os.remove('run.restart')
        os.remove('run.data')

        self.assertEqual(L.system, L2.system)
예제 #30
0
#!/usr/bin/env python

from mpi4py import MPI
from lammps import PyLammps

L = PyLammps()
L.file("in.melt")

if MPI.COMM_WORLD.rank == 0:
    print("Potential energy: ", L.eval("pe"))

MPI.Finalize()
예제 #31
0
from mpi4py import MPI
from lammps import PyLammps

L = PyLammps()
L.file('in.melt')


if MPI.COMM_WORLD.rank == 0:
    pe = L.eval("pe")
    print("Potential Energy:", pe)