def get_relaxed_cell_via_dpdata(self, atom_dump_path, element_symbols): s = System(atom_dump_path, fmt='lammps/dump', type_map=element_symbols) st = s.to_pymatgen_structure()[0] return Cell(st.lattice, st.species, st.cart_coords, coords_are_cartesian=True)
def to_system(self, data, **kwargs): """ convert system to list, usefull for data collection """ from dpdata import System, LabeledSystem if 'forces' in data: system = LabeledSystem(data=data) else: system = System(data=data) if len(system) == 0: return [] if len(system) == 1: return [system] else: systems = [] for ii in range(len(system)): systems.append(system.sub_system([ii])) return systems
def structure2system(structure): atom_numbs = [] atom_names = [] comp = structure.composition symbol = sorted(structure.symbol_set) el_map = dict(zip(symbol, range(len(symbol)))) atom_types = [el_map[ii.symbol] for ii in structure.species] cell = structure.lattice.matrix coords = structure.cart_coords for el in structure.symbol_set: atom_numbs.append(int(comp[el])) atom_names.append(el) data = { "atom_numbs": atom_numbs, "atom_names": atom_names, "atom_types": atom_types, "cells": cell.reshape(1, 3, 3), "coords": coords.reshape(1, sum(atom_numbs), 3), "orig": np.array([0, 0, 0]) } return System(data=data)
def build_deepmd_frames(path, outcar, deepmd): """ sub_ls = ls.sub_system(idx) """ try: ls = LabeledSystem(outcar, fmt=args.format) except: ls = System(outcar, fmt=args.format) if args.exclude: oldsize = len(ls) idx_new = [i for i in range(len(ls)) if i not in args.exclude] ls = ls.sub_system(idx_new) newsize = len(ls) print('{0}/{1} is selected'.format(newsize, oldsize)) if args.force_limit: fmin = min(args.force_limit) fmax = max(args.force_limit) print("force limit imposed, force in between {0}, {1}".format( fmin, fmax)) idx_new = [] exclude = [] for i in range(len(ls)): forces = ls[i].data['forces'] if forces.min() >= fmin and forces.max() <= fmax: idx_new.append(i) else: exclude.append(i) print('excluded frames', exclude) print('{0} / {1} is selected'.format(len(idx_new), len(ls))) ls = ls.sub_system(idx_new) if args.idx: print("index file provided") idx = np.loadtxt(args.idx).astype(int) elif (not args.idx) and args.vaspidx: print("vasp index file provided") vaspidx = np.loadtxt(args.vaspidx) fp = open(outcar) fp.readline() nsw_sel = fp.readline() if 'nsw_sel' in nsw_sel: print('file generated by merge_out.py') tmp = nsw_sel.split('=')[1].strip().split(' ') nsw_sel = [int(tmp_idx) for tmp_idx in tmp] idx = [] for i in range(len(nsw_sel)): if nsw_sel[i] in vaspidx: idx.append(i) else: print('OUTCAR file generated by VASP') idx = vaspidx - 1 else: print("split train and test by ratio {0} : {1}".format( args.train_test_ratio, 1)) train_size = round( len(ls) * (args.train_test_ratio) / (args.train_test_ratio + 1)) idx = np.random.choice(range(len(ls)), train_size, replace=False) idx.sort() idx2 = [i for i in range(len(ls)) if i not in idx] # test ls2 = ls.sub_system(idx2) # test ls = ls.sub_system(idx) deepmd = os.path.join(path, deepmd) ls.to_deepmd_npy(deepmd, set_size=1000000) # give a *large* value, default is 5000 if len(ls2) == 0: print('test set has no data') elif args.savetest and len(ls2) > 0: ls2.to_deepmd_npy('test_tmp', set_size=1000000) shutil.copytree('test_tmp/set.000', os.path.join(deepmd, 'set.001')) shutil.rmtree('test_tmp')
import numpy as np from maptool.core.analysis import rdf from dpdata import System ls = System('dump_npt_470.atom', fmt='lammps/dump', type_map=['Li']) sls = ls.sub_system(range(int(0.5 * len(ls)), len(ls))) pmg_sts = sls.to_pymatgen_structure() d = [st.density for st in pmg_sts] print(np.std(d)) print(np.mean(d)) rdf, radii = rdf(pmg_sts, 10, 200, (0, 10)) ret = np.vstack((radii, rdf)).T print(ret.shape) np.savetxt('rn.txt', ret)
import numpy as np from maptool.core.analysis import rdf from dpdata import System ls = System('dump_nvt_470.atom', fmt='lammps/dump', type_map=['Li']) sls = ls.sub_system(range(1000, len(ls))) pmg_sts = sls.to_pymatgen_structure() d = [st.density for st in pmg_sts] print(np.mean(d))
def do_energy_calculation(self, organism, dictionary, key, composition_space, element_order=None): """ Calculates the energy of an organism using LAMMPS, and stores the relaxed organism in the provided dictionary at the provided key. If the calculation fails, stores None in the dictionary instead. Args: organism: the Organism whose energy we want to calculate dictionary: a dictionary in which to store the relaxed Organism key: the key specifying where to store the relaxed Organism in the dictionary composition_space: the CompositionSpace of the search Precondition: the garun directory and temp subdirectory exist, and we are currently located inside the garun directory """ # make the job directory job_dir_path = str(os.getcwd()) + '/temp/' + str(organism.id) os.mkdir(job_dir_path) # copy the lammps input script to the job directory and get its path shutil.copy(self.input_script, job_dir_path) script_name = os.path.basename(self.input_script) input_script_path = job_dir_path + '/' + str(script_name) # write the in.data file self.conform_to_lammps(organism.cell) # print(organism.cell) # print(job_dir_path) # print(composition_space) # print(composition_space.get_all_elements()) #em_list=['Mg',"Al","Cu"] #em_list=["Li"] #self.write_data_file(organism, job_dir_path, composition_space) # write out the unrelaxed structure to a poscar file organism.cell.sort() organism.cell.to(fmt='poscar', filename=job_dir_path + '/POSCAR.' + str(organism.id) + '_unrelaxed') ls = System(job_dir_path + '/POSCAR.' + str(organism.id) + '_unrelaxed', fmt='poscar', type_map=element_order) ls.to_lammps_lmp(job_dir_path + '/in.data') # run 'calllammps' script as a subprocess to run LAMMPS print('Starting LAMMPS calculation on organism {} '.format( organism.id)) try: lammps_output = subprocess.check_output( ['calllammps', input_script_path], stderr=subprocess.STDOUT) # convert from bytes to string (for Python 3) lammps_output = lammps_output.decode('utf-8') except subprocess.CalledProcessError as e: # write the output of a bad LAMMPS call to for the user's reference with open(job_dir_path + '/log.lammps', 'w') as log_file: log_file.write(e.output.decode('utf-8')) print('Error running LAMMPS on organism {} '.format(organism.id)) dictionary[key] = None return # write the LAMMPS output with open(job_dir_path + '/log.lammps', 'w') as log_file: log_file.write(lammps_output) # parse the relaxed structure from the atom.dump file symbols = [] all_elements = composition_space.get_all_elements() for element in all_elements: symbols.append(element.symbol) #relaxed_cell = self.get_relaxed_cell( # job_dir_path + '/dump.atom', job_dir_path + '/in.data', # symbols) try: relaxed_cell = self.get_relaxed_cell_via_dpdata( job_dir_path + '/dump.atom', symbols) except: print('Error reading structure of organism {} from LAMMPS ' 'output '.format(organism.id)) dictionary[key] = None return # parse the total energy from the log.lammps file try: total_energy = self.get_energy(job_dir_path + '/log.lammps') except: print('Error reading energy of organism {} from LAMMPS ' 'output '.format(organism.id)) dictionary[key] = None return # check that the total energy isn't unphysically large # (can be a problem for empirical potentials) epa = total_energy / organism.cell.num_sites if epa < -50: print('Discarding organism {} due to unphysically large energy: ' '{} eV/atom.'.format(organism.id, str(epa))) dictionary[key] = None return organism.cell = relaxed_cell organism.total_energy = total_energy organism.epa = epa print('Setting energy of organism {} to {} eV/atom '.format( organism.id, organism.epa)) dictionary[key] = organism
### run fix fix_nve all nve dump dump_all all custom 1 dump.dat id type x y z vx vy vz fx fy fz thermo_style custom step press ke pe etotal vol lx ly lz atoms thermo_modify flush yes format float %15.8g thermo 1 run 0 """ pwd=os.getcwd() #fs=["Mg2Al10-2-170.vasp"] #fs=["Mg9-166-23.vasp"] #fs=["Al4-225-24.vasp"] paths=["1.03"] for path in paths: os.chdir(path) s=System('CONTCAR',fmt='poscar') st=s.copy() etyp=s.get_atom_names() s.apply_type_map(['Al','Mg']) s.to_lammps_lmp('lmp.conf') if etyp==['Al']: f2=""" mass 1 26.981538 """ else : f2=""" mass 1 26.981538 mass 2 24.305000 """ with open('in.lmp','w') as fid: fid.write(f1+f2+f3)