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')
    def test_melt_using_groups(self):
        """ 3d Lennard-Jones melt with two atom types """
        L = PyLammps()
        L.units('lj')
        L.atom_style('atomic')
        L.lattice('fcc', 0.8442) # NOTE: lattice command is different in LJ units
        L.region('whole block', 0.0, 10.0, 0, 10, 0, 10)
        L.create_box(2, 'whole')
        L.region('upper block', 4.9, 10.1, 'EDGE EDGE EDGE EDGE')
        L.region('lower block', 0.0,  4.9, 'EDGE EDGE EDGE EDGE')

        # fill box with atoms according to lattice positions
        L.create_atoms(1, 'region upper')
        L.create_atoms(2, 'region lower')

        L.mass(1, 1.0)
        L.mass(2, 2.0)

        L.group('gu', 'type', 1)
        L.group('gl', 'type', 2)

        L.velocity('gu', 'create 2.0 12345 mom no rot no')
        L.velocity('gl', 'create 4.0 54321 mom no rot no')


        L.timestep(0.002)
        L.pair_style('lj/cut', 2.5)
        L.pair_coeff('* *', 1.0, 1.0, 2.5)
        L.fix('f1 all nve')

        #L.dump('d1 all image 500 snap-03.*.jpg type type')

        L.thermo(50)
        L.run(500)
    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)
    def test_melt(self):
        """ 3d Lennard-Jones melt """
        L = PyLammps()
        L.units('lj')
        L.atom_style('atomic')

        L.lattice('fcc', 0.8442)   # NOTE: lattice command is different in LJ units
                                   #       0.8442 is density fraction
        L.region('r1 block', 0, 10, 0, 10, 0, 10)
        L.create_box(1, 'r1')

        # fill box with atoms according to lattice positions
        L.create_atoms(1, 'box')
        L.mass(1, 1.0)
        L.velocity('all create', 3.0, 87287, 'mom no')

        L.timestep(0.002)

        L.pair_style('lj/cut', 2.5)
        L.pair_coeff(1, 1, 1.0, 1.0, 2.5)
        L.fix('f1 all nve')

        L.dump('d1 all image 500 snap-01.*.jpg type type')

        L.thermo(50)
        L.run(500)

        self.assertTrue(os.path.exists('snap-01.0.jpg'))
        self.assertTrue(os.path.exists('snap-01.500.jpg'))
        os.remove('snap-01.0.jpg')
        os.remove('snap-01.500.jpg')
    def setUp(self):
        """create 3d rocksalt-like structure"""
        L = PyLammps()
        L.units('real')         # kcal/mol, Angstrom, picoseconds
        L.atom_style('charge')  # atomic + charge

        # lattice for Na+ ions and box
        L.lattice('fcc', 6.0, 'origin', 0.0, 0.0, 0.0)
        L.region('r1', 'block', -3, 3,-3, 3,-3, 3)
        L.create_box(2, 'r1')

        # fill box with Na+ ions according to lattice positions
        L.create_atoms(1, 'box')

        # new lattice for Cl- ions shifted by half box diagonal
        L.lattice('fcc', 6.0, 'origin', 0.5, 0.5, 0.5)
        L.create_atoms(2, 'box')

        L.mass(1, 22.989770)
        L.mass(2, 35.453)
        L.set('type', 1, 'charge',  1.0)
        L.set('type', 2, 'charge', -1.0)

        L.group('na type', 1)
        L.group('cl type', 2)

        L.velocity('all create', 800.0, 12345, 'mom no rot no')
        L.timestep(0.001)
        self.L = L
