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
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)
#!/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()
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") L.fix("thermofix", "clustergr", "langevin", Temp, Temp, 0.1, 12345, "zero", "yes") # does not perform time integration ! L.fix("nveintegration", "clustergr", "nve") # move only cluster atoms L.timestep(0.002) starttime = time.time() L.run(50000) print("dt at start: {} fs".format(L.eval("dt") * 1000))
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
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)
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"