Exemplo n.º 1
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)
Exemplo n.º 2
0
    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)
Exemplo n.º 3
0
    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')
Exemplo n.º 4
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
Exemplo n.º 5
0
    #L.dump_modify("d1","element","Au","Ni","C")
    #L.dump_modify("d1","pbc","yes") # remap atoms via periodic boundary conditions
    #L.dump("trajectory","all","atom",100, "T" + str(Temp) + "_Fulltrajectories.lammpstrj")

    # Set thermo output to log file
    L.thermo_style("custom", "step", "atoms", "temp", "etotal", "pe", "ke",
                   "dt")
    L.thermo(1000)
    L.thermo_modify("lost", "ignore", "flush", "yes")
    L.echo("none")

    L.velocity("all", "create", Temp, 12345, "dist", "gaussian", "mom", "yes",
               "rot", "yes")

    #L.fix("thermofix","all","temp/csvr",Temp,Temp,0.1,12345)	# does not perform time integration !
    L.fix("thermofix1", "allintegrategr", "langevin", 1, 1, 0.1, 699483,
          "zero", "yes")
    #L.fix("nveintegration","allintegrategr","nve/limit",0.05)	# performs time integration with modified velocities in micro-canonical ensemble
    L.fix("nveintegration", "allintegrategr", "nve")

    # initial equilibration:
    starttime = time.time()
    L.run(20000)
    print("dt at start: {} fs".format(L.eval("dt") * 1000))
    print("T at start: {} K".format(L.eval("temp")))
    print("elapsed time: {} s".format(time.time() - starttime))

    L.unfix("nveintegration")  # remove time integration fix
    L.unfix("thermofix1")

    L.velocity("all", "create", Temp, 12345, "dist", "gaussian", "mom", "yes",
               "rot", "yes")
Exemplo n.º 6
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)
Exemplo n.º 7
0
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")

#f = l.extract_atom("f",3)
#a = np.ctypeslib.as_array(f.contents,shape=(natoms, 3))
#print(a)

lmp.dump("id all atom 50 dumpT10.0.lammpstrj")

lmp.thermo(50)
lmp.run(10000)
Exemplo n.º 8
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")
py_lmp.dimension(3)
py_lmp.boundary("p p p")
py_lmp.lattice("sc", 1 / (run_args.cell_size**3))
py_lmp.region("box", "block", -run_args.num_cells / 2, run_args.num_cells / 2,
              -run_args.num_cells / 2, run_args.num_cells / 2,
              -run_args.num_cells / 2, run_args.num_cells / 2)
simulation.setup("box")
simulation.create_rods(box=None)

# ROD DYNAMICS
py_lmp.fix("thermostat", "all", "langevin", run_args.temp, run_args.temp,
           run_args.damp, seed)  #, "zero yes")

simulation.set_rod_dynamics("nve", opt=["mol", model.rod_states[0]])

py_lmp.neigh_modify("every 1 delay 1")
py_lmp.timestep(run_args.dt)

# THERMALIZE INITIAL CONFIGURATION
simulation.deactivate_state(0, vx_eps=5.0)
py_lmp.run(1000)
simulation.activate_state(0)
py_lmp.reset_timestep(0)

# GROUPS & COMPUTES
if hasattr(run_args, 'label_micelles'):
    micelle_group = 'sol_tips'
Exemplo n.º 9
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)
Exemplo n.º 10
0
py_lmp.dimension(3)
py_lmp.boundary('p p f')
py_lmp.region('box', 'block', membrane.xmin, membrane.xmax, membrane.ymin,
              membrane.ymax, 0.0, run_args.Lz)

simulation.setup('box',
                 type_offset=max(membrane.bead_types),
                 extra_pair_styles=[('cosine/squared', model.global_cutoff)],
                 bond_offset=membrane.bond_type,
                 extra_bond_styles=['fene'],
                 opt=['angle/types', 1, 'extra/angle/per/atom', 1])
py_lmp.angle_style('harmonic')

zwalls_fix = 'zwalls'
py_lmp.fix(zwalls_fix, 'all', 'wall/lj126', 'zlo EDGE', 1.0, model.rod_radius,
           model.rod_radius * pow(2, 1. / 6), 'zhi EDGE', 1.0,
           model.rod_radius, model.rod_radius * pow(2, 1. / 6))

for bead_type in membrane.bead_types:
    py_lmp.mass(bead_type, membrane.bead_mass)
py_lmp.angle_coeff(membrane.angle_type, 5.0 * membrane.eps, 180)
py_lmp.bond_coeff(membrane.bond_type, 'fene',
                  30.0 * membrane.eps / membrane.sigma**2,
                  1.5 * membrane.sigma, membrane.eps, membrane.sigma)