Beispiel #6
0
def data(i):
    lmp1 = lammps()
    polymer = PyLammps(ptr=lmp1)
    x = 60
    y = 30
    z = 30
    t = 1
    polymer.units("lj")
    polymer.dimension(3)
    polymer.atom_style("bond")
    polymer.bond_style("harmonic")
    polymer.pair_style("lj/cut", 3)
    polymer.read_data("data.polymer")
    polymer.region("void cylinder x", 15, 15, 2, 29, 31)
    polymer.pair_coeff(1, 2, 2.5, 3)
    polymer.pair_coeff(1, 3, 2.5, 1.12)
    polymer.pair_coeff(2, 3, 2.5, 1.12)
    polymer.velocity("all create", t, 97287)
    polymer.group("polymer type", 1, 2)
    polymer.group("first type", 1)
    polymer.region("box block", 0, x, 0, y, 0, z)
    polymer.region("spherein sphere", 29, 15, 15, 2)
    polymer.region("boxin block", 27, 29, 13, 17, 13, 17)
    polymer.region("hemiin intersect", 2, "boxin spherein")
    x0 = polymer.atoms[0].position[0]
    y0 = polymer.atoms[0].position[1]
    z0 = polymer.atoms[0].position[2]
    r = lambda x0, y0, z0: np.sqrt((x0 - 29)**2 + (y0 - 15)**2 + (z0 - 15)**2)
    fx = lambda x0, y0, z0: 5 * (x0 - 29) / r(x0, y0, z0)
    fy = lambda x0, y0, z0: 5 * (y0 - 15) / r(x0, y0, z0)
    fz = lambda x0, y0, z0: 5 * (z0 - 15) / r(x0, y0, z0)
    polymer.fix(1, "polymer nve")
    polymer.fix(2, "polymer langevin", t, t, 1.5,
                np.random.randint(2, high=200000))
    polymer.fix(3, "polymer spring tether", 10, i, "NULL NULL", 0)
    polymer.timestep(0.01)
    polymer.compute("com polymer com")
    polymer.variable("ftotal equal fcm(polymer,x)")
    polymer.variable("c equal c_com[1]")
    polymer.thermo_style("custom v_ftotal v_c")
    polymer.thermo(1)
    polymer.run(500000)
    l = polymer.runs[0][0][1][20000:] + [i]
    u = [np.mean(polymer.runs[0][0][0][20000:]), i]
    np.savetxt("trial%dmean.txt" % i, u)
    np.savetxt("trial%dall.txt" % i, l)
    return u
    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
Beispiel #8
0
# time spans for scattering simulation in ps:
initequalt = 1  # initial equilibration time between velocity reset and new scattering event
dcheckafterscatteringt = 0.4  # time between scattering event and displacement check
equilibrationt = 0.5  # time for equilibration

# continue from existing geometry?
continueprevsim = False

#reset geometry after every run?
resetgeom = False
selectfromNIST = True

# MD PARAMETERS:
L.units("metal")
L.atom_style("atomic")
L.atom_modify("map array")

latticeconst = 4.08
dispthresh = (4.08 + 3.52) / 2 / math.sqrt(2) * 0.90
NNthresh = (4.08 + 3.52) / 2 / math.sqrt(2) * 1.2

L.timestep(0.0005)  # time-step in ps (metal units)
dsub = 10

density = 2000
Amass = 12.011 * 1.660538E-27
nPartsub = int(round(Lsub * Lsub * dsub * 1e-30 * density / Amass))
print(nPartsub)

#Au-C: (Lewis.2000)
Beispiel #9
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)
Beispiel #10
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")
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)
    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)
 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')
