def __initLAMMPS__(self, inputFilename=None, logFilename=None, verbose = False): """Initialize a LAMMPS object using the provided input file. Parameters ----------------------- inputFilename : string (None) Path to input file. logFilename : string (None) Path to log file. verbose : bool If true, write output to standard out. """ try: from lammps import lammps except: print "ERROR: The LAMMPS python interface could not be found. Check your PYTHONPATH and compiled LAMMPS directory to make sure it is compiled and importable." # check to see we are handing an absolute pathname. if not os.path.isabs(inputFilename): inputFilename = os.path.abspath(inputFilename) # we're going to assume here that the user is taking care of the fact that LAMMPS needs to know where to find things but we will issue a worning in case they aren't. if os.path.dirname(inputFilename) != os.getcwd(): print "WARNING: Getting lammps input file from directory other than current working directory. Be sure pathnames are correct in input files." # initialize the lammps object if verbose == True: self.lmp=lammps() #self.lmp = lammps("", ["-c", "on", "-sf", "cuda"]) else: args = ["-sc", "none", "-echo", "none", "-log", "none"] self.lmp = lammps("", args) # after the lammps object is created, initialize the lammps simulation. # specify general log file parameters #self.command("echo none") # write out log file if needed if logFilename is not None: if not os.path.isabs(logFilename): logFilename = os.path.abspath(logFilename) self.command("log " + logFilename) else: self.command("log none") # if there is a specified filename, use it to set up the simulation. if inputFilename != None: #self.command("log " + logFilename) self.lmp.file(inputFilename) #self.__setupLAMMPS__(filename) return self.lmp
def lammpsGenerateE(vaspPOSCAR, preCmd, postCmd, vRatio): # Convert to lammps input configure format, rescale accordingly lammpsConfig = "lmp.config" lammpsPOSCAR = "POSCAR_eos" shutil.copyfile(vaspPOSCAR, lammpsPOSCAR) poscarGrow.poscarGrow(lammpsPOSCAR, lammpsPOSCAR, 3, 3, 3) poscarVolume.ratio(lammpsPOSCAR, vRatio) poscar2lmpcfg.poscar2dump(lammpsPOSCAR, lammpsConfig) # Run lammps lmp = lammps.lammps() print "here" map(lambda x: lmp.command(x), preCmd) lmp.command("read_data %s" % lammpsConfig) map(lambda x: lmp.command(x), postCmd) # Grab data from LAMMPS natom = lmp.get_natoms() pe = lmp.extract_compute("thermo_pe", 0, 0) / natom prs = lmp.extract_compute("thermo_press", 0, 0) * bars2GPa vol = lmp.extract_variable("v", 0, 0) / natom os.remove(lammpsConfig) os.remove(lammpsPOSCAR) return pe, prs, vol
def __init__(self,init_file,datafile,dumpfile,temp,max_disp=1.0,type_lengths=(5,13),numtrials=5,anchortype=2,restart=False,parallel=False): dname = os.path.dirname(os.path.abspath(init_file)) print "Configuration file is "+str(init_file) print 'Directory name is '+dname os.chdir(dname) self.lmp = lammps("",["-echo","none","-screen","lammps.out"]) self.lmp.file(os.path.abspath(init_file)) #if parrallel: # pool = mpc.Pool() # self.lmp_clones = pool.map(self.clone_lammps,range(numtrials)) # pool.close() self.molecules = mol.constructMolecules(datafile) self.atomlist = self.get_atoms() self.lmp.command("thermo 1") self.lmp.command("thermo_style custom step etotal ke temp pe ebond eangle edihed eimp evdwl ecoul elong press") self.temp = temp self.dumpfile = os.path.abspath(dumpfile) self.datafile = os.path.abspath(datafile) self.init_file = os.path.abspath(init_file) self.exclude=False self.initializeGroups(self.lmp) self.initializeComputes(self.lmp) self.initializeFixes(self.lmp) self.initializeMoves(anchortype,max_disp,type_lengths,numtrials,parallel) self.initialize_data_files(restart) self.step=0 if not restart else self.get_last_step_number() self.update_neighbor_list()
def preparelammps(self,pair_style=None,pair_coeff=None,x_interface=0.5,w_interface=3.0): restartfile=self.restartfile self.lmp=lammps() self.lmp.command("atom_modify map hash") self.lmp.command('read_restart '+restartfile+' remap') if pair_style is not None: self.lmp.command('pair_style '+pair_style) if pair_coeff is not None: self.lmp.command('pair_coeff '+pair_coeff) self.lmp.command("fix NVE all nve") xlo=self.lmp.extract_global("boxxlo",1) xhi=self.lmp.extract_global("boxxhi",1) print "Box is [%f,%f]." % (xlo, xhi) # The position of the interface, at the middle by default (0.5) x_interface=(xlo+xhi)*x_interface xmax=x_interface+w_interface xmin=x_interface-w_interface self.lmp.command("region middle block %f %f INF INF INF INF" % (xmin,xmax)) self.lmp.command("group interface region middle") self.lmp.command("compute fxs interface property/atom fx") self.lmp.command("compute fys interface property/atom fy") self.lmp.command("compute fzs interface property/atom fz") # Coordinates ordered by atom ID coords_data=self.lmp.gather_atoms("x",1,3) # Coordinates in a numpy array coords=np.array(coords_data[:],dtype=np.dtype('f8')) self.natoms=self.lmp.extract_global("natoms",0) coords=np.reshape(coords,(self.natoms,3)) # X-coordinates in a Numpy array xs=coords[:,0] # Atom on the left side? mask_left=np.logical_and(xs<x_interface,xs>xmin) # Atom on the right side? mask_right=np.logical_and(xs>x_interface,xs<xmax) # Note that these indices differ from atom IDs by a factor of one self.inds_left=np.where(mask_left)[0] self.inds_right=np.where(mask_right)[0] # All atom indices sorted by atom ID, duplicates removed inds_interface=np.unique(np.concatenate((self.inds_left,self.inds_right))) # Where are the atoms of the left atom set self.ids_L=np.in1d(inds_interface,self.inds_left) self.ids_L=np.where(self.ids_L)[0] # Atoms of the right set self.ids_R=np.in1d(inds_interface,self.inds_right) self.ids_R=np.where(self.ids_R)[0]
def start_lammps(self): # start lammps process if self.parameters.log_file is None: cmd_args = ['-echo', 'log', '-log', 'none', '-screen', 'none', '-nocite'] else: cmd_args = ['-echo', 'log', '-log', self.parameters.log_file, '-screen', 'none','-nocite'] self.cmd_args = cmd_args if not hasattr(self, 'lmp'): self.lmp = lammps(self.parameters.lammps_name, self.cmd_args, comm=self.parameters.comm) # Use metal units: Angstrom, ps, and eV for cmd in self.parameters.lammps_header: self.lmp.command(cmd) for cmd in self.parameters.lammps_header: if "units" in cmd: self.units = cmd.split()[1] if hasattr(self.parameters, "lammps_header_extra") and self.parameters.lammps_header_extra is not None: for cmd in self.parameters.lammps_header_extra: self.lmp.command(cmd) self.started=True
def reax_potential_energy(atoms, FF="ffield.reax.mitch"): """ Perform a single point LAMMPS calculation returns the potential energy""" lmp = lammps(cmdargs=["-sc", "none", "-l", "none"]) lmp.command("units real") lmp.command("atom_style charge") lmp.command("box tilt large") pbc = ["f", "f", "f"] for i, bc in enumerate(atoms.get_pbc()): if bc: pbc[i] = "p" lmp.command("boundary {0} {1} {2}".format(pbc[0], pbc[1], pbc[2])) atoms2lammps(atoms) lmp.command("read_data data.atoms") lmp.command("pair_style reax/c NULL") lmp.command("pair_coeff * * {0} Au".format(FF)) lmp.command("fix 1 all qeq/reax 1 0.0 10.0 1e-6 reax/c") lmp.command("variable nrg equal pe/23.06035") lmp.command("run 0") nrg = lmp.extract_variable("nrg", None, 0) lmp.close() os.unlink("log.cite") os.unlink("data.atoms") return nrg
def __init__(self, fn_lmp): # Load all LAMMPS commands lammps_in = open(fn_lmp).read().splitlines() self._lammps_in = lammps_in # Neighbor lists checked at every step lammps_in.append('neigh_modify delay 0 every 1 check yes') # Instantiate lmp = lammps.lammps(cmdargs=['-screen','none','-log','none']) self._lmp = lmp # Command execution for cmd in self._lammps_in: lmp.command(cmd) # Gather some constants natoms = lmp.get_natoms() self.natoms = natoms N = 3 * natoms self.N = N # Ctypes array for LAMMPS position data self._x_c = (N * ct.c_double)() self._dV_dx = (N * ct.c_double)()
def make_grain_prototypes(se,lt): #OK what types of defects, FCC full, partial, BCC full... strain and thermalize DOUT={} tdict={se.grain_names[0]:'fcc_GB',\ se.grain_names[1]:'bcc_GB'} for gn in se.grain_names: template=lt.adjust_temp_read(se.lattice,gn+'.struct',gn,athermal=True) with open('temp.in', 'w') as f: f.write(template) f.write('\nrun 0 post no\n') lmp=lammps() lmp.file('temp.in') lmp.close() check=run_ovitos('CNA',gn+'.struct',gn+'CNAOUT') lil_d={gn+'CNAOUT':tdict[gn]} if tdict[gn].find('fcc')!=-1: lil_cond={gn+'CNAOUT':['CNA',1]} elif tdict[gn].find('bcc')!=-1: lil_cond={gn+'CNAOUT':['CNA',3]} DOUT[gn]=initialize_dislocation_descriptors(gn+'CNAOUT',lil_d,lil_cond) DOUT[gn].index=DOUT[gn]['PID'] print "\n\n\n FINISHED GRAIN BOUNDARY PROTOTYPES \n\n\n" return DOUT
def Run_Dihedral_Scan( Molecule, File_List): Energy = [] for file in File_List: file = open(file, 'r') file = file.readlines() i = 0 for line in file: try: line = line.split() coords = np.array([float(line[1]), float(line[2]), float(line[3])]) Molecule.Atom_List[i].Position = coords i += 1 except: continue D_Sys = System.System([Molecule], [1], 100.0, "Dihedral") D_Sys.Gen_Rand() D_Sys.Write_LAMMPS_Data( Dihedral=True) os.system("cp %sin.Dihedral_Energy ./" % Configure.Template_Path) lmp = lammps() lmp.file("in.Dihedral_Energy") Output_File = open("log.lammps", 'r') Output_File = Output_File.readlines() for Line in Output_File: try: if len(Line.split()) == 2 and float(Line.split()[0]) == float(Line.split()[1]): Energy.append(float(Line.split()[0])) except: continue Energy = np.asarray(Energy) return Energy- Energy[0]
def clone_lammps(self): lmp2 = lammps("",["-echo","none","-screen","lammps.out"]) lmp2.file(os.path.abspath(self.init_file)) lmp2.command("thermo 1") lmp2.command("thermo_style custom step etotal ke temp pe ebond eangle edihed eimp evdwl ecoul elong press") self.initializeGroups(lmp2) self.initializeComputes(lmp2) self.initializeFixes(lmp2) return(lmp2)
def surfaces(se,alld,descriptors,dic,DOUT,lt): need_proto=False #DOUT={} for stru in se.structs: for i in se.indicies: for bound in se.bounds: for s in se.scales: box=get_boxes(s) for b in box: # we only need to check one [100] face!! if i[dic[bound]]==[0,1,0] or i[dic[bound]]==[0,0,1]: break for t in range(se.thermal): lx=se.lattice*np.sqrt(i[0][0]**2+i[0][1]**2+i[0][2]**2) ly=se.lattice*np.sqrt(i[1][0]**2+i[1][1]**2+i[1][2]**2) lz=se.lattice*np.sqrt(i[2][0]**2+i[2][1]**2+i[2][2]**2) if random.random() < se.sampling_rate: fiz='example'+'_'+stru+str(random.randint(0,10000)) else: fiz='temporaryfile' template=lt.adjust_temp(se.lattice,lx,ly,lz,i[0],i[1],i[2],bound,stru,fiz) with open('temp.in', 'w') as f: f.write(template) f.write('\nchange_box all '+b+' boundary '+bound+' remap units box\n') f.write('\nrun 0 post no\n') lmp=lammps() try: lmp.file('temp.in') temp=nab_bispec_train(fiz) #alld=alld.append(temp) except: print "\nFAILURE TO RUN LAMMPS." lmp.close() # we need the number of atoms, the bounds (to tell which is periodic), the orientations, and the structure #descriptors.append([i,s,b,t,bound,len(temp)]) if i == se.indicies[1]: strang='1 0 0' else: strang=str(i[dic[bound]]) print '\n'+strang+' '+stru temp.index=temp['id'] temp['desc']=DOUT[(stru,tuple(i[dic[bound]]))]['desc'] alld=alld.append(temp) return alld
def __init__(self, input_file_ = None, verbose_ = False): if input_file_ == None: print "Lammps input file not defined." exit() else: print "Using "+input_file_ if verbose_: self.lmp = lammps() else: lammps_commands = ["-screen", "none", "-log", "none"] self.lmp = lammps("", lammps_commands) if os.path.isfile(input_file_): self.lmp.file(input_file_) else: print "Cannot find input file "+input_file_ self.atom_system = atoms(self.lmp, input_file_ = input_file_) self.lmp.command("run 0 post no") self.lmp.command("variable e equal pe") self.atom_system.positions = self.lmp.extract_atom("x", 3) self.radius = get_radius(self.lmp)/100. print self.radius
def make_surface_prototypes(se,alld,dic,lt): DOUT={} tdict={(se.structs[0],tuple(se.indicies[0][0])):'fcc_111',\ (se.structs[0],tuple(se.indicies[0][1])):'fcc_110',\ (se.structs[0],tuple(se.indicies[0][2])):'fcc_112',\ (se.structs[0],tuple(se.indicies[1][2])):'fcc_100',\ (se.structs[1],tuple(se.indicies[0][0])):'bcc_111',\ (se.structs[1],tuple(se.indicies[0][1])):'bcc_110',\ (se.structs[1],tuple(se.indicies[0][2])):'bcc_112',\ (se.structs[1],tuple(se.indicies[1][2])):'bcc_100'} counter=0 for stru in se.structs: for i in se.indicies: for bound in se.bounds: if i[dic[bound]]==[0,1,0] or i[dic[bound]]==[0,0,1]: break lx=se.lattice*np.sqrt(i[0][0]**2+i[0][1]**2+i[0][2]**2) ly=se.lattice*np.sqrt(i[1][0]**2+i[1][1]**2+i[1][2]**2) lz=se.lattice*np.sqrt(i[2][0]**2+i[2][1]**2+i[2][2]**2) fiz='tempstruct_'+str(counter) counter+=1 template=lt.adjust_temp_athermal(se.lattice,lx,ly,lz,i[0],i[1],i[2],bound,stru,fiz) with open('temp.in', 'w') as f: f.write(template) f.write('\nrun 0 post no\n') lmp=lammps() try: lmp.file('temp.in') temp=nab_bispec_train(fiz) alld=alld.append(temp) except: print "\nFAILURE TO RUN LAMMPS." lmp.close() #get the CNA parameters from ovito check=run_ovitos('CNA',fiz,fiz+'CNAOUT') lil_d={fiz+'CNAOUT':tdict[(stru,tuple(i[dic[bound]]))]} if stru=='fcc': lil_cond={fiz+'CNAOUT':['CNA',1]} elif stru=='bcc': lil_cond={fiz+'CNAOUT':['CNA',3]} DOUT[(stru,tuple(i[dic[bound]]))]=initialize_dislocation_descriptors(fiz+'CNAOUT',lil_d,lil_cond) #reset the index to the atomic IDs for the merge with the bispec data DOUT[(stru,tuple(i[dic[bound]]))].index=DOUT[(stru,tuple(i[dic[bound]]))]['PID'] #need_proto=False print "\n\n\n FINISHED SURFACE PROTOTYPES \n\n\n" return DOUT
def make_interstitial_prototypes(se,alld,dic,lt): #dictionary of prototype features DOUT={} ot={0:'tetrahedral',1:'octahedral'} tdict={(se.structs[0],ot[0]):'fcc_tet_interstitial',\ (se.structs[0],ot[1]):'fcc_oct_interstitial',\ (se.structs[1],ot[0]):'bcc_tet_interstitial',\ (se.structs[1],ot[1]):'bcc_oct_interstitial'} counter=0 i = se.indicies[1] #standard cell for stru in se.structs: c=0 for inter in se.interstitial[stru]: lx=se.lattice*np.sqrt(i[0][0]**2+i[0][1]**2+i[0][2]**2) ly=se.lattice*np.sqrt(i[1][0]**2+i[1][1]**2+i[1][2]**2) lz=se.lattice*np.sqrt(i[2][0]**2+i[2][1]**2+i[2][2]**2) fiz='tempstruct_'+str(counter) counter+=1 template=lt.adjust_temp_athermal(se.lattice,lx,ly,lz,i[0],i[1],i[2],'p p p',stru,fiz) with open('temp.in', 'w') as f: f.write(template) f.write('\ncreate_atoms 1 single '+str(inter[0])+' '+str(inter[1])+' '+str(inter[2])) f.write('\nrun 0 post no\n') lmp=lammps() try: lmp.file('temp.in') temp=nab_bispec_train(fiz) except: print "\nFAILURE TO RUN LAMMPS." lmp.close() #make a prototype if needed check=run_ovitos('CNA',fiz,fiz+'CNAOUT') lil_d={fiz+'CNAOUT':tdict[(stru,ot[c])]} if stru=='fcc': lil_cond={fiz+'CNAOUT':['CNA',1]} elif stru=='bcc': lil_cond={fiz+'CNAOUT':['CNA',3]} DOUT[(stru,ot[c])]=initialize_dislocation_descriptors(fiz+'CNAOUT',lil_d,lil_cond) #reset the index to the atomic IDs for the merge with the bispec data DOUT[(stru,ot[c])].index=DOUT[(stru,ot[c])]['PID'] c+=1 #need_proto=False print "\n\n\n FINISHED INTERSTITIAL PROTOTYPES \n\n\n" return DOUT
def grain_boundaries(se,alld,DOUT,lt): for gn in se.grain_names: template=lt.adjust_temp_read(se.lattice,'temporary.out',gn) with open('temp.in', 'w') as f: f.write(template) f.write('\nrun 0 post no\n') lmp=lammps() lmp.file('temp.in') temp=nab_bispec_train('temporary.out') lmp.close() # we need the number of atoms, the structure, flag for the type of intersitial print '\n'+gn temp.index=temp['id'] temp['desc']=DOUT[gn]['desc'] alld=alld.append(temp) return alld
def interstitials(se,alld,descriptors,DOUT,lt): ot={0:'tetrahedral',1:'octahedral'} for stru in se.structs: c=0 for inter in se.interstitial[stru]: for s in se.scales: box=get_boxes(s) for b in box: for t in range(se.thermal): lx=se.lattice ly=se.lattice lz=se.lattice if random.random() < se.sampling_rate: fiz='keep_'+ot[c]+'interstitial_'+stru+str(random.randint(0,10000)) else: fiz='temporaryfile' template=lt.adjust_temp(se.lattice,lx,ly,lz,[1,0,0],[0,1,0],[0,0,1],'p p p',stru,fiz) with open('temp.in', 'w') as f: f.write(template) f.write('\ncreate_atoms 1 single '+str(inter[0])+' '+str(inter[1])+' '+str(inter[2])) f.write('\nchange_box all '+b+' boundary '+'p p p'+' remap units box\n') f.write('\nrun 0 post no\n') lmp=lammps() try: lmp.file('temp.in') temp=nab_bispec_train(fiz) #alld=alld.append(temp) except: print "\nFAILURE TO RUN LAMMPS." lmp.close() # we need the number of atoms, the structure, flag for the type of intersitial print '\n'+ot[c]+'interstitial '+stru temp.index=temp['id'] temp['desc']=DOUT[(stru,ot[c])]['desc'] alld=alld.append(temp) c+=1 return alld
def make_vacancy_prototypes(se,alld,dic,lt): #dictionary of prototype features DOUT={} dcheck={se.structs[0]:False,se.structs[1]:False} tdict={se.structs[0]:'fcc_vacancy',se.structs[1]:'bcc_vacancy'} counter=0 i = se.indicies[1] #standard cell for stru in se.structs: lx=se.lattice*np.sqrt(i[0][0]**2+i[0][1]**2+i[0][2]**2) ly=se.lattice*np.sqrt(i[1][0]**2+i[1][1]**2+i[1][2]**2) lz=se.lattice*np.sqrt(i[2][0]**2+i[2][1]**2+i[2][2]**2) fiz='tempstruct_'+str(counter) counter+=1 template=lt.adjust_temp_athermal(se.lattice,lx,ly,lz,i[0],i[1],i[2],'p p p',stru,fiz) with open('temp.in', 'w') as f: f.write(template) f.write('\n group g1 id 1') f.write('\n delete_atoms group g1') f.write('\nrun 0 post no\n') lmp=lammps() try: lmp.file('temp.in') temp=nab_bispec_train(fiz) #alld=alld.append(temp) except: print "\nFAILURE TO RUN LAMMPS." lmp.close() #make a prototype if needed #if need_proto==True: check=run_ovitos('CNA',fiz,fiz+'CNAOUT') lil_d={fiz+'CNAOUT':tdict[stru]} if stru=='fcc': lil_cond={fiz+'CNAOUT':['CNA',1]} elif stru=='bcc': lil_cond={fiz+'CNAOUT':['CNA',3]} DOUT[stru]=initialize_dislocation_descriptors(fiz+'CNAOUT',lil_d,lil_cond) #reset the index to the atomic IDs for the merge with the bispec data DOUT[stru].index=DOUT[stru]['PID'] #need_proto=False print "\n\n\n FINISHED VACANCY PROTOTYPES \n\n\n" return DOUT
def loop(N,cut0,thresh,lmpptr): print "LOOP ARGS",N,cut0,thresh,lmpptr from lammps import lammps lmp = lammps(ptr=lmpptr) natoms = lmp.get_natoms() for i in range(N): cut = cut0 + i*0.1 lmp.set_variable("cut",cut) # set a variable in LAMMPS lmp.command("pair_style lj/cut ${cut}") # LAMMPS command #lmp.command("pair_style lj/cut %d" % cut) # LAMMPS command option lmp.command("pair_coeff * * 1.0 1.0") # ditto lmp.command("run 10") # ditto pe = lmp.extract_compute("thermo_pe",0,0) # extract total PE from LAMMPS print "PE",pe/natoms,thresh if pe/natoms < thresh: return
def vacancies(se, alld, descriptors,DOUT,lt): #loops to create all of the vacancies for stru in se.structs: for s in se.scales: box=get_boxes(s) for b in box: for t in range(se.thermal): lx=se.lattice ly=se.lattice lz=se.lattice if random.random() < se.sampling_rate: fiz='vacancy_'+stru+str(random.randint(0,10000)) else: fiz='temporaryfile' template=lt.adjust_temp(se.lattice,lx,ly,lz,[1,0,0],[0,1,0],[0,0,1],'p p p',stru,fiz) with open('temp.in', 'w') as f: f.write(template) f.write('\n group g1 id 1') f.write('\n delete_atoms group g1') f.write('\nchange_box all '+b+' boundary '+'p p p'+' remap units box\n') f.write('\nrun 0 post no\n') lmp=lammps() try: lmp.file('temp.in') temp=nab_bispec_train(fiz) #alld=alld.append(temp) except: print "\nFAILURE TO RUN LAMMPS." lmp.close() # we need the number of atoms, the structure, flag that it's a vacancy print '\n'+'vacancy '+stru temp.index=temp['id'] temp['desc']=DOUT[stru]['desc'] alld=alld.append(temp) return alld
def add_tensile_dislocations(se,alld,DOUT,lt): for x in range(1,4): #for t in range(se.thermal): template=lt.adjust_temp_read(se.lattice,'temporary.out','tensile_'+str(x)+'.out',athermal=True) with open('temp.in', 'w') as f: f.write(template) f.write('\nrun 0 post no\n') lmp=lammps() lmp.file('temp.in') temp=nab_bispec_train('temporary.out') lmp.close() # we need the number of atoms, the structure, flag for the type of intersitial print '\n tensile dislocation run '+str(x) temp.index=temp['id'] temp['desc']=DOUT[x]['desc'] alld=alld.append(temp) return alld
def __init__(self, use_internal_interface=False, **kwargs): """Constructor. Parameters ---------- engine_type : EngineType type of engine use_internal_interface : bool, optional If true, then the internal interface (library) is used when communicating with LAMMPS, if false, then file-io interface is used where input/output files are used to communicate with LAMMPS """ self.boundary_condition = DataContainer() self.BC = self.boundary_condition self.computational_model = DataContainer() self.CM = self.computational_model self.solver_parameters = DataContainer() self.SP = self.solver_parameters self.cuds_sd = kwargs.get('cuds', CUDS()) self.SD = self.cuds_sd self._use_internal_interface = use_internal_interface self._script_writer = ScriptWriter(AtomStyle.ATOMIC) if self._use_internal_interface: import lammps self._lammps = lammps.lammps(cmdargs=["-log", "none"]) self._data_manager = LammpsInternalDataManager(self._lammps, self.cuds_sd, AtomStyle.ATOMIC) else: self._data_manager = LammpsFileIoDataManager(self.cuds_sd, AtomStyle.ATOMIC) # Number of runs self._run_count = 0 # Dataset uids which are added. self._dataset_uids = [] # Call the base class in order to load CUDS super(LammpsWrapper, self).__init__(**kwargs)
def initialise(self, data): """builds a lammps instance, and sets up the simulation based on the data provided - called automatically if data is provided to the constructor.""" self.data = data if (self.lmp == None): args = ['-log', 'none'] if not self.show_lammps_output: args.extend(['-screen', 'none']) self.lmp = lammps.lammps(cmdargs=args) commands = self.commands_from_script(self._build_init()) self._run_commands(commands) self.add_particles(self.data['elements'], already_in_array=True) self.constants_modified() self.timesteps_run = [0]
def tensile_prototype(se,lt): DOUT={} # we have 3 tensile tests right now for x in range(1,4): template=lt.adjust_temp_read(se.lattice,'tensile_'+str(x)+'.struct','tensile_'+str(x)+'.out',athermal=True) with open('temp.in', 'w') as f: f.write(template) f.write('\nrun 0 post no\n') lmp=lammps() lmp.file('temp.in') lmp.close() check=run_ovitos('CNA','tensile_'+str(x)+'.struct','tensile_'+str(x)+'CNAOUT') lil_d={'tensile_'+str(x)+'CNAOUT':'fcc_partial_disloc'} lil_cond={'tensile_'+str(x)+'CNAOUT':['CNAonly',2]} DOUT[x]=initialize_dislocation_descriptors('tensile_'+str(x)+'CNAOUT',lil_d,lil_cond) DOUT[x].index=DOUT[x]['PID'] print "\n\n\n FINISHED TENSILE PROTOTYPES \n\n\n" return DOUT
def __init__(self, domain_size, nr_of_atom_types=1, lj_eps=0.001, boundaries="p p", verbose=False): self._domain_size = domain_size self._nr_of_atom_types = nr_of_atom_types self._verbose=verbose self._lammps_id_counter = 0 cmdargs = ["-pk", "omp", "4", "-sf", "omp"] if not verbose: cmdargs += ['-screen', 'none'] self._lammps = lammps(cmdargs=cmdargs) self._lj_eps = lj_eps commands = """ dimension 2 boundary {boundaries} p atom_style atomic neighbor 0.6 bin # <skin> <style> neigh_modify delay 2 region r_whole_domain block 0 {domain_size[0]} 0 {domain_size[1]} -0.1 0.1 create_box {nr_of_atom_types} r_whole_domain pair_style lj/cut 1.2246 timestep 0.1 fix f_time_integration all nve fix f_enforce_2d all enforce2d #compute myke all ke #compute mype all pe #variable myte equal "c_myke + c_mype" thermo 10000 #thermo_style custom c_myke c_mype v_myte #thermo_modify lost ignore flush yes """ self._run_lammps(commands.format(domain_size=domain_size, nr_of_atom_types=nr_of_atom_types, boundaries=boundaries)) self._atom_type_info = [None] * nr_of_atom_types for i in range(nr_of_atom_types): self._atom_type_info[i] = {'mass': 1.0, 'radius': 1.0}
def make_into_bispec( fn, latt, se, clfdict, clf, expected_struct="fcc", frame=0, bounds="p p p", multiframe=False, stendframe=[0, 0], outfilename="output", ): # turns a lammps dump into bispec components # we convert everything to Cu lattice parameter scaling for now if stendframe[1] == 0: final = 1 else: final = stendframe[1] for x in range(stendframe[0], final, 100): if multiframe == False: x = frame b = [8.0960598, 71.3280029, 0.0, 22.0, -51.1679993, 57.1920013] template = get_former_dump(se.lattice, "temporaryfile.out", fn, x, b, bounds) with open("temp.in", "w") as f: f.write(template) f.write( "\nchange_box all " + get_boxesf(1.0, se.lattice / latt) + " boundary " + bounds + " remap units box\n" ) f.write("\nrun 0 post no\n") lmp = lammps() lmp.file("temp.in") lmp.close() dat, output, trans, tdata, preds, cd = nab_and_format_bispec("temporaryfile.out", clfdict, expected_struct, clf) make_output("temporaryfile.out", dat, output, outfilename, append=multiframe) return dat, output, trans, tdata, preds, cd
def dislocations(se,alld,descriptors,DOUT,lt): #OK what types of defects, FCC full, partial, BCC full... strain and thermalize for d in se.defect_names: for s in se.scales: box=get_boxes(s) for b in box: for t in range(se.thermal): lx=se.lattice ly=se.lattice lz=se.lattice if random.random() < se.sampling_rate: fiz='dislocation'+d+str(random.randint(0,10000)) else: fiz='temporaryfile' template=lt.adjust_temp_read(se.lattice,fiz,d) with open('temp.in', 'w') as f: f.write(template) f.write('\nchange_box all '+b+' boundary '+'p p p'+' remap units box\n') f.write('\nrun 0 post no\n') lmp=lammps() try: lmp.file('temp.in') temp=nab_bispec_train(fiz) #alld=alld.append(temp) except: print "\nFAILURE TO RUN LAMMPS." lmp.close() # we need the number of atoms, the structure, flag for the type of intersitial print '\n'+d+'dislocation ' temp.index=temp['id'] temp['desc']=DOUT[d]['desc'] alld=alld.append(temp) return alld
from __future__ import division import numpy as np import matplotlib.pyplot as plt from lammps import lammps from mpi4py import MPI from pylab import * import random import sys """ This script is to sample the initial condition for transition probability calculation. Input file has the first argument for the starting point, and second argument is the size of sampling pool. """ pol = lammps(cmdargs=["-sc", "none"]) pol.file("in.ljwall") start = eval(sys.argv[1]) size = eval(sys.argv[2]) monomer = eval(sys.argv[3]) init_x = [] init_v = [] init_t = [] i = 0 pol.command("run 0 pre no post no") com_current = pol.extract_compute("com", 0, 1)[0] left = com_current < start while i < size: com_current = pol.extract_compute("com", 0, 1)[0] if com_current > start and left: x_current = pol.gather_atoms("x", 1, 3) v_current = pol.gather_atoms("v", 1, 3) init_x.append(x_current[:3 * monomer]) init_v.append(v_current[:3 * monomer])
def testExternalArray(self): """Test fix external from Python with pf/array""" machine = None if 'LAMMPS_MACHINE_NAME' in os.environ: machine = os.environ['LAMMPS_MACHINE_NAME'] lmp = lammps(name=machine, cmdargs=['-nocite', '-log', 'none', '-echo', 'screen']) # a few commands to set up simple system basic_system = """lattice sc 1.0 region box block -1 1 -1 1 -1 1 create_box 1 box create_atoms 1 box mass 1 1.0 pair_style zero 0.1 pair_coeff 1 1 velocity all set 0.1 0.0 -0.1 fix 1 all nve fix ext all external pf/array 1 fix_modify ext energy yes virial yes thermo_style custom step temp pe ke press thermo 5 """ lmp.commands_string(basic_system) force = lmp.fix_external_get_force("ext") nlocal = lmp.extract_setting("nlocal") for i in range(nlocal): force[i][0] = 0.0 force[i][1] = 0.0 force[i][2] = 0.0 lmp.fix_external_set_energy_global("ext", 0.5) lmp.fix_external_set_virial_global("ext", [0.5, 0.5, 0.5, 0.0, 0.0, 0.0]) lmp.command("run 5 post no") self.assertAlmostEqual(lmp.get_thermo("temp"), 4.0 / 525.0, 14) self.assertAlmostEqual(lmp.get_thermo("pe"), 1.0 / 16.0, 14) self.assertAlmostEqual(lmp.get_thermo("press"), 0.06916666666666667, 14) if NUMPY_INSTALLED: npforce = lmp.numpy.fix_external_get_force("ext") self.assertEqual(len(npforce), 8) self.assertEqual(len(npforce[0]), 3) self.assertEqual(npforce[1][1], 0.0) force = lmp.fix_external_get_force("ext") nlocal = lmp.extract_setting("nlocal") for i in range(nlocal): force[i][0] = 6.0 force[i][1] = 6.0 force[i][2] = 6.0 lmp.fix_external_set_energy_global("ext", 1.0) lmp.fix_external_set_virial_global("ext", [1.0, 1.0, 1.0, 0.0, 0.0, 0.0]) lmp.command("run 5 post no") self.assertAlmostEqual(lmp.get_thermo("temp"), 1.0 / 30.0, 14) self.assertAlmostEqual(lmp.get_thermo("pe"), 1.0 / 8.0, 14) self.assertAlmostEqual(lmp.get_thermo("press"), 0.15416666666666667, 14) if NUMPY_INSTALLED: npforce = lmp.numpy.fix_external_get_force("ext") self.assertEqual(npforce[0][0], 6.0) self.assertEqual(npforce[3][1], 6.0) self.assertEqual(npforce[7][2], 6.0)
# Velocity prefactor vf = 1e-4*R*T # LAMMPS units [real units, g A^2 * fs^-2 mol^-1] # Pressure prefactor for volume change move Pb = P*1.01325 # Pressure [bar] Pc = kB*1.0e30*1.0e-5 # Conversion factor [bar A^3 K^-1] Pf = Pb/(Pc*T) # Prefactor for Metropolis criterion [A^-3] #-------------------- Initialization --------------------# # Seed random number generator random.seed(rseed) # Initialize LAMMPS lmp = lammps(name="",cmdargs=["-log","none","-screen","none"]) # Load script/data lmp.file("in.nve") # Set the integration time step lmp.command("timestep %f" % dt) # Define compute for kinetic energy lmp.command("compute thermo_ke all ke") # Get initial system properties natoms = lmp.extract_global("natoms",0) mass = lmp.extract_atom("mass",2) atomid = lmp.gather_atoms("id",0,1) atype = lmp.gather_atoms("type",0,1)
def getidxvar(lmpptr): from lammps import lammps lmp = lammps(ptr=lmpptr) val = lmp.extract_variable("idx") print(val)
def relax_group(lmpcuts, ensemble, group="all", keyword=None, create_velocity=True): """ Relax the group of atoms of the given system. Parameters ---------- lmpcuts : ag_lammps_sim.LmpSim basic settings ensemble : str ("npt" or "nvt") the type of simulation keyword : str or None one of lammps' keywords for npt runs """ lmp = lammps() pylmp = PyLammps(ptr=lmp) lmp.command("log {} append".format(lmpcuts.output_lmplog)) #lmpcuts.use_gpu(lmp, neigh=False) lmp.file(lmpcuts.settings_file) lmp.command("box tilt large") # ignore too tilted boxes lmpcuts.load_system(lmp) lmpcuts.dump(lmp) lmpcuts.thermo(lmp) if lmpcuts.pc_file is not None: lmp.file(lmpcuts.pc_file) # define the atoms that may move during the simulation if group == "all": lmpcuts.fix_hoover(lmp, group, ensemble, keyword) else: lmp.command("group group_1 {}".format(group)) lmpcuts.fix_hoover(lmp, "group_1", ensemble, keyword) lmp.command( "fix ic_prevention all momentum 100 linear 1 1 1 angular rescale") # pre-optimization if lmpcuts.input_lmprst is None: lmp.command("min_style cg") lmp.command("min_modify dmax 0.5") lmp.command("minimize 1.0e-5 1.0e-8 10000 100000") if create_velocity is True: lmp.command( "velocity all create {} {} mom yes rot yes dist gaussian".format( lmpcuts.tstart, np.random.randint(29847587))) lmp.command("run {}".format(lmpcuts.runsteps)) # tidy up before closing lmpcuts.unfix_undump(pylmp, lmp) #lmp.command("reset_timestep 0") lmp.command("write_restart {}".format(lmpcuts.output_lmprst)) lmp.command("clear") # close lammps lmp.close()
def testWithArgs(self): """Create LAMMPS instance with a few arguments""" lmp = lammps(name=self.machine, cmdargs=['-nocite', '-sf', 'opt', '-log', 'none']) self.assertIsNot(lmp.lmp, None) self.assertEqual(lmp.opened, 1)
def lammps_gb(self): """ This function will call lammps to calculate the Gay-Berne potential for a uniaxial ellipsoid Returns: Pandas dataframe with the intermolecular distance and energy for the four configurations """ # no output to screen or file lmp = lammps(cmdargs=["-sc", "none", "-log", "none"]) lmp.command("units lj") lmp.command("boundary p p p") lmp.command("atom_style hybrid molecular ellipsoid") # define the gay berne pair_style lmp.command("pair_style gayberne 1.0 %f %f %f" % (self.nu, self.mu, self.cutoff)) lmp.command("read_data system.data") # define the ellipsoid's shape lmp.command("set type 1 shape %f %f %f" % (self.width, self.width, self.length)) # define initial orientation for the atoms lmp.command("set atom 1 quat 1 0 0 0") lmp.command("set atom 2 quat 1 0 0 0") # Define the gay-berne pair_coeff lmp.command("pair_coeff 1 1 1.0 %f %f %f %f %f %f %f" % (self.sigma, self.X_depth, self.X_depth, self.z_depth, self.X_depth, self.X_depth, self.z_depth)) # function to move the first ellipsoid. direction: 0 is x, 1 is y and 2 # is z. def move_molecule(configuration, direction): """ Function to translate the molecule in the desired direction""" i = 0 pot_tot = [] position = [] i = 0 while i < self.x_range: xc = lmp.gather_atoms("x", 1, 3) lmp.command("run 0") pot = lmp.extract_compute("thermo_pe", 0, 0) pot_tot.append(pot) position.append(xc[direction]) xc[direction] = xc[direction] + 0.01 lmp.scatter_atoms("x", 1, 3, xc) i = i + 1 position = pd.DataFrame( {"MD_" + str(configuration) + "_distance": position}) pot_tot = pd.DataFrame( {"MD_" + str(configuration) + "_energy": pot_tot}) self.df = pd.concat([self.df, position, pot_tot], axis=1) for configuration in self.colors: # reinitialze the position of the first atom lmp.command("set atom 1 x 0 y 0 z 0") if configuration == "ll" or "z": # No rotatio for ll and end configuration lmp.command("set atom 1 quat 1 0 0 0") if configuration == "ll": # move in x direction for side-by-side direction = 0 xc = lmp.gather_atoms("x", 1, 3) # Can be changed if the values are too far from the minimum xc[direction] = xc[direction] + self.width / 1.5 xc = lmp.scatter_atoms("x", 1, 3, xc) move_molecule(configuration, direction) if configuration == "z": # move in the z direction for end-to-end direction = 2 xc = lmp.gather_atoms("x", 1, 3) # Can be changed if the values are too far from the minimum xc[direction] = xc[direction] + self.length / 1.1 xc = lmp.scatter_atoms("x", 1, 3, xc) move_molecule(configuration, direction) if configuration == "T" or "X": # The first ellipsoid is rotated by 90 degree in the x axis lmp.command("set atom 1 quat 1 0 0 90") if configuration == "X": # the first ellipsoid is translated in the x direction direction = 0 xc = lmp.gather_atoms("x", 1, 3) # Can be changed if the values are too far from the minimum xc[direction] = xc[direction] + self.width / 1.5 xc = lmp.scatter_atoms("x", 1, 3, xc) move_molecule(configuration, direction) if configuration == "T": # Translation in the y axis direction = 1 xc = lmp.gather_atoms("x", 1, 3) xc[direction] = xc[direction] + self.length - \ self.width # Can be changed if the values are too far from the minimum xc = lmp.scatter_atoms("x", 1, 3, xc) move_molecule(configuration, direction) # close lammps print("LAMMPS done") return self.df lmp.close()
from mpi4py import MPI comm = MPI.COMM_WORLD me = comm.Get_rank() nprocs = comm.Get_size() # create two subcommunicators if me < nprocs // 2: color = 0 else: color = 1 split = comm.Split(color, key=0) if color == 0: from lammps import lammps lmp = lammps(comm=split) # run infile one line at a time lines = open(infile, 'r').readlines() for line in lines: lmp.command(line) # run 10 more steps # get coords from LAMMPS # change coords of 1st atom # put coords back into LAMMPS # run a single step with changed coords lmp.command("run 10") x = lmp.gather_atoms("x", 1, 3)
from mpi4py import MPI from lammps import lammps lammps = lammps() comm = MPI.COMM_WORLD rank = comm.Get_rank() print("hello", rank, "\n") #x = ForceField_Tersoff("ffield.original") #x.data[0][0][6] = "7.000" #x.data[0][0][9] = "3.000" #x.writeForceField("ffield.tersoff") lammps.file("CompFile.lmp") etersoff = lammps.extract_compute("etersoff", 0, 0) print(etersoff, "\n")
#!/usr/bin/env python # This script finds the optimal a and c lattice parameters for graphite, # using the DRIP-AIREBO potential. # Optimisation parameters are hard-coded for now. import sys from scipy.optimize import minimize from lammps_gen_graphite_drip_airebo import lammps_gen_graphite_drip_airebo # test that the lammps import works try: from lammps import lammps lmp = lammps(cmdargs=["-log", "none", "-nocite", "-screen", "none"]) version = lmp.version() print("LAMMPS version: " + str(version)) lmp.close() # destroy a LAMMPS object except ImportError: print("Error importing LAMMPS, exiting ...") sys.exit() # function that we want to minimise def objective_funtion(params): # get lattice parameters a_const = params[0] c_const = params[1] # hard code the lattice size cells_x = 5
import sys, os, unittest from lammps import lammps, LAMMPS_INT, LMP_STYLE_GLOBAL, LMP_STYLE_LOCAL, \ LMP_STYLE_ATOM, LMP_TYPE_VECTOR, LMP_TYPE_SCALAR, LMP_TYPE_ARRAY, \ LMP_VAR_ATOM from ctypes import c_void_p has_manybody = False try: machine = None if 'LAMMPS_MACHINE_NAME' in os.environ: machine = os.environ['LAMMPS_MACHINE_NAME'] lmp = lammps(name=machine) has_manybody = lmp.has_style("pair", "sw") lmp.close() except: pass try: import numpy NUMPY_INSTALLED = True except ImportError: NUMPY_INSTALLED = False @unittest.skipIf(not NUMPY_INSTALLED, "numpy is not available") class PythonNumpy(unittest.TestCase): def setUp(self): machine = None if 'LAMMPS_MACHINE_NAME' in os.environ: machine = os.environ['LAMMPS_MACHINE_NAME'] self.lmp = lammps(
from mpi4py import MPI comm = MPI.COMM_WORLD me = comm.Get_rank() nprocs = comm.Get_size() # create two subcommunicators if me < nprocs // 2: color = 0 else: color = 1 split = comm.Split(color,key=0) if color == 0: from lammps import lammps lmp = lammps(comm=split) # run infile one line at a time lines = open(infile,'r').readlines() for line in lines: lmp.command(line) # run 10 more steps # get coords from LAMMPS # change coords of 1st atom # put coords back into LAMMPS # run a single step with changed coords lmp.command("run 10") x = lmp.gather_atoms("x",1,3) epsilon = 0.1
dih_cdf_norm = np.hstack((dih_potential[:,0].reshape((dih_cdf.shape[0],1)),dih_cdf_norm.reshape((dih_cdf.shape[0],1)))) max_angle = 0.34906585 max_radius = 1.4 inputfile = 'system.data' (atoms,bonds,angles,dihedrals) = rdlmp.readAll(inputfile) print "Initializing atoms from lmp input file..." natoms = atoms.shape[0] molIDs = atoms[np.where(atoms[:,2]==sulfurID)][:,1] #ddtMols = atoms[np.where(atoms[:,2]==ch3ID)][:,1] #meohMols = atoms[np.where(atoms[:,2]==oxygenID)][:,1] print "Finding molecules..." (ddts,meohs) = initializeMols(atoms,bonds,atomIDs) print "Starting up lammps instance..." lmp = lammps("",["-echo","none","-screen","lammps.out"]) #lmp = lammps("",["-screen","lammps.out"]) #lmp = lammps() print "Running equilibration steps..." lmp.file("system.in") lmp.command("minimize 1.0e-5 1.0e-7 1000 10000") lmp.command("compute pair_pe all pe pair") lmp.command("neigh_modify exclude type 1 1") #lmp.command("compute unique all pe/atom pair") #lmp.command("read_data relaxed.lmp") #lmp.command("run 1") #cont = raw_input("continue?") pe = lmp.extract_compute("thermo_pe",0,0) get_coords(lmp,atoms) coords = lmp.gather_atoms("x",1,3)
def getRandCoords(flag, n_id, rmin, rmax, lmpptr): import random from mpi4py import MPI from lammps import lammps lmp = lammps(ptr=lmpptr) comm = MPI.COMM_WORLD me = comm.Get_rank() nprocs = comm.Get_size() itermax = 100000 natoms = lmp.get_natoms() coords = lmp.gather_atoms("x", 1, 3) typ = lmp.gather_atoms("type", 0, 1) boxlo, boxhi, xy, yz, xz, periodicity, box_change = lmp.extract_box() n_gc = lmp.extract_variable("n_GCMC", 0, 0) iSiDist = lmp.extract_variable( "iSiDist", 0, 0) #addon1 #1:to place new atom such that rmin< disminSi <rmax iNear1 = lmp.extract_variable("iNear1", 0, 0) #addon2.1 #1:to place near Si typeNear1 = lmp.extract_variable("typeNear1", 0, 0) #atom type of Si iNear2 = lmp.extract_variable("iNear2", 0, 0) #addon2.2 #1:to place near Si or Li typeNear2 = lmp.extract_variable("typeNear2", 0, 0) #atom type of Li iparticle = lmp.extract_variable("iparticle", 0, 0) #addon3 #1:to place in particle far_atoms = lmp.extract_variable("far_atoms", 0, 0) far_rfact = lmp.extract_variable("far_rfact", 0, 0) if me == 0: #box dim and non-gc atoms lx = boxhi[0] - boxlo[0] ly = boxhi[1] - boxlo[1] lz = boxhi[2] - boxlo[2] n_nongc = natoms - int(round(n_gc)) #get indices of all atoms and delete the index of the atom that is to be displaced (if any) indices = range(natoms) if (flag): del indices[(n_id - 1)] ##for i in range(natoms): ## print i+1, typ[i], coords[3*i], coords[3*i+1], coords[3*i+2] #find com and radius of particle xcm = ycm = zcm = 0 part_indices = [] for i in range(n_nongc): if typ[i] == typeNear1: #It is considered that the atom type of particle are same as typeNear1 xcm = xcm + coords[3 * i] ycm = ycm + coords[3 * i + 1] zcm = zcm + coords[3 * i + 2] part_indices.append(i) n_part = len(part_indices) xcm = xcm / n_part ycm = ycm / n_part zcm = zcm / n_part far_part_atoms = int( round(far_atoms) ) #No. of farthest atoms from COM whose avg dist from COM to be considered for radius of particle calc far_r_factor = far_rfact #Calc avg radius^2 of r_atoms will be multiplied by this factor (<1 to be conservative) rsq = [ ] #list of squared radial distances of atoms in particle from COM of particle for i in part_indices: #It is considered that the atom type of particle are same as typeNear dx = coords[3 * i] - xcm dy = coords[3 * i + 1] - ycm dz = coords[3 * i + 2] - zcm rsq.append(dx * dx + dy * dy + dz * dz) rsq_part = (sum(sorted(rsq)[-far_part_atoms:]) / far_part_atoms) * far_r_factor print "No. of particle atoms, COM and radius^2 of particle are: ", n_part, xcm, ycm, zcm, rsq_part #define criteria variable with high and false values so that the loop is entered rminsq = rmin * rmin rmaxsq = rmax * rmax distminsq = 100000000 #for default-criteria distminSisq = 100000000 #for addon-criteria1 typedistmin = 0 #for addon-criteria2 rsq_gc = 10000000 #for addon-criteria3 #Distance of new gcmc atom from particle com if iNear2 == 0: typeNear2 = typeNear1 iter = 0 while (not((distminsq >= rminsq) and (distminsq <= rmaxsq) \ and (distminSisq*iSiDist >= rminsq*iSiDist) and (distminSisq*iSiDist <= rmaxsq*iSiDist) \ and ((typedistmin*iNear1 == typeNear1*iNear1) or (typedistmin*iNear1 == typeNear2*iNear1)) \ and (rsq_gc*iparticle <= rsq_part*iparticle) )): iter = iter + 1 if (iter > itermax): break distminsq = 100000000 distminSisq = 100000000 rx = boxlo[0] + random.random() * lx ry = boxlo[1] + random.random() * ly rz = boxlo[2] + random.random() * lz rsq_gc = (rx - xcm) * (rx - xcm) + (ry - ycm) * (ry - ycm) + ( rz - zcm) * (rz - zcm) for i in indices: distx = min(abs(rx - coords[3 * i]), lx - abs(rx - coords[3 * i])) disty = min(abs(ry - coords[3 * i + 1]), ly - abs(ry - coords[3 * i + 1])) distz = min(abs(rz - coords[3 * i + 2]), lz - abs(rz - coords[3 * i + 2])) distsq = distx * distx + disty * disty + distz * distz if (distsq < distminsq): distminsq = distsq typedistmin = typ[i] if (typ[i] == typeNear1 and distsq < distminSisq): distminSisq = distsq if (flag): rx = rx - coords[3 * (n_id - 1)] ry = ry - coords[3 * (n_id - 1) + 1] rz = rz - coords[3 * (n_id - 1) + 2] else: rx = ry = rz = frx = fry = frz = distminsq = distminSisq = typedistmin = rsq_gc = rsq_part = iter = None rx = comm.bcast(rx, root=0) ry = comm.bcast(ry, root=0) rz = comm.bcast(rz, root=0) frx = lmp.set_variable("rx", rx) fry = lmp.set_variable("ry", ry) frz = lmp.set_variable("rz", rz) iter = comm.bcast(iter, root=0) if me == 0: print 'In getcoord.py (iter, coords(3), distminsq, distminSisq, typedistmin, rsq_gc, rsq_part:', iter, rx, ry, rz, distminsq, distminSisq, typedistmin, rsq_gc, rsq_part if (iter <= itermax): return 1 else: return 0
def __init__(self, ff, fn_system, fn_log="none", suffix='', do_table=True, fn_table='lammps.table', scalings_table=[0.0, 0.0, 1.0], do_ei=True, kspace='ewald', kspace_accuracy=1e-7, scalings_ei=[0.0, 0.0, 1.0], triclinic=True, comm=None, move_central_cell=False): r'''Initalize LAMMPS ForcePart **Arguments:** system An instance of the ``System`` class. fn_system The file containing the system data in LAMMPS format, can be generated using external.lammpsio.write_lammps_system_data **Optional Arguments:** fn_log Filename where LAMMPS output is stored. This is probably only necessary for debugging. Default: None, which means no output is stored suffix The suffix of the liblammps_*.so library file do_table Boolean, compute a potentual using tabulated values fn_table Filename of file containing tabulated non-bonded potential without point-charge electrostatics. Can be written using the ```write_lammps_table``` method. Default: lammps.table scalings_vdw List containing vdW scaling factors for 1-2, 1-3 and 1-4 neighbors do_ei Boolean, compute a point-charge electrostatic contribution kspace Method to treat long-range electrostatics, should be one of ewald or pppm kspace_accuracy Desired relative error in electrostatic forces Default: 1e-6 scalings_ei List containing electrostatic scaling factors for 1-2, 1-3 and 1-4 neighbors triclinic Boolean, specify whether a triclinic cell will be used during the simulation. If the cell is orthogonal, set it to False as LAMMPS should run slightly faster. Default: True comm MPI communicator, required if LAMMPS should run in parallel move_central_cell Boolean, if True, every atom is moved to the central cell (centered at the origin) before passing positions to LAMMPS. Change this if LAMMPS gives a Atoms Lost ERROR. ''' self.system = ff.system # Try to load the lammps package, quit if not possible try: from lammps import lammps except: log("Could not import the lammps python package which is required to use LAMMPS as a library" ) raise ImportError # Some safety checks... if self.system.cell.nvec != 3: raise ValueError( 'The system must be 3D periodic for LAMMPS calculations.') if not os.path.isfile(fn_system): raise ValueError('Could not read file %s' % fn_system) if do_table: if not os.path.isfile(fn_table): raise ValueError('Could not read file %s' % fn_table) tables = read_lammps_table(fn_table) table_names = [table[0] for table in tables] npoints, _, rcut = tables[0][1] elif do_ei: rcut = 0 for part in ff.parts: if part.name == 'pair_ei': rcut = part.pair_pot.rcut if rcut == 0: log("ERROR, do_ei set to True, but pair_ei was not found in the ff" ) else: raise NotImplementedError if not kspace in ['ewald', 'pppm']: raise ValueError('kspace should be one of ewald or pppm') if self.system.natom > 2000 and kspace == 'ewald' and log.do_warning: log.warn("You are simulating a more or less large system." "It might be more efficient to use kspace=pppm") if self.system.natom < 1000 and kspace == 'pppm' and log.do_warning: log.warn("You are simulating a more or less small system." "It might be better to use kspace=ewald") # Initialize a class instance and some attributes ForcePart.__init__(self, 'lammps', self.system) self.comm = comm self.triclinic = triclinic self.move_central_cell = move_central_cell ffatypes, ffatype_ids = get_lammps_ffatypes(ff) nffa = len(ffatypes) # Pass all commands that would normally appear in the LAMMPS input file # to our instance of LAMMPS. self.lammps = lammps(name=suffix, comm=self.comm, cmdargs=["-screen", fn_log, "-log", "none"]) self.lammps.command("units electron") self.lammps.command("atom_style full") self.lammps.command("atom_modify map array") self.lammps.command("box tilt large") self.lammps.command("read_data %s" % fn_system) self.lammps.command("mass * 1.0") self.lammps.command("bond_style none") # Hybrid style combining electrostatics and table if do_ei and do_table: self.lammps.command( "pair_style hybrid/overlay coul/long %13.8f table spline %d" % (rcut, npoints)) self.lammps.command("pair_coeff * * coul/long") self.lammps.command("kspace_style %s %10.5e" % (kspace, kspace_accuracy)) # Only electrostatics elif do_ei: self.lammps.command("pair_style coul/long %13.8f" % rcut) self.lammps.command("pair_coeff * *") self.lammps.command("kspace_style %s %10.5e" % (kspace, kspace_accuracy)) # Only table elif do_table: self.lammps.command("pair_style table spline %d" % (npoints)) else: raise NotImplementedError for i in range(nffa): ffai = ffatypes[i] for j in range(i, nffa): ffaj = ffatypes[j] if ffai > ffaj: name = '%s---%s' % (str(ffai), str(ffaj)) else: name = '%s---%s' % (str(ffaj), str(ffai)) if do_ei and do_table: self.lammps.command("pair_coeff %d %d table %s %s" % (i + 1, j + 1, fn_table, name)) elif do_table: self.lammps.command("pair_coeff %d %d %s %s" % (i + 1, j + 1, fn_table, name)) if do_ei is not None: self.lammps.command( "special_bonds lj %f %f %f coul %f %f %f" % (scalings_table[0], scalings_table[1], scalings_table[2], scalings_ei[0], scalings_ei[1], scalings_ei[2])) else: self.lammps.command( "special_bonds lj %f %f %f" % (scalings_table[0], scalings_table[1], scalings_table[2])) self.lammps.command("neighbor 0.0 bin") self.lammps.command("neigh_modify delay 0 every 1 check no") self.lammps.command("compute virial all pressure NULL virial") self.lammps.command("variable eng equal pe") self.lammps.command("variable Wxx equal c_virial[1]") self.lammps.command("variable Wyy equal c_virial[2]") self.lammps.command("variable Wzz equal c_virial[3]") self.lammps.command("variable Wxy equal c_virial[4]") self.lammps.command("variable Wxz equal c_virial[5]") self.lammps.command("variable Wyz equal c_virial[6]") thermo_style = "step time etotal evdwl ecoul elong etail " thermo_style += " ".join(["c_virial[%d]" % i for i in range(1, 7)]) self.lammps.command("thermo_style custom %s" % thermo_style) self.lammps.command("fix 1 all nve") # LAMMPS needs cell vectors (ax,0,0), (bx,by,0) and (cx,cy,cz) # This means we need to perform a rotation to switch between Yaff and # LAMMPS coordinates. All information about this rotation is stored # in the variables defined below self.rvecs = np.eye(3) self.cell = Cell(self.rvecs) self.rot = np.zeros((3, 3)) self.vtens_lammps = np.zeros((6, ))
def main(): # import libraries # print "got here..." from mpi4py import MPI # print "and here" my_rank = MPI.COMM_WORLD.Get_rank() size = MPI.COMM_WORLD.Get_size() from lammps import lammps if my_rank == 0: print "begin python script" # user input; global variables lammpsScript = "in.accelerated-test.txt" lammpsArgs = ["-echo", "log"] #--------------END OF USER DEFINED PARAMETERS-------------------------------------- # run lammps script lmp1 = lammps( cmdargs=lammpsArgs) # lammps(comm=MPI.COMM_WORLD,cmdargs=lammpsArgs) lmp1.file(lammpsScript) initialize() lmp1.command("run 0") #todo, grab box dimensions for periodic boundaries. #- lmp1.extract_global("boxzlo",0) #boxlo,boxhi,xy,yz,xz,periodicity,box_change = lmp1.extract_box() #coordFile.write("xdim: " + str(boxdim[0]) + "\nydim: " + str(boxdim[1]) + "\nzdim: " + str(boxdim[2]) + "\n\n") # Get lammps data as python variables natoms = lmp1.get_natoms() coordinates = lmp1.gather_atoms("x", 1, 3) atomType = lmp1.gather_atoms("type", 0, 1) for i in range(100): #gets global quantity ntimestep (current timestep) in lammps. more extractable stuff can be viewed in library.cpp currentStep = lmp1.extract_global("ntimestep", 0) natoms = lmp1.get_natoms() boxdim[0] = lmp1.extract_global("boxxhi", 1) boxdim[1] = lmp1.extract_global("boxyhi", 1) boxdim[2] = lmp1.extract_global("boxzhi", 1) coordinates = lmp1.gather_atoms("x", 1, 3) atomType = lmp1.gather_atoms("type", 0, 1) coordFile.write("Time Step: " + str(currentStep) + "\n") #for o in range(natoms): #coordFile.write("Atom Index: "+ str(o) + " X: "+ str(coordinates[3*o]) + " Y: "+ str(coordinates[3*o+1]) + " Z: " + str(coordinates[3*o+2])) #coordFile.write("\n") search(natoms, atomType, coordinates, currentStep) findSuccessBonds(natoms, atomType, coordinates, currentStep) lmp1.command("run " + str(timestep)) # lmp1.command("run 100000") newfile.close() coordFile.close() bondFile.close() # add additional commands to lammps instance and run additional steps # ============================================================================= # for i in range(2): # natoms = lmp1.get_natoms() # coordinates = lmp1.gather_atoms("x",1,3) # atomType = lmp1.gather_atoms("type",0,1) # coordinatesLocal = lmp1.extract_atom("x",3) # coordFile.write("\n" + str(coordinates(0)) + str(coordinates(1))+ str(coordinates(2))) # search(natoms, atomType, coordinates) # lmp1.command("run " + str(timestep)) # lmp1.command("run 100000") # timeCurr += timestep # ============================================================================= lmp1.close() if my_rank == 0: print "End of run"
def main(Sim_name, MooseFileDir, LammpsFileDir, Porosity_Filecpp, PorosityFileMOOSE, Mesh, MooseFile, LammpsFile, ParticlesFile, In_Press, Num_times, Num_parts, Diameter, Poros, Mui, Mud, Domain, Ann_rad, Dom_rad, NN, Init=True): os.chdir("/home/crhea/Dropbox/Thesis/PrimaryFiles/" + Sim_name + "/") #Calculate element and node numbers for finite element mesh num_nodes, num_elem = count_FEMesh(Mesh) print(Sim_name) lmp = lammps() #---------------------------INITIALIZATION---------------------------------# #if Init == True: Update_Lammps_Init(Sim_name, LammpsFileDir, LammpsFile, ParticlesFile, Diameter, Domain) Update_Porosity(Sim_name, LammpsFileDir, Porosity_Filecpp, Mesh, Num_parts, Diameter / 2.0, num_nodes, num_elem, Ann_rad, Dom_rad, NN) print("Reconfig Input file for the C++ file") reconfigInit(Sim_name, LammpsFileDir, ParticlesFile, Num_parts) os.system('g++ -o porosity porosity.cpp') os.system('./porosity') Init_FF(Sim_name, MooseFileDir, MooseFile, Mesh, PorosityFileMOOSE, In_Press) #Init = False # -------------- DONE WITH INITIALIZATION ----------------------# call('mpiexec -n 1 /home/crhea/Dropbox/Thesis/bat/bat-opt -i ' + MooseFile, shell=True) Moose_append_init(MooseFileDir + "/", "MOOSEOutput.e") #Setup MOOSE for subsequent runs Update_Moose_after_Init(Sim_name, Mesh, MooseFile, PorosityFileMOOSE) for timestep in range(Num_times): # Run LAMMPS #call('lammps < LAMMPS/inputfiles/in.primary',shell=True) # Update Velocity and Viscosity Fields in LAMMPS print("----------Beginning Interpolating----------") Interpolate(ParticlesFile, Num_parts, "velocitiesX.csv", "velocitiesY.csv", MooseFileDir + "/MOOSEOutput.e", "VelForLammps") visc_avg("MOOSEValues_sat_updated.txt", ParticlesFile, Mui, Mud, Num_parts, "Viscosity") sat_int("MOOSEValues_sat_updated.txt", ParticlesFile, Num_parts, "SaturationInterpolated") print("----------Ending Interpolating----------") # RUN LAMMPS if timestep == 0: print("----------LAMMPS RUN " + str(timestep) + " Beginning----------") lmp.file(LammpsFile + "_init") #lmp.close() print("----------LAMMPS RUN " + str(timestep) + " Ending----------") else: print("----------LAMMPS RUN " + str(timestep) + " Beginning----------") lmp.command("clear") #lmp = lammps() lmp.file(LammpsFile) #lmp.close() print("----------LAMMPS RUN " + str(timestep) + " Ending----------") #Update csv files for particle positions write_to_txt( "/home/crhea/Dropbox/Thesis/PrimaryFiles/" + Sim_name + "/" + LammpsFileDir + "/pos_lammps_out.txt", number_particles, LammpsFileDir + "/Pos/pos_", timestep) # ---------------------- POROSITY UPDATE ----------------------# if Poros == True: #Only run porosity update if desired Update_Porosity(Sim_name, LammpsFileDir, Porosity_Filecpp, Mesh, Num_parts, Diameter / 2.0, num_nodes, num_elem, Ann_rad, Dom_rad, NN) print("Reconfig Input file for the C++ file") reconfig( Sim_name, LammpsFileDir, "/home/crhea/Dropbox/Thesis/PrimaryFiles/" + Sim_name + "/" + LammpsFileDir + "/pos_lammps_out.txt", Num_parts) os.system('g++ -o porosity porosity.cpp') start = time.time() os.system('./porosity') end = time.time() print("Total Time for porosity calculations " + str(end - start)) else: pass # ---------------------------- LAMMPS UPDATE ---------------------# Update_Lammps(Sim_name, LammpsFileDir, LammpsFile) # -------------------------- MOOSE -------------------------------# Update_MOOSE(Sim_name, MooseFile, PorosityFileMOOSE, time) print("----------MOOSE RUN " + str(timestep + 1) + " Beginning----------") call('mpiexec -n 1 /home/crhea/Dropbox/Thesis/bat/bat-opt -i ' + MooseFile, shell=True) MooseRenamePorosity(Sim_name) print("----------MOOSE RUN " + str(timestep + 1) + " Ending----------") Moose_append_timestep(MooseFileDir + "/", "MOOSEOutput.e", timestep)
from ctypes import c_double, c_int from mpi4py import MPI import numpy as np import pickle import sys try: from lammps import lammps except ImportError: pass # Lammps executable job = lammps(cmdargs=['-screen', 'none']) def extract_compute(funct_args): if MPI.COMM_WORLD.rank == 0: return np.array(job.extract_compute(*funct_args)) def get_thermo(funct_args): if MPI.COMM_WORLD.rank == 0: return np.array(job.get_thermo(*funct_args)) def scatter_atoms(funct_args): py_vector = funct_args[3] if issubclass(type(py_vector[0]), np.integer): c_vector = (len(py_vector) * c_int)(*py_vector) else:
def __init__(self, ptr): self.lmp = lammps.lammps(ptr=ptr)
from ase.optimize.fire import FIRE from ase import Atoms from ase.optimize import BFGS from ase.build import sort import logging from random import randint import pandas as pd import os import numpy as np # set up for lammps lammps_name = '' comm = None log_file = 'lammps.log' cmd_args = ['-echo', 'log', '-log', log_file, '-screen', 'none', '-nocite'] lmp = lammps(lammps_name, cmd_args, comm) logging.basicConfig(format='%(asctime)s :: %(message)s', filename='results.log', level=logging.INFO) parameters = [ "atom_style full", "pair_style lj/cut/tip4p/long 1 2 1 1 0.278072379 17.007", "bond_style class2 ", "angle_style harmonic", "kspace_style pppm/tip4p 0.0001", "read_data tmp/data.lammps", "pair_coeff 2 2 0 0", "pair_coeff 1 2 0 0", "pair_coeff 1 1 0.000295147 5.96946",
This shows that the dBi/dRj components extracted with dgradflag = 1 are correct. Serial syntax: python compute_snap_dgrad.py Parallel syntax: mpirun -np 4 python compute_snap_dgrad.py """ from __future__ import print_function import sys import ctypes import numpy as np from lammps import lammps, LMP_TYPE_ARRAY, LMP_STYLE_GLOBAL # get MPI settings from LAMMPS lmp = lammps() me = lmp.extract_setting("world_rank") nprocs = lmp.extract_setting("world_size") cmds = ["-screen", "none", "-log", "none"] lmp = lammps(cmdargs=cmds) def run_lammps(dgradflag): # simulation settings lmp.command("clear") lmp.command("units metal") lmp.command("boundary p p p") lmp.command("atom_modify map hash")
from mpi4py import MPI from lammps import lammps lmp = lammps() lmp.file('in.thread') me = MPI.COMM_WORLD.Get_rank() nprocs = MPI.COMM_WORLD.Get_size() MPI.Finalize()
def __init__(self, ptr, group_name="all"): self.lmp = lammps(ptr=ptr) self.group_name = group_name
def scan(lmpdat, output, indices_and_values, ks, temps=(600, 0), omit_entity=True, pair_coeffs=None, settings=None): """ Scan a bond, angle or dihedral. Carry out a force field calculation for an atom, a bond or a dihedral using the fix restrain command. Parameters ---------- lmpdat : str lammps data file indices_and_values : dict geometry indices is the key and value is the value of the geometry e.g. {"3 4 5 12": 180.05, "4 5 2 6 1": 168.90, ...} output : str appendix to output files pair_coeffs : None or str file with all pair coefficients settings : None or str file with basic settings before loading the data file when no file is given, standard values will be assumed Sources: (https://lammps.sandia.gov/threads/msg17271.html) https://lammps.sandia.gov/doc/fix_restrain.html """ # change lammps data file so a dummy entity is created which can later # be used for the single point calculation (one with the original angle # and one without -> important for fitting when using the difference curve) igeom, icoeff_id = add_dummy_to_lmpdat(lmpdat, indices_and_values, key_index=0) #pdb.set_trace() save_step = 50000 anneal_step = 750000 quench_step = 500000 thermargs = [ "step", "temp", "pe", "eangle", "edihed", "eimp", "evdwl", "ecoul", "ebond", "enthalpy" ] # split world communicator into n partitions and run lammps only on that specific one lmp = lammps(comm=split, cmdargs=["-screen", "lmp_out.txt"]) lmp.command("log {}.lmplog".format(output)) if settings is not None: lmp.file(settings) else: lmp.command("units metal") lmp.command("boundary p p p") lmp.command("dimension 3") lmp.command("atom_style full") lmp.command("pair_style lj/cut/coul/cut 30.0") lmp.command("bond_style harmonic") lmp.command("angle_style harmonic") lmp.command("dihedral_style charmm") lmp.command("improper_style cvff") lmp.command("special_bonds amber") lmp.command("timestep 0.001") # data and thermo lmp.command("read_data {}".format(lmpdat)) # make lammps calculate the value of the entity (bond, angle, dihedral) lmp.command("thermo_style custom " + " ".join(thermargs)) lmp.command("thermo_modify lost warn flush yes") lmp.command("thermo {}".format(save_step)) lmp.command("fix MOMENT all momentum 100 linear 1 1 1 angular") lmp.command("dump DUMP all dcd {} {}.dcd".format(save_step, output)) # read file which provides the pair coefficients if pair_coeffs is not None: lmp.file(pair_coeffs) # annealing -> achieve wanted angle (may be omitted?) print(bcolors.red + "Annealing on rank {}: ".format(rank) + output + bcolors.endc) ########################################################################### # TESTING #indices_and_values = {"25 8 9 10" : 90.0} #indices_and_values = {"11 7 8 25" : -4.0} #indices_and_values = {"25 8 7 11" : 3.1415} #lmp.command("compute 1 entity_atoms property/local dtype datom1 datom2 datom3 datom4") #lmp.command("compute 2 entity_atoms dihedral/local phi") #lmp.command("dump 1 all local 1000 {}.dump index c_2".format(output)) ########################################################################### lmp.command( "velocity all create {} 8675309 mom yes rot yes dist gaussian".format( temps[0])) lmp.command("fix NVE all nve") lmp.command("fix TFIX all langevin {} {} 100 24601".format( temps[0], temps[1])) restrain_anneal = compile_restrain_string(indices_and_values, ks, hold=0) lmp.command(restrain_anneal) lmp.command("fix_modify REST energy yes") lmp.command("run {}".format(anneal_step)) #try: # lmp.command("run {}".format(anneal_step)) #except Exception: # print("***Error: Simulation crashed (annealing)! Force constants too high? Pair Coeffs set?") # MPI.COMM_WORLD.Abort() # quenching print(bcolors.yellow + "Quenching on rank {}: ".format(rank) + output + bcolors.endc) restrain_quench = compile_restrain_string(indices_and_values, ks, hold=1) lmp.command("fix TFIX all langevin {} {} 100 24601".format( temps[1], temps[1])) lmp.command(restrain_quench) lmp.command("fix_modify REST energy yes") try: lmp.command("run {}".format(quench_step)) except: print( "***Error: Simulation crashed (quenching)! Force constants too high?" ) MPI.COMM_WORLD.Abort() # sanity check for convergence print(bcolors.green + "Minimization on rank {}: ".format(rank) + output + bcolors.endc) try: lmp.command("minimize 1e-6 1e-9 2000000 100000") except: print("***Error: Simulation crashed (minimization)!") MPI.COMM_WORLD.Abort() # report unrestrained energies, single point energy lmp.command("unfix REST") try: lmp.command("run 0") except: print("***Error: Simulation crashed (single step calculation)!") MPI.COMM_WORLD.Abort() # omit energy contribution of the scanned entity by setting its value to 0.0 if omit_entity is True: lmp.command("group entity_atoms id {}".format( list(indices_and_values.keys())[0])) lmp.command("set group entity_atoms {} {}".format(igeom, icoeff_id)) try: lmp.command("run 0") except: print( "***Error: Simulation crashed (single step w/o entity calculation)!" ) MPI.COMM_WORLD.Abort() lmp.close()
def testExternalCallback(self): """Test fix external from Python with pf/callback""" machine = None if 'LAMMPS_MACHINE_NAME' in os.environ: machine = os.environ['LAMMPS_MACHINE_NAME'] lmp = lammps(name=machine, cmdargs=['-nocite', '-log', 'none', '-echo', 'screen']) # a few commands to set up simple system basic_system = """lattice sc 1.0 region box block -1 1 -1 1 -1 1 create_box 1 box create_atoms 1 box mass 1 1.0 pair_style zero 0.1 pair_coeff 1 1 velocity all set 0.1 0.0 -0.1 thermo_style custom step temp pe ke etotal press thermo 5 fix 1 all nve fix ext all external pf/callback 5 1 compute eatm all pe/atom fix compute vatm all stress/atom NULL fix compute sum all reduce sum c_eatm c_vatm[*] thermo_style custom step temp pe ke etotal press c_sum[*] fix_modify ext energy yes virial yes """ lmp.commands_string(basic_system) lmp.fix_external_set_vector_length("ext", 6) lmp.set_fix_external_callback("ext", callback_one, lmp) # check setting per-atom data with python lists lmp.command("run 0 post no") reduce = lmp.extract_compute("sum", LMP_STYLE_GLOBAL, LMP_TYPE_VECTOR) self.assertAlmostEqual(reduce[0], 2.8, 14) self.assertAlmostEqual(reduce[1], -0.1, 14) self.assertAlmostEqual(reduce[2], 7.8, 14) self.assertAlmostEqual(reduce[3], -0.3, 14) self.assertAlmostEqual(reduce[4], -0.4, 14) self.assertAlmostEqual(reduce[5], 6.5, 14) self.assertAlmostEqual(reduce[6], -0.6, 14) lmp.command("run 10 post no") self.assertAlmostEqual(lmp.get_thermo("temp"), 1.0 / 30.0, 14) self.assertAlmostEqual(lmp.get_thermo("pe"), 1.0 / 8.0, 14) self.assertAlmostEqual(lmp.get_thermo("press"), 0.15416666666666667, 14) # check setting per-atom data numpy arrays reduce = lmp.extract_compute("sum", LMP_STYLE_GLOBAL, LMP_TYPE_VECTOR) self.assertAlmostEqual(reduce[0], 2.8, 14) self.assertAlmostEqual(reduce[1], -0.1, 14) self.assertAlmostEqual(reduce[2], 7.8, 14) self.assertAlmostEqual(reduce[3], -0.3, 14) self.assertAlmostEqual(reduce[4], -0.4, 14) self.assertAlmostEqual(reduce[5], 6.5, 14) self.assertAlmostEqual(reduce[6], -0.6, 14) val = 0.0 for i in range(0, 6): val += lmp.extract_fix("ext", LMP_STYLE_GLOBAL, LMP_TYPE_VECTOR, nrow=i) self.assertAlmostEqual(val, 15.0, 14)
def main(filePrefix): # filePrefix='090415a' dataFile = filePrefix + '_Si.dat' restartFile = filePrefix + '.quenched.restart' length = 200 width = 20 mass = 28.0 rho = 2.291 # Density in g/cm^3 Natoms = np.int( np.round(rho * 1e-3 / 1e-6 * length * width**2 * 1e-30 / (mass * 1.66e-27))) # Create the box of silicon atoms, write to datafile ab = atombox(length, width, Natoms) ab.fillBox(seed=1234) ab.writeToFile(dataFile, mass) del ab # Minimize the atom positions lmp = lammps() lmp.command("variable filename string '" + filePrefix + "'") lmp.command("variable datafile string '" + dataFile + "'") lmp.command("variable restartfile string '" + restartFile + "'") def iterateFile(lmp, filename): ''' Do the same as lmp.file(filename) but allow the script to be continued after quit. ''' with open(filename, "r") as f: for line in f: print line if "quit" in line and line[0] != "#": return else: lmp.command(line) return # lmp.file("quench_Si.lmp") # If quit is found, python quits iterateFile(lmp, "quench_Si.lmp") lmp.close() # Create a new LAMMPS object lmp = lammps() lmp.command("variable filename string '" + filePrefix + "'") lmp.command("variable restartfile string '" + restartFile + "'") iterateFile(lmp, "amorphous_interface.lmp") # lmp.file("amorphous_interface.lmp") fileCompactVels = filePrefix + '.vels.dat.compact' fileVels = filePrefix + '.vels.dat' widthWin = 0.5e12 KijFilePrefix = filePrefix scaleFactor = 1.602e-19 / (1e-20) * 1e4 dt_md = 2.5e-15 pP = SHCPostProc.SHCPostProc(fileCompactVels, KijFilePrefix, dt_md=dt_md, scaleFactor=scaleFactor, LAMMPSDumpFile=fileVels, widthWin=widthWin, NChunks=20, chunkSize=50000, backupPrefix=filePrefix, LAMMPSRestartFile=restartFile, reCalcVels=True, reCalcFC=True) pP.postProcess() # Pickling the post-processing object into file import cPickle as pickle with open(filePrefix + '_PP.pckl', 'w') as f: pickle.dump(pP, f) # Saving into numpy files np.save(filePrefix + '_oms.npy', pP.oms_fft) np.save(filePrefix + '_SHC.npy', pP.SHC_smooth) # Saving the frequencies and heat currents to file np.savetxt(fileprefix + '_SHC.txt', np.column_stack((oms, pP.SHC_smooth)))
import sys import os lmp_dir = os.path.abspath('lammps-30Mar18') sys.path.append(os.path.join(lmp_dir, 'python')) print('PID', os.getpid()) # in case of debugging import lammps l = lammps.lammps(name="serial") import ase import ase.calculators.lammpslib as ase_lmp import ase.build import numpy as np cmds = { 'ref': [ "pair_style tersoff", "pair_coeff * * %s/potentials/Si.tersoff Si" % lmp_dir ], 'our': ["pair_style pot/gen 3.2", "pair_coeff * * potentials/Si.potc-param Si"] } default_header = [ 'units metal', 'atom_style atomic', 'atom_modify map array sort 0 0' ] lammps = {} for name, cmd in cmds.items(
def generate_lammps_trajectory( structure, input_file, total_time=0.1, # picoseconds time_step=0.002, # picoseconds relaxation_time=0, silent=False, supercell=(1, 1, 1), memmap=False, # not fully implemented yet! velocity_only=False, lammps_log=True, temperature=None, thermostat_mass=0.5, sampling_interval=1): # in timesteps cmdargs_lammps = ['-echo', 'none', '-screen', 'none'] if not lammps_log: cmdargs_lammps += ['-log', 'none'] lmp = lammps(cmdargs=cmdargs_lammps) lmp.file(input_file) lmp.command('timestep {}'.format(time_step)) lmp.command('replicate {} {} {}'.format(*supercell)) # Force reset temperature (overwrites lammps script) # This forces NVT simulation if temperature is not None: print('Temperature reset to {} (NVT)'.format(temperature)) lmp.command('fix int all nvt temp {0} {0} {1}'.format( temperature, thermostat_mass)) # Check if correct number of atoms if lmp.extract_global("natoms", 0) < 2: print('Number of atoms in MD should be higher than 1!') exit() # Check if initial velocities all zero if not np.array(lmp.gather_atoms("v", 1, 3)).any(): print('Set lammps initial velocities') t = temperature if temperature is not None else 100 lmp.command( 'velocity all create {} 3627941 dist gaussian mom yes'. format(t)) lmp.command('velocity all scale {}'.format(t)) lmp.command('run 0') # natoms = lmp.extract_global("natoms",0) # mass = lmp.extract_atom("mass",2) # temp = lmp.extract_compute("thermo_temp",0,0) # print("Temperature from compute =",temp) # print("Natoms, mass, x[0][0] coord =", natoms, mass[1], x[0][0]) # print ('thermo', lmp.get_thermo('1')) try: xlo = lmp.extract_global("boxxlo", 1) xhi = lmp.extract_global("boxxhi", 1) ylo = lmp.extract_global("boxylo", 1) yhi = lmp.extract_global("boxyhi", 1) zlo = lmp.extract_global("boxzlo", 1) zhi = lmp.extract_global("boxzhi", 1) xy = lmp.extract_global("xy", 1) yz = lmp.extract_global("yz", 1) xz = lmp.extract_global("xz", 1) except UnboundLocalError: boxlo, boxhi, xy, yz, xz, periodicity, box_change = lmp.extract_box() xlo, ylo, zlo = boxlo xhi, yhi, zhi = boxhi simulation_cell = np.array([[xhi - xlo, xy, xz], [0, yhi - ylo, yz], [0, 0, zhi - zlo]]).T positions = [] velocity = [] energy = [] na = lmp.get_natoms() id = lmp.extract_atom("id", 0) id = np.array([id[i] - 1 for i in range(na)], dtype=int) xp = lmp.extract_atom("x", 3) reference = np.array([[xp[i][0], xp[i][1], xp[i][2]] for i in range(na)], dtype=float)[id, :] # xc = lmp.gather_atoms("x", 1, 3) # reference = np.array([xc[i] for i in range(na*3)]).reshape((na,3)) template = get_correct_arrangement(reference, structure) indexing = np.argsort(template) lmp.command('variable energy equal pe'.format( int(relaxation_time / time_step))) lmp.command('run {}'.format(int(relaxation_time / time_step))) if not silent: _progress_bar(0, 'lammps') n_loops = int(total_time / time_step / sampling_interval) for i in range(n_loops): if not silent: _progress_bar( float((i + 1) * time_step * sampling_interval) / total_time, 'lammps', ) lmp.command('run {}'.format(sampling_interval)) # xc = lmp.gather_atoms("x", 1, 3) # vc = lmp.gather_atoms("v", 1, 3) energy.append(lmp.extract_variable('energy', 'all', 0)) id = lmp.extract_atom("id", 0) id = np.array([id[i] - 1 for i in range(na)], dtype=int) vc = lmp.extract_atom("v", 3) velocity.append( np.array([[vc[i][0], vc[i][1], vc[i][2]] for i in range(na)], dtype=float)[id, :][indexing, :]) # velocity.append(np.array([vc[i] for i in range(na * 3)]).reshape((na, 3))[indexing, :]) if not velocity_only: xc = lmp.extract_atom("x", 3) positions.append( np.array([[xc[i][0], xc[i][1], xc[i][2]] for i in range(na)], dtype=float)[id, :][indexing, :]) # positions.append(np.array([xc[i] for i in range(na * 3)]).reshape((na, 3))[indexing, :]) positions = np.array(positions, dtype=complex) velocity = np.array(velocity, dtype=complex) energy = np.array(energy) if velocity_only: positions = None lmp.close() time = np.array( [i * time_step * sampling_interval for i in range(n_loops)], dtype=float) return dyn.Dynamics(structure=structure, trajectory=positions, velocity=velocity, time=time, energy=energy, supercell=simulation_cell, memmap=memmap)
def generate_lammps_trajectory(structure, input_file, total_time=0.1, # picoseconds time_step=0.002, # picoseconds relaxation_time=0, silent=False, supercell=(1, 1, 1), memmap=False, # not fully implemented yet! velocity_only=False, lammps_log=True, temperature=None, thermostat_mass=0.5, sampling_interval=1): # in timesteps cmdargs_lammps = ['-echo','none', '-screen', 'none'] if not lammps_log: cmdargs_lammps += ['-log', 'none'] lmp = lammps(cmdargs=cmdargs_lammps) lmp.file(input_file) lmp.command('timestep {}'.format(time_step)) lmp.command('replicate {} {} {}'.format(*supercell)) # Force reset temperature (overwrites lammps script) # This forces NVT simulation if temperature is not None: print ('Temperature reset to {} (NVT)'.format(temperature)) lmp.command('fix int all nvt temp {0} {0} {1}'.format(temperature, thermostat_mass)) # Check if correct number of atoms if lmp.extract_global("natoms",0) < 2: print ('Number of atoms in MD should be higher than 1!') exit() # Check if initial velocities all zero if not np.array(lmp.gather_atoms("v", 1, 3)).any(): print('Set lammps initial velocities') t = temperature if temperature is not None else 100 lmp.command('velocity all create {} 3627941 dist gaussian mom yes'.format(t)) lmp.command('velocity all scale {}'.format(t)) lmp.command('run 0') # natoms = lmp.extract_global("natoms",0) # mass = lmp.extract_atom("mass",2) # temp = lmp.extract_compute("thermo_temp",0,0) # print("Temperature from compute =",temp) # print("Natoms, mass, x[0][0] coord =", natoms, mass[1], x[0][0]) # print ('thermo', lmp.get_thermo('1')) xlo =lmp.extract_global("boxxlo", 1) xhi =lmp.extract_global("boxxhi", 1) ylo =lmp.extract_global("boxylo", 1) yhi =lmp.extract_global("boxyhi", 1) zlo =lmp.extract_global("boxzlo", 1) zhi =lmp.extract_global("boxzhi", 1) xy =lmp.extract_global("xy", 1) yz =lmp.extract_global("yz", 1) xz =lmp.extract_global("xz", 1) simulation_cell = np.array([[xhi-xlo, xy, xz], [0, yhi-ylo, yz], [0, 0, zhi-zlo]]).T positions = [] velocity = [] energy = [] na = lmp.get_natoms() xc = lmp.gather_atoms("x", 1, 3) reference = np.array([xc[i] for i in range(na*3)]).reshape((na,3)) template = get_correct_arrangement(reference, structure) indexing = np.argsort(template) lmp.command('variable energy equal pe'.format(int(relaxation_time/time_step))) lmp.command('run {}'.format(int(relaxation_time/time_step))) if not silent: _progress_bar(0, 'lammps') n_loops = int(total_time / time_step / sampling_interval) for i in range(n_loops): if not silent: _progress_bar(float((i+1) * time_step * sampling_interval) / total_time, 'lammps', ) lmp.command('run {}'.format(sampling_interval)) xc = lmp.gather_atoms("x", 1, 3) vc = lmp.gather_atoms("v", 1, 3) energy.append(lmp.extract_variable('energy', 'all', 0)) velocity.append(np.array([vc[i] for i in range(na * 3)]).reshape((na, 3))[indexing, :]) if not velocity_only: positions.append(np.array([xc[i] for i in range(na * 3)]).reshape((na, 3))[indexing, :]) positions = np.array(positions, dtype=complex) velocity = np.array(velocity, dtype=complex) energy = np.array(energy) if velocity_only: positions = None lmp.close() time = np.array([i * time_step * sampling_interval for i in range(n_loops)], dtype=float) return dyn.Dynamics(structure=structure, trajectory=positions, velocity=velocity, time=time, energy=energy, supercell=simulation_cell, memmap=memmap)
# This example demonstrates how to obtain normal modes from LAMMPS # ################################################################### import os import math import sys if sys.platform == "cygwin": from cyglibra_core import * elif sys.platform == "linux" or sys.platform == "linux2": from liblibra_core import * from libra_py import * import lammps lmp = lammps.lammps() # Do the Hessian/dynmat calculations D, H, R, M, typ = LAMMPS_methods.compute_dynmat(lmp, "in.lammps", [1], 1e-3, 0) print "Atom types are:", typ print "Masses are:" M.show_matrix() print "Coordinates are:" R.show_matrix() #print "Hessian matrix is:"; H.show_matrix() #print "Dynamical matrix is:"; D.show_matrix() # Map atom types to atom names E = [] PT = {1: "Au"}
### Parameters ### # Create velocity Array velx = np.zeros( (nmd.numTstep, nmd.numAtoms), dtype=float) vely = np.zeros( (nmd.numTstep, nmd.numAtoms), dtype=float) velz = np.zeros( (nmd.numTstep, nmd.numAtoms), dtype=float) # x = np.zeros( (nmd.numTstep, nmd.numAtoms), dtype=float) x = np.zeros( (nmd.numTstep, 768,768), dtype=float) y = np.zeros( (nmd.numTstep, nmd.numAtoms), dtype=float) z = np.zeros( (nmd.numTstep, nmd.numAtoms), dtype=float) ###--- MAIN ---### lmp1 = lammps() #lmp2 = lammps() lmp1.file("in.simple") #lmp2.file("in.run") print "Proc %d out of %d procs has" % (pypar.rank(),pypar.size()),lmp1 # Retract simulation 1 info #x = lmp1.gather_atoms("x", "all", 1) #y = lmp1.gather_atoms("y", "all", 1) #z = lmp1.gather_atoms("z", "all", 1) #vx = lmp1.gather_atoms("vx", "all", 1) #vy = lmp1.gather_atoms("vy", "all", 1) #vz = lmp1.gather_atoms("vz", "all", 1) #print "Proc %d out of %d procs has" % (pypar.rank(),pypar.size()),lmp2 # Insert simulation 1 info
def __init__( self, inp, name = "serial", cmdargs = [ "-sc", "none" ] ): self.lmp = x_lammps.lammps( name, cmdargs ) self.lmp.file( inp ) self.chg = self.lmp.gather_atoms( "q", 1, 1 ) self.crd = self.lmp.gather_atoms( "x", 1, 3 )
# Purpose: illustrate use of many library interface commands # Syntax: demo.py # uses in.demo as LAMMPS input script from __future__ import print_function import sys # parse command line argv = sys.argv if len(argv) != 1: print("Syntax: demo.py") sys.exit() from lammps import lammps lmp = lammps() # test out various library functions after running in.demo lmp.file("in.demo") print("\nPython output:") natoms = lmp.extract_global("natoms",0) mass = lmp.extract_atom("mass",2) x = lmp.extract_atom("x",3) print("Natoms, mass, x[0][0] coord =",natoms,mass[1],x[0][0]) temp = lmp.extract_compute("thermo_temp",0,0) print("Temperature from compute =",temp)
#!/usr/bin/env python -i # preceeding line should have path for Python on your machine # simple.py # Purpose: mimic operation of couple/simple/simple.cpp via Python # Syntax: simple.py in.lammps # in.lammps = LAMMPS input script from __future__ import print_function import sys infile = 'in.simple' me = 0 from lammps import lammps lmp = lammps(cmdargs=sys.argv[1:]) # run infile one line at a time lines = open(infile,'r').readlines() for line in lines: lmp.command(line) lmp.command("run 10") x = lmp.gather_atoms("x",1,3) epsilon = 0.1 x[0] += epsilon lmp.scatter_atoms("x",1,3,x) lmp.command("run 1"); f = lmp.extract_atom("f",3) print ("Force on 1 atom via extract_atom: ",f[0][0])