lj_factor = pow(2, 1. / 6)
# head-head & head-tail inter-lipid interaction
for bead_type in membrane.bead_types:
    py_lmp.pair_coeff(membrane.head_type, bead_type, membrane.eps,
                      0.95 * membrane.sigma * lj_factor,
                      0.95 * membrane.sigma * lj_factor, 'wca')
Exemplo n.º 11
0
py_lmp.dimension(3)
py_lmp.boundary('p p f')
py_lmp.region('box', 'block',
              membrane.xmin, membrane.xmax,
              membrane.ymin, membrane.ymax,
              0.0, run_args.Lz)

simulation.setup('box', type_offset=max(membrane.bead_types),
                 extra_pair_styles=[('cosine/squared', model.global_cutoff)],
                 bond_offset=membrane.bond_type, extra_bond_styles=['fene'],
                 everything_else=['angle/types', 1, 'extra/angle/per/atom', 1])
py_lmp.angle_style('harmonic')

zwalls_fix = 'zwalls'
py_lmp.fix(zwalls_fix, 'all', 'wall/lj126',
           'zlo EDGE', 1.0, model.rod_radius, model.rod_radius*pow(2,1./6),
           'zhi EDGE', 1.0, model.rod_radius, model.rod_radius*pow(2,1./6))

for bead_type in membrane.bead_types:
    py_lmp.mass(bead_type, membrane.bead_mass)
py_lmp.angle_coeff(membrane.angle_type, 5.0*membrane.eps, 180)
py_lmp.bond_coeff(membrane.bond_type, 'fene', 30.0*membrane.eps/membrane.sigma**2,
                  1.5*membrane.sigma, membrane.eps, membrane.sigma)

lj_factor = pow(2, 1./6)
# head-head & head-tail inter-lipid interaction
for bead_type in membrane.bead_types:
    py_lmp.pair_coeff(membrane.head_type, bead_type, membrane.eps,
                      0.95*membrane.sigma*lj_factor,
                      0.95*membrane.sigma*lj_factor, 'wca')