Beispiel #14
0
class LammpsCalc(object):
    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

    # def load_files(self):
    #     self.lmp.file("init.mod")
    #     self.lmp.file("potential.mod")

    def read_prim(self):
        prim_path = "./prim.json"
        prim_file = open(prim_path).read()
        prim = json.JSONDecoder().decode(prim_file)
        print("prim:\n\n\n\n", prim)
        if prim['coordinate_mode'] == "Fractional":
            self.basis_vec = np.array(prim['lattice_vectors'])
            self.basis_sites = []
            # for basis in prim['']

    def read_structure(self):
        # Dir is defined at CASMcode/python/casm/casm/project/project.py
        # dir.__setattr__("POS", open(self.configurename + "/POS"))
        # pos_file = dir.POS(self.configname)
        pos_file = open(self.poscar)
        # assert \
        self.configurename == pos_file.readline().strip()
        a0 = float(pos_file.readline().strip())
        print(a0)
        a1str = pos_file.readline().strip()
        a1 = a1str.split()
        a2str = pos_file.readline().strip()
        a2 = a2str.split()
        a3str = pos_file.readline().strip()
        a3 = a3str.split()

        self.lattice = np.array([a1, a2, a3], float) * a0
        print("lattice")
        print(self.lattice)

        labels = pos_file.readline().strip().split()
        nums = pos_file.readline().strip().split()

        for i in range(len(labels)):
            self.atoms_num[labels[i]] = nums[i]

        self.total_atoms = np.sum(np.array(nums, int))
        self.num_types_cell = len(labels)
        self.atoms = np.zeros((self.total_atoms, 3))
        self.atom_types = np.zeros(self.total_atoms)

        assert 'Direct' == pos_file.readline().strip()

        i = 0
        line = pos_file.readline()
        while line:
            line = line.strip()
            tokens = line.split()
            line = pos_file.readline()
            if len(tokens) <= 0:
                continue
            frac_coor = np.array(tokens[:3], float)
            # cart_coor = frac_coor @ lattice.T # convert fractional coordinates to cartesian
            # print(self.lmp.atoms)
            # self.lmp.atoms[i].position = tuple(cart_coor.reshape(1, -1)[0])
            self.atoms[i] = frac_coor
            # self.lmp.atoms[i].type = int(labels_dict[tokens[3].strip()])
            self.atom_types[i] = int(self.labels_dict[tokens[3].strip()])
            # print(atoms[i], atom_types[i])
            i += 1

    def create_structure(self):
        # Might not need this function anymore
        self.read_structure()
        # self.xlo = round(np.amin(cart_coors[:, 0]), 8)
        # # self.xhi = round(np.amax(cart_coors[:, 0]), 8)
        # self.ylo = round(np.amin(cart_coors[:, 1]), 8)
        # # self.yhi = round(np.amax(cart_coors[:, 1]), 8)
        # self.zlo = round(np.amin(cart_coors[:, 2]), 8)
        # # self.zhi = round(np.amax(cart_coors[:, 2]), 8)
        self.create_region()
        self.read_prim()
        self.create_atoms()


    def create_atoms(self):
        self.cart_coors = self.atoms @ self.lattice

        print('\nAtoms:\n', self.cart_coors[:10], "\n", self.atom_types[:10])

        print("test", self.cart_coors[0][0])
        print("atom types", self.atom_types)
        print("coors: ")
        print(self.cart_coors)
        print(self.pylmp.atoms.natoms)

        # Could optionally use lammps_create_atoms(void *, int, tagint *, int *, double *, double *,
        #                          imageint *, int)
        # But would still need to iterate through list and this method aides debugging.
        for i in range(self.cart_coors.shape[0]):
            # maybe should iterate through possible rounding values
            ### rounding must be consistent across all structure values
            print(
                'create_atoms ' + str(int(self.atom_types[i])) + ' single ' + str(round(self.cart_coors[i][0], 16)) + ' '
                + str(round(self.cart_coors[i][1], 16)) + ' ' + str(round(self.cart_coors[i][2], 16)))
            # self.pylmp.command(
            #     'create_atoms ' + str(int(self.atom_types[i])) + ' single ' + str(round(self.cart_coors[i][0], 16)) + ' '
            #     + str(round(self.cart_coors[i][1], 16)) + ' ' + str(round(self.cart_coors[i][2], 16)))
            self.pylmp.command(
                'create_atoms ' + str(int(self.atom_types[i])) + ' single ' + str(
                    self.cart_coors[i][0]) + ' '
                + str(self.cart_coors[i][1]) + ' ' + str(self.cart_coors[i][2]))

        print(self.cart_coors.shape[0])
        print(self.pylmp.atoms.natoms)



    def get_labels(self):
        raise NotImplementedError()

    def run_calc(self):
        raise NotImplementedError()

    def create_properties(self):
        self.properties['atom_type'] = list(self.labels_dict.keys())
        self.properties['atoms_per_type'] = [self.atoms_num[atom] for atom in self.atoms_num.keys()]
        # enforces same order as atom_type
        self.properties['coord_mode'] = 'cartesian'
        self.properties['is_complete'] = True if self.relaxed_energy is not None else False
        relaxed_basis = []
        relaxed_forces = []
        for i in range(self.total_atoms):
            relaxed_basis.append(list(self.pylmp.atoms[i].position))
            relaxed_forces.append(list(self.pylmp.atoms[i].force))

        self.properties['relaxed_basis'] = relaxed_basis
        self.properties['relaxed_energy'] = self.relaxed_energy
        self.properties['relaxed_forces'] = relaxed_forces
        self.properties['relaxed_lattice'] = [[self.pylmp.system.xhi-self.pylmp.system.xlo, 0, 0],
                                              [self.pylmp.eval('xy'), self.pylmp.system.yhi-self.pylmp.system.ylo, 0],
                                              [self.pylmp.eval('xz'), self.pylmp.eval('yz'), self.pylmp.system.zhi-self.pylmp.system.zlo]]
        j_encoder = json.JSONEncoder()
        self.json_props = j_encoder.encode(self.properties)
        return self.properties
        # self.properties['relaxed_lattice'] = self.lattice

    # def report_results(self):
    #
    #     try:
    #         os.mkdir(self.configurename + '/calctype.lammps')
    #     except:
    #         pass
    #
    #     outputfile = self.configurename + '/calctype.lammps/properties.calc.json'
    #
    #     with open(outputfile, 'wb') as file:
    #         # cls=noindent.NoIndentEncoder,
    #         file.write(six.u(json.dumps(self.properties, indent=4, sort_keys=True)).encode('utf-8'))
    #     print("Wrote " + outputfile)
    #     sys.stdout.flush()
    #     self.report_status()

    # def report_status(self):
    #     output = {'status': 'complete'}
    #     outputfile = self.configurename + '/calctype.lammps/status.json'
    #
    #     with open(outputfile, 'wb') as file:
    #         # cls=noindent.NoIndentEncoder,
    #         file.write(six.u(json.dumps(output, indent=4, sort_keys=True)).encode('utf-8'))
    #     print("Wrote " + outputfile)
    #     sys.stdout.flush()

    def create_region(self):
        # In the future will have to read prim and take max or min vector for each dimension
        # Need to add space for next position b/c otherwise periodicity will make atoms at border overlap
        # basis_vec = np.array([0.666666666667, 0.333333333334, 0.500000000000])
        # lat_vec = np.array([[3.184000000000, 0.000000000000, 0.000000000000],
        #                     [-1.592000000000, 2.757424885650, 0.000000000000],
        #                     [0.000000000000, 0.000000000000, 5.249000000000]])
        # dist = basis_vec @ lat_vec
        # self.xhi += dist[0]
        # self.yhi += dist[1]
        # self.zhi += dist[2]
        # a = 3.2094
        # self.lmp.lattice("hcp ", a)
        # self.xy = self.lattice[1, 0]
        # self.yz = self.lattice[2, 1]
        # self.xz = self.lattice[2, 0]
        self.xlo = 0
        self.ylo = 0
        self.zlo = 0
        self.cos_alpha = self.cos_angle(self.lattice[1], self.lattice[2])
        self.cos_beta = self.cos_angle(self.lattice[0], self.lattice[2])
        self.cos_gamma = self.cos_angle(self.lattice[0], self.lattice[1])
        self.xy = self.norm(self.lattice[1]) * self.cos_gamma
        self.xz = self.norm(self.lattice[2]) * self.cos_beta
        self.xhi = self.norm(self.lattice[0])
        self.yhi = np.sqrt(self.norm(self.lattice[1])**2 - self.xy**2)
        self.yz = ((self.norm(self.lattice[1]) * self.norm(self.lattice[2]) * self.cos_alpha) - (self.xy * self.xz)) / self.yhi
        self.zhi = np.sqrt((self.norm(self.lattice[2])**2) - (self.xz**2) - (self.yz**2))
        # self.xhi = self.lattice[0, 0] - self.lattice[1, 0] - self.lattice[2, 0]
        # self.yhi = self.lattice[1, 1] - self.lattice[0, 1] - self.lattice[2, 1]
        # self.zhi = self.lattice[2, 2] - self.lattice[0, 2] - self.lattice[1, 2]

        self.pylmp.atom_style('atomic')
        print('prism ', self.xlo, ' ', self.xhi, ' ', self.ylo, ' ', self.yhi, ' ', self.zlo, ' ', self.zhi, ' ', self.xy, ' ', self.xz, ' ', self.yz)
        self.pylmp.region('box prism ', self.xlo, ' ', self.xhi, ' ', self.ylo, ' ', self.yhi, ' ', self.zlo, ' ', self.zhi, ' ', self.xy, ' ', self.xz, ' ', self.yz)
        self.pylmp.command("boundary	p p p")
        # self.lmp.region("box block", self.xlo, self.xhi, self.ylo, self.yhi, self.zlo, self.zhi)
        # self.lmp.command("create_box {0:d} box".format(num_types))
        self.pylmp.command("create_box {0:d} box".format(len(self.labels_dict.keys())))
        print("bounding box", self.pylmp.system.xlo, self.pylmp.system.xhi, self.pylmp.system.ylo, self.pylmp.system.yhi, self.pylmp.system.zlo, self.pylmp.system.zhi)

        # self.lmp.create_atoms("1 box")
        for i in self.labels_dict.values():
            self.pylmp.command("mass {0:d} 1.0e-20".format(i))
            # self.pylmp.command("mass 2 1.0e-20")

    def norm(self, vec):
        return np.sqrt(np.sum(vec**2))

    def dot_prod(self, vec1, vec2):
        return np.sum(vec1 * vec2)

    def cos_angle(self, vec1, vec2):
        cos_theta = self.dot_prod(vec1, vec2) / (self.norm(vec1) * self.norm(vec2))
        assert cos_theta >= -1 and cos_theta <= 1
        if cos_theta < -1:
            cos_theta = -1
        elif cos_theta > 1:
            cos_theta = 1

        return cos_theta

    def visualize(self):
        try:
            print("creating", "./dumpfiles/" + self.scel)
            os.mkdir("./dumpfiles/" + self.scel)
        except:
            pass

        try:
            print("creating", "./dumpfiles/" + self.configurename)
            os.mkdir("./dumpfiles/" + self.configurename)
        except:
            pass

        self.pylmp.dump("dump1", "all", "atom", 1, "./dumpfiles/" + self.configurename + "/dump.atom") # , "zoom 2.0"
Beispiel #15
0
class LammpsKernel(IGMKernel):
    def __init__(self, model, cfg, runid):
        self.cfg = cfg
        self.model = model
        self.runid = runid
        
        self.tmp_dir = self.cfg.tmpdir('optimization')
        self.randseed = int(self.cfg["optimization/kernel_opts/lammps/seed"])
        
        self.initLammps()
        
        self.setupSimulationBox()
        
        self.setupParticles()
        self.setCoordinates()
        self.setRadii()
        
        self.setupNeighbor()
        
    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')
    
    def setupSimulationBox(self):
        """
        setup lammps simulation box
        """
        atom_types = 1
        bond_types = 0
        bond_per_atom = 0
        for Res in self.model.restraints:
            atom_types += Res.extra_atom_types
            bond_types += Res.extra_bond_types
            bond_per_atom += Res.extra_bond_per_atom
            
            if res.type == "Envelope":
                xx , yy, zz = Res.a*1.2, Res.b*1.2, Res.c*1.2
        
        self.Lmp.region("IGMBOX", "block", -xx, xx, -yy, yy, -zz, zz)
        self.Lmp.create_box(1, "IGMBOX", "bond/types", bond_types, "extra/bond/per/atom", bond_per_atom)
    
    def setupParticles(self):
        """
        initialize particles with random position
        """
        
        #add user define per-atom property: radius(double)
        self.Lmp.fix("UserProperty","all","property/atom","d_radius")
        
        #number of particles
        self.nbead = len(self.model.particles)
        
        self.atom_style_index = 1
        self.Lmp.create_atoms(1, "random", self.nbead, self.randseed, "IGMBOX")
        
        #set particle mass 1.0
        self.Lmp.mass('*', 1.0)
        
        #group particle NORMAL
        self.lmp_group_NORMAL = "NORMAL"
        self.Lmp.group(self.lmp_group_NORMAL, "type", 1)
        
        #get numpy view of per atom array
        
        self.particle_id  = self.Lmp.lmp.numpy.extract_atom_iarray('id', n, 1)
        self._coordinates = self.Lmp.lmp.numpy.extract_atom_darray('x', n, 3)
        self._radii       = self.lmp.lmp.numpy.extract_atom_darray('d_radius', n, 1)
        
    def indexMapping(self):
        """
        particle mapping from lammps index to original index
        """
        return np.argsort( self.particle_id[:, 0] )
    
    def setCoordinates(self, crd = None):
        """
        assign xyz values to lammps
        """
        if crd:
            self.coordinates[self.indexMapping(), :] = crd[:]
        else:
            self.coordinates[self.indexMapping(), :] = self.model.particles.coordinates[:]
        
    def setRadii(self, radii = None):
        """
        assign radius values to lammps
        """
        if radii:
            self.radii[self.indexMapping(), :]       = radii[:]
        else:
            self.radii[self.indexMapping(), :]       = self.model.particles.radii[:]
            
        self.maxrad = max(self.radii)
        
    def setupNeighbor(self):
        """
        setup neighbor list rules
        """
        if hasattr(self, "maxrad"):
            self.Lmp.neighbor(self.maxrad, 'bin')
        else:
            raise RuntimeError("Radii not set before setupNeighbor()")
            
        max_neighbor = int(self.cfg["optimization/kernel_opts/lammps/max_neigh"])
        
        self.Lmp.neigh_modify('every',1,'check','yes')
        self.Lmp.neigh_modify("one", max_neighbor, 'page', 20*max_neighbor)
    
    def addRestraints(self):
        """
        add restraints to lammps one by one
        """
        #lammps bond style definition
        bond_styles = set()
        n = 1
        for Res in self.model.restraints:
            if hasattr(Res, "bond_style"):
                bond_styles.add(Res.bond_style)
                
                #give_bond_id
                Res.setBondId(n)
                n += 1
        if len(bond_styles) == 1:
            self.Lmp.bond_style(bond_styles.pop())
        elif len(bond_styles) > 1:
            cmd = ["bond_style", "hybrid"]
            while bond_styles:
                cmd.append(bond_styles.pop())
            self.Lmp.command(" ".join(cmd))
            
        #define variable for fast communication/avoid input string parsing
        self.Lmp.variable("batoms","string","EMPTY")
        bond_variable = "batoms"
        
        #loop all restraints and apply lammps code
        for Res in self.model.restraints:
            Res.Lammps(self.Lmp, runid         = self.runid, 
                                 tmp_dir       = self.tmp_dir, 
                                 randseed      = self.randseed, 
                                 normal_group  = self.lmp_group_NORMAL,
                                 bond_variable = bond_variable)