# tail-tail inter-lipid interaction
Exemplo n.º 12
0
def elastic():
    """ Compute elastic constant tensor for a crystal

     In order to calculate the elastic constants correctly, care must be taken to specify
     the correct units (units). It is also  important to verify that the minimization of energy
     w.r.t atom  positions in the deformed cell is fully converged.
     One indication of this is that the elastic constants are insensitive
     to the choice of the variable ${up}. Another is to check
     the final max and two-norm forces reported in the log file. If you know
     that minimization is not required, you can set maxiter = 0.0 """

    parser = ArgumentParser(
        description=
        'A python script to compute elastic properties of bulk materials')

    parser.add_argument("input_data_file",
                        help="The full path & name of the lammps data file.")
    parser.add_argument(
        "kim_model",
        help="the KIM ID of the interatomic model archived in OpenKIM")
    parser.add_argument(
        "elements",
        nargs='+',
        default=['Au'],
        help=
        "a list of N chemical species, which defines a mapping between atom types in LAMMPS to the available species in the OpenKIM model"
    )
    parser.add_argument(
        "--min_style",
        default="cg",
        help="which algorithm will be used for minimization from lammps")
    parser.add_argument("--minimize",
                        type=float,
                        nargs=4,
                        default=[1.0e-4, 1.0e-6, 100, 1000],
                        help="minimization parameters")
    parser.add_argument("--up",
                        type=float,
                        default=1.0e-6,
                        help="the deformation magnitude (in strain units)")
    args = parser.parse_args()

    L = PyLammps()

    L.units("metal")

    # Define the finite deformation size.
    #Try several values to verify that results do not depend on it.
    L.variable("up equal {}".format(args.up))

    # Define the amount of random jiggle for atoms. It prevents atoms from staying on saddle points
    atomjiggle = 1.0e-5

    # metal units, elastic constants in GPa
    cfac = 1.0e-4

    # Define minimization parameters
    L.variable("dmax equal 1.0e-2")

    L.boundary("p", "p",
               "p")  # periodic boundary conditions in all three directions
    L.box(
        "tilt large"
    )  # to avoid termination if the final simulation box has a high tilt factor

    # use the OpenKIM model to set the energy interactions
    L.kim("init", args.kim_model, "metal", "unit_conversion_mode")

    L.read_data(args.input_data_file)

    potential(L, args)

    # Need to set mass to something, just to satisfy LAMMPS
    mass_dictionary = {
        'H': 1.00797,
        'He': 4.00260,
        'Li': 6.941,
        'Be': 9.01218,
        'B': 10.81,
        'C': 12.011,
        'N': 14.0067,
        'O': 15.9994,
        'F': 18.998403,
        'Ne': 20.179,
        'Na': 22.98977,
        'Mg': 24.305,
        'Al': 26.98154,
        'Si': 28.0855,
        'P': 30.97376,
        'S': 32.06,
        'Cl': 35.453,
        'K': 39.0983,
        'Ar': 39.948,
        'Ca': 40.08,
        'Sc': 44.9559,
        'Ti': 47.90,
        'V': 50.9415,
        'Cr': 51.996,
        'Mn': 54.9380,
        'Fe': 55.847,
        'Ni': 58.70,
        'Co': 58.9332,
        'Cu': 63.546,
        'Zn': 65.38,
        'Ga': 69.72,
        'Ge': 72.59,
        'As': 74.9216,
        'Se': 78.96,
        'Br': 79.904,
        'Kr': 83.80,
        'Rb': 85.4678,
        'Sr': 87.62,
        'Y': 88.9059,
        'Zr': 91.22,
        'Nb': 92.9064,
        'Mo': 95.94,
        'Tc': 98,
        'Ru': 101.07,
        'Rh': 102.9055,
        'Pd': 106.4,
        'Ag': 107.868,
        'Cd': 112.41,
        'In': 114.82,
        'Sn': 118.69,
        'Sb': 121.75,
        'I': 126.9045,
        'Te': 127.60,
        'Xe': 131.30,
        'Cs': 132.9054,
        'Ba': 137.33,
        'La': 138.9055,
        'Ce': 140.12,
        'Pr': 140.9077,
        'Nd': 144.24,
        'Pm': 145,
        'Sm': 150.4,
        'Eu': 151.96,
        'Gd': 157.25,
        'Tb': 158.9254,
        'Dy': 162.50,
        'Ho': 164.9304,
        'Er': 167.26,
        'Tm': 168.9342,
        'Yb': 173.04,
        'Lu': 174.967,
        'Hf': 178.49,
        'Ta': 180.9479,
        'W': 183.85,
        'Re': 186.207,
        'Os': 190.2,
        'Ir': 192.22,
        'Pt': 195.09,
        'Au': 196.9665,
        'Hg': 200.59,
        'Tl': 204.37,
        'Pb': 207.2,
        'Bi': 208.9804,
        'Po': 209,
        'At': 210,
        'Rn': 222,
        'Fr': 223,
        'Ra': 226.0254,
        'Ac': 227.0278,
        'Pa': 231.0359,
        'Th': 232.0381,
        'Np': 237.0482,
        'U': 238.029
    }
    for itype in range(1, len(args.elements) + 1):
        L.mass(itype, mass_dictionary.get(args.elements[itype - 1], 1.0e-20))

    # Compute initial state at zero pressure
    L.fix(3, "all", "box/relax", "aniso", 0.0)
    L.min_style(args.min_style)
    L.minimize(args.minimize[0], args.minimize[1], int(args.minimize[2]),
               int(args.minimize[3]))

    L.variable("lx0 equal {}".format(L.eval("lx")))
    L.variable("ly0 equal {}".format(L.eval("ly")))
    L.variable("lz0 equal {}".format(L.eval("lz")))

    # These formulas define the derivatives w.r.t. strain components
    L.variable("d1 equal -(v_pxx1-{})/(v_delta/v_len0)*{}".format(
        L.eval("pxx"), cfac))
    L.variable("d2 equal -(v_pyy1-{})/(v_delta/v_len0)*{}".format(
        L.eval("pyy"), cfac))
    L.variable("d3 equal -(v_pzz1-{})/(v_delta/v_len0)*{}".format(
        L.eval("pzz"), cfac))
    L.variable("d4 equal -(v_pyz1-{})/(v_delta/v_len0)*{}".format(
        L.eval("pyz"), cfac))
    L.variable("d5 equal -(v_pxz1-{})/(v_delta/v_len0)*{}".format(
        L.eval("pxz"), cfac))
    L.variable("d6 equal -(v_pxy1-{})/(v_delta/v_len0)*{}".format(
        L.eval("pxy"), cfac))

    L.displace_atoms("all", "random", atomjiggle, atomjiggle, atomjiggle,
                     87287, "units box")

    # Write restart
    L.unfix(3)
    L.write_restart("restart.equil")

    for idir in range(1, 7):
        displace(L, args, idir)

    postprocess_and_output(L)
    return
Exemplo n.º 13
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)