def _check_poscars(testCase, idx, fp_task_max, type_map): fp_path = os.path.join('iter.%06d' % idx, '02.fp') candi_files = glob.glob(os.path.join(fp_path, 'candidate.shuffled.*.out')) candi_files.sort() sys_idx = [str(os.path.basename(ii).split('.')[2]) for ii in candi_files] for sidx, ii in zip(sys_idx, candi_files): md_task = [] f_idx = [] with open(ii) as fp: for ii in fp: md_task.append(ii.split()[0]) f_idx.append(ii.split()[1]) md_task = md_task[:fp_task_max] f_idx = f_idx[:fp_task_max] cc = 0 for tt, ff in zip(md_task, f_idx): traj_file = os.path.join(tt, 'traj', '%d.lammpstrj' % int(ff)) poscar_file = os.path.join(fp_path, 'task.%03d.%06d' % (int(sidx), cc), 'POSCAR') cc += 1 sys0 = dpdata.System(traj_file, fmt='lammps/dump', type_map=type_map) sys1 = dpdata.System(poscar_file, fmt='vasp/poscar') test_atom_names(testCase, sys0, sys1)
def _check_confs(testCase, idx, jdata): md_dir = os.path.join('iter.%06d' % idx, '01.model_devi') tasks = glob.glob(os.path.join(md_dir, 'task.*')) tasks.sort() cur_job = jdata['model_devi_jobs'][idx] sys_idx = cur_job['sys_idx'] sys_configs = jdata['sys_configs'] poscars = [] for ii in sys_idx: sys_poscars = [] for ss in sys_configs[ii]: tmp_poscars = glob.glob(ss) sys_poscars += tmp_poscars sys_poscars.sort() poscars.append(sys_poscars) for ii in tasks: conf_file = os.path.join(ii, 'conf.lmp') l_conf_file = os.path.basename(os.readlink(conf_file)) poscar_file = poscars[int(l_conf_file.split('.')[0])][int( l_conf_file.split('.')[1])] sys_0 = dpdata.System(conf_file, type_map=jdata['type_map']) sys_1 = dpdata.System(poscar_file) test_atom_names(testCase, sys_0, sys_1) test_atom_types(testCase, sys_0, sys_1) test_cell(testCase, sys_0, sys_1) test_coord(testCase, sys_0, sys_1)
def setUp(self): tmp_system = dpdata.System() tmp_system.from_pwmat_atomconfig(os.path.join('pwmat', 'atom.config.oh')) # tmp_system.from_lammps_lmp(os.path.join('poscars', 'conf.lmp'), type_map = ['O', 'H']) tmp_system.to_pwmat_atomconfig('tmp.atom.config') self.system = dpdata.System() self.system.from_pwmat_atomconfig('tmp.atom.config')
def setUp(self): sys0 = dpdata.System('pwmat/atom.config', fmt='atom.config') sys0.data['atom_names'] = ['A', 'H', 'B', 'C', 'D'] sys0.data['atom_numbs'] = [0, 1, 0, 1, 0] sys0.data['atom_types'] = np.array([0, 0, 0, 1], dtype=int) sys1 = dpdata.System('pwmat/atom.config', fmt='pwmat/atom.config', type_map=['A', 'H', 'B', 'C', 'D']) self.system_1 = sys0 self.system_2 = sys1 self.places = 6 self.e_places = 6 self.f_places = 6 self.v_places = 6
def compute(self, output_dir): log_lammps = os.path.join(output_dir, 'log.lammps') if not os.path.isfile(log_lammps): warnings.warn("cannot find log.lammps in " + output_dir + " skip") return None else: with open(log_lammps, 'r') as fp: if 'Total wall time:' not in fp.read(): warnings.warn("lammps not finished " + log_lammps + " skip") return None else: fp.seek(0) lines = fp.read().split('\n') for ii in lines: if ("Total number of atoms" in ii) and (not 'print' in ii): natoms = float(ii.split('=')[1].split()[0]) if ("Final energy per atoms" in ii) and (not 'print' in ii): epa = float(ii.split('=')[1].split()[0]) dump = os.path.join(output_dir, 'dump.relax') contcar = os.path.join(output_dir, 'CONTCAR') d_dump = dpdata.System(dump, fmt='lammps/dump') d_dump.to('vasp/poscar', contcar, frame_idx=-1) force = d_dump['forces'] result_dict = { "energy": natoms * epa, "force": list(force[-1].reshape(natoms)) } return result_dict
def run_model_devi(iter_index, jdata, mdata): """submit dp test tasks""" iter_name = make_iter_name(iter_index) work_path = os.path.join(iter_name, model_devi_name) # generate command commands = [] tasks = glob.glob(os.path.join(work_path, "task.*")) run_tasks = [os.path.basename(ii) for ii in tasks] # get models models = glob.glob(os.path.join(work_path, "graph*pb")) model_names = [os.path.basename(ii) for ii in models] task_model_list = [] for ii in model_names: task_model_list.append(os.path.join('..', ii)) # get max data size data_size = max([ len(dpdata.System(os.path.join(task, rest_data_name), fmt="deepmd/npy")) for task in tasks ]) # models commands = [] detail_file_names = [] for ii, mm in enumerate(task_model_list): detail_file_name = "{prefix}.{ii}".format( prefix=detail_file_name_prefix, ii=ii, ) # TODO: support 0.x? command = "{python} -m deepmd test -m {model} -s {system} -n {numb_test} -d {detail_file}".format( python=mdata['python_test_path'], model=mm, system=rest_data_name, numb_test=data_size, detail_file=detail_file_name, ) commands.append(command) detail_file_names.append(detail_file_name) # submit try: model_devi_group_size = mdata['model_devi_group_size'] except: model_devi_group_size = 1 forward_files = [rest_data_name] backward_files = sum([[pf + ".e.out", pf + ".f.out", pf + ".v.out"] for pf in detail_file_names], []) dispatcher = make_dispatcher(mdata['model_devi_machine'], mdata['model_devi_resources'], work_path, run_tasks, model_devi_group_size) dispatcher.run_jobs(mdata['model_devi_resources'], commands, work_path, run_tasks, model_devi_group_size, model_names, forward_files, backward_files, outlog='model_devi.log', errlog='model_devi.log')
def make_fp_configs(iter_index, jdata): pick_data = jdata['pick_data'] use_clusters = jdata.get('use_clusters', False) iter_name = make_iter_name(iter_index) work_path = os.path.join(iter_name, fp_name) create_path(work_path) picked_data_path = os.path.join(iter_name, model_devi_name, picked_data_name) if use_clusters: systems = get_multi_system(picked_data_path, jdata) jj = 0 for system in systems: for subsys in system: task_name = "task." + fp_task_fmt % (0, jj) task_path = os.path.join(work_path, task_name) create_path(task_path) subsys.to('vasp/poscar', os.path.join(task_path, 'POSCAR')) jj += 1 else: picked_data_path = os.path.abspath(picked_data_path) sys_path = glob.glob(os.path.join(picked_data_path, sys_name_pattern)) for ii in sys_path: tmp_sys = dpdata.System(ii, fmt='deepmd/npy') sys_idx = os.path.basename(ii).split('.')[1] jj = 0 for ss in tmp_sys: task_name = "task." + fp_task_fmt % (int(sys_idx), jj) task_path = os.path.join(work_path, task_name) create_path(task_path) ss.to('vasp/poscar', os.path.join(task_path, 'POSCAR')) job = {} with open(os.path.join(task_path, 'job.json'), 'w') as fp: json.dump(job, fp, indent=4) jj += 1
def make_siesta(tdir, fp_params, fp_pp_path, fp_pp_files): cwd = os.getcwd() os.chdir(tdir) sys_data = dpdata.System('POSCAR').data ret = make_siesta_input(sys_data, fp_pp_files, fp_params) open('input', 'w').write(ret) os.chdir(cwd)
def test_make_confs_0(self): if not os.path.exists(os.path.join(self.equi_path, 'CONTCAR')): with self.assertRaises(RuntimeError): self.eos.make_confs(self.target_path, self.equi_path) shutil.copy(os.path.join(self.source_path, 'CONTCAR'), os.path.join(self.equi_path, 'CONTCAR')) task_list = self.eos.make_confs(self.target_path, self.equi_path) dfm_dirs = glob.glob(os.path.join(self.target_path, 'task.*')) incar0 = Incar.from_file(os.path.join('vasp_input', 'INCAR.rlx')) incar0['ISIF'] = 4 for ii in dfm_dirs: self.assertTrue(os.path.isfile(os.path.join(ii, 'POSCAR'))) eos_json_file = os.path.join(ii, 'eos.json') self.assertTrue(os.path.isfile(eos_json_file)) eos_json = loadfn(eos_json_file) self.assertEqual( os.path.realpath(os.path.join(ii, 'POSCAR.orig')), os.path.realpath(os.path.join(self.equi_path, 'CONTCAR'))) sys = dpdata.System(os.path.join(ii, 'POSCAR')) natoms = sys.get_natoms() self.assertAlmostEqual(eos_json['volume'], np.linalg.det(sys['cells'][0]) / natoms)
def _make_fake_md(idx, md_descript, atom_types, type_map) : """ md_descript: list of dimension [n_sys][n_MD][n_frame] """ natoms = len(atom_types) ntypes = len(type_map) atom_types = np.array(atom_types, dtype = int) atom_numbs = [np.sum(atom_types == ii) for ii in range(ntypes)] sys = dpdata.System() sys.data['atom_names'] = type_map sys.data['atom_numbs'] = atom_numbs sys.data['atom_types'] = atom_types for sidx,ss in enumerate(md_descript) : for midx,mm in enumerate(ss) : nframes = len(mm) cells = np.random.random([nframes,3,3]) coords = np.random.random([nframes,natoms,3]) sys.data['coords'] = coords sys.data['cells'] = cells task_dir = os.path.join('iter.%06d' % idx, '01.model_devi', 'task.%03d.%06d' % (sidx, midx)) os.makedirs(os.path.join(task_dir, 'traj'), exist_ok = True) for ii in range(nframes) : _write_lammps_dump(sys, os.path.join(task_dir, 'traj', '%d.lammpstrj' % ii)) md_out = np.zeros([nframes, 7]) md_out[:,0] = np.arange(nframes) md_out[:,4] = mm np.savetxt(os.path.join(task_dir, 'model_devi.out'), md_out)
def make_pwscf(tdir, fp_params, mass_map, fp_pp_path, fp_pp_files, user_input): cwd = os.getcwd() os.chdir(tdir) sys_data = dpdata.System('POSCAR').data sys_data['atom_masses'] = mass_map ret = make_pwscf_input(sys_data, fp_pp_files, fp_params) open('input', 'w').write(ret) os.chdir(cwd)
def take_cluster(old_conf_name, type_map, idx, jdata): cutoff = jdata['cluster_cutoff'] sys = dpdata.System(old_conf_name, fmt = 'lammps/dump', type_map = type_map) atom_names = sys['atom_names'] atom_types = sys['atom_types'] cell = sys['cells'][0] coords = sys['coords'][0] symbols = [atom_names[atom_type] for atom_type in atom_types] # detect fragment frag_numb, frag_index, graph = _crd2frag(symbols, coords, True, cell, return_bonds=True) # get_distances all_atoms = Atoms(symbols = symbols, positions = coords, pbc=True, cell=cell) all_atoms[idx].tag = 1 distances = all_atoms.get_distances(idx, range(len(all_atoms)), mic=True) distancescutoff = distances < cutoff cutoff_atoms_idx = np.where(distancescutoff)[0] # make cutoff atoms in molecules taken_atoms_idx = [] added = [] for ii in range(frag_numb): frag_atoms_idx = np.where(frag_index == ii)[0] if np.any(np.isin(frag_atoms_idx, cutoff_atoms_idx)): if 'cluster_minify' in jdata and jdata['cluster_minify']: # currently support C, H take_frag_idx=[] for aa in frag_atoms_idx: if np.any(np.isin(aa, cutoff_atoms_idx)): take_frag_idx.append(aa) elif np.count_nonzero(np.logical_and(distancescutoff, graph.toarray()[aa]==1)): if all_atoms[aa].symbol == 'H': take_frag_idx.append(aa) elif all_atoms[aa].symbol == 'C': near_atom_idx = np.nonzero(np.logical_and(distancescutoff, graph.toarray()[aa]>0))[0][0] vector = all_atoms[aa].position - all_atoms[near_atom_idx].position new_position = all_atoms[near_atom_idx].position + vector / np.linalg.norm(vector) * 1.09 added.append(Atom('H', new_position)) elif np.count_nonzero(np.logical_and(distancescutoff, graph.toarray()[aa]>1)): take_frag_idx=frag_atoms_idx break else: take_frag_idx = frag_atoms_idx taken_atoms_idx.append(take_frag_idx) all_taken_atoms_idx = np.concatenate(taken_atoms_idx) # wrap cutoff_atoms = sum(added, all_atoms[all_taken_atoms_idx]) cutoff_atoms.wrap( center=coords[idx] / cutoff_atoms.get_cell_lengths_and_angles()[0: 3], pbc=True) coords = cutoff_atoms.get_positions() sys.data['coords'] = np.array([coords]) sys.data['atom_types'] = np.array(list(atom_types[all_taken_atoms_idx]) + [atom_names.index('H')]*len(added)) sys.data['atom_pref'] = np.array([cutoff_atoms.get_tags()]) for ii, _ in enumerate(atom_names): sys.data['atom_numbs'][ii] = np.count_nonzero(sys.data['atom_types']==ii) return sys
def _get_res(self, res_dir): res = {} sys = dpdata.System(os.path.join(res_dir, 'POSCAR')) res['natoms'] = (sys['atom_numbs']) res['vol'] = np.linalg.det(sys['cells'][0]) res['nvalence'] = (self._get_potcar_nvalence( os.path.join(res_dir, 'POTCAR'))) res['ele_temp'] = self._get_incar_ele_temp( os.path.join(res_dir, 'INCAR')) * pc.electron_volt / pc.Boltzmann res['nbands'] = self._get_incar_nbands(os.path.join(res_dir, 'INCAR')) return res
def make_one(out_dir) : # [0.5, 1) [aa,bb,cc] = np.random.random(3) * 0.5 + 0.5 # [1, 179) [alpha,beta,gamma] = np.random.random(3) * (178 / 180) + 1 # make cell cell = ase.geometry.cellpar_to_cell([aa,bb,cc,alpha,beta,gamma]) sys = dpdata.System('POSCAR') sys['cells'][0] = cell os.makedirs(out_dir, exist_ok=True) sys.to_vasp_poscar(os.path.join(out_dir, 'POSCAR'))
def cvt_lammps_conf(fin, fout, ofmt = 'lammps/data'): """ Format convert from fin to fout, specify the output format by ofmt Imcomplete situation """ supp_ofmt = ['lammps/dump', 'lammps/data', 'vasp/poscar'] supp_exts = ['dump', 'lmp', 'poscar/POSCAR'] if 'dump' in fout : ofmt = 'lammps/dump' elif 'lmp' in fout : ofmt = 'lammps/data' elif 'poscar' in fout or 'POSCAR' in fout : ofmt = 'vasp/poscar' if not ofmt in supp_ofmt : raise RuntimeError ("output format " + ofmt + " is not supported. use one of " + str(supp_ofmt)) if 'lmp' in fout : d_poscar=dpdata.System(fin, fmt = 'vasp/poscar') d_poscar.to_lammps_lmp(fout, frame_idx=0) elif 'poscar' in fout or 'POSCAR' in fout: d_dump=dpdata.System(fin, fmt = 'lammps/dump') d_dump.to_vasp_poscar(fout, frame_idx=-1)
def make_fp_gaussian(iter_index, jdata): work_path = os.path.join(make_iter_name(iter_index), fp_name) fp_tasks = glob.glob(os.path.join(work_path, 'task.*')) cwd = os.getcwd() if 'user_fp_params' in jdata.keys(): fp_params = jdata['user_fp_params'] else: fp_params = jdata['fp_params'] cwd = os.getcwd() for ii in fp_tasks: os.chdir(ii) sys_data = dpdata.System('POSCAR').data ret = make_gaussian_input(sys_data, fp_params) with open('input', 'w') as fp: fp.write(ret) os.chdir(cwd)
def test_make_vasp_rlx_cell_shape (self): jdata = { 'relax_incar' : 'vasp_input/INCAR.rlx', 'potcar_map': {'Si': 'vasp_input/POTCAR' }, 'vol_start': 15, 'vol_end': 25, 'vol_step': 1.0, 'eos_relax_cell_shape': True, } make_vasp(jdata, 'confs/si/mp-149') target_path = '01.eos/si/mp-149/vasp-relax_incar' equi_path = '00.equi/si/mp-149/vasp-relax_incar' dfm_dirs = glob.glob(os.path.join(target_path, 'vol*')) # check root INCAR incar0 = Incar.from_file(os.path.join('vasp_input', 'INCAR.rlx')) incar1 = Incar.from_file(os.path.join(target_path, 'INCAR')) self.assertFalse(incar0 == incar1) incar0['ISIF'] = 4 self.assertTrue(incar0 == incar1) # check root POTCAR with open(os.path.join('vasp_input', 'POTCAR')) as fp: pot0 = fp.read() with open(os.path.join(target_path, 'POTCAR')) as fp: pot1 = fp.read() self.assertEqual(pot0, pot1) # check subdir for ii in dfm_dirs: self.assertTrue(os.path.isfile(os.path.join(ii, 'KPOINTS'))) self.assertEqual(os.path.realpath(os.path.join(ii, 'POSCAR.orig')), os.path.realpath(os.path.join(equi_path, 'CONTCAR'))) self.assertEqual(os.path.realpath(os.path.join(ii, 'INCAR')), os.path.realpath(os.path.join(target_path, 'INCAR'))) self.assertEqual(os.path.realpath(os.path.join(ii, 'POTCAR')), os.path.realpath(os.path.join(target_path, 'POTCAR'))) sys = dpdata.System(os.path.join(ii, 'POSCAR')) vol = float(ii.split('/')[-1].split('-')[1]) natoms = sys.get_natoms() self.assertAlmostEqual(vol, np.linalg.det(sys['cells'][0]) / natoms)
def lmp2pos(path, sel_nsw, copybs=False): """ build POSCAR based on XDATCAR given in the path copy INCAR, POTCAR, KPOINTS into the same folder """ # lmps1=glob.glob(os.path.join(path,'*lammps*')) lmps2 = glob.glob(os.path.join(path, '*dump*')) if lmps2 is []: print("No dump file found") elif not (lmps2 is []): lmp = lmps2[0] # elif not(lmps1 is []): # lmp = lmps1[0] else: print("No dump file and lammps file found") path = os.path.join(path, 'recal') ls = dpdata.System(lmp, fmt='lammps/dump') if sel_nsw is None: sel_nsw = range(0, len(ls), args.step) else: sel_nsw = sel_nsw for i in sel_nsw: print(i) if os.path.exists(os.path.join(path, str(i + 1))): print("Folder {0} already exists,skip making".format(i)) else: os.mkdir(os.path.join(path, str(i + 1))) # return None target_path = os.path.join(path, str(i + 1)) ls.to_vasp_poscar(os.path.join(target_path, 'POSCAR'), frame_idx=i) copy(os.path.join(inputfile, 'INCAR'), target_path) copy(os.path.join(inputfile, 'KPOINTS'), target_path) copy(os.path.join(inputfile, 'POTCAR'), target_path) if run_vasp: run(cwd, target_path)
def make_lammps_input(ensemble, conf_file, graphs, nsteps, dt, neidelay, trj_freq, mass_map, temp, tau_t=0.1, pres=None, tau_p=0.5, pka_e=None, max_seed=1000000): ret = "variable NSTEPS equal %d\n" % nsteps ret += "variable THERMO_FREQ equal %d\n" % trj_freq ret += "variable DUMP_FREQ equal %d\n" % trj_freq ret += "variable TEMP equal %f\n" % temp ret += "variable PRES equal %f\n" % pres ret += "variable TAU_T equal %f\n" % tau_t ret += "variable TAU_P equal %f\n" % tau_p ret += "\n" ret += "units metal\n" ret += "boundary p p p\n" ret += "atom_style atomic\n" ret += "\n" ret += "neighbor 1.0 bin\n" if neidelay is not None: ret += "neigh_modify delay %d\n" % neidelay ret += "\n" ret += "box tilt large\n" ret += "read_data %s\n" % conf_file ret += "change_box all triclinic\n" for jj in range(len(mass_map)): ret += "mass %d %f\n" % (jj + 1, mass_map[jj]) graph_list = "" for ii in graphs: graph_list += ii + " " ret += "pair_style deepmd %s ${THERMO_FREQ} model_devi.out\n" % graph_list ret += "pair_coeff \n" ret += "\n" ret += "thermo_style custom step temp pe ke etotal press vol lx ly lz xy xz yz\n" ret += "thermo ${THERMO_FREQ}\n" ret += "dump 1 all custom ${DUMP_FREQ} traj/*.lammpstrj id type x y z\n" ret += "\n" if pka_e is None: ret += "velocity all create ${TEMP} %d" % ( random.randrange(max_seed - 1) + 1) else: sys = dpdata.System(conf_file, fmt='lammps/lmp') sys_data = sys.data pka_mass = mass_map[sys_data['atom_types'][0] - 1] pka_vn = pka_e * pc.electron_volt / \ (0.5 * pka_mass * 1e-3 / pc.Avogadro * (pc.angstrom / pc.pico) ** 2) pka_vn = np.sqrt(pka_vn) print(pka_vn) pka_vec = _sample_sphere() pka_vec *= pka_vn ret += 'group first id 1\n' ret += 'velocity first set %f %f %f\n' % ( pka_vec[0], pka_vec[1], pka_vec[2]) ret += 'fix 2 all momentum 1 linear 1 1 1\n' ret += "\n" if ensemble.split('-')[0] == 'npt': assert (pres is not None) if ensemble == "npt" or ensemble == "npt-i" or ensemble == "npt-iso": ret += "fix 1 all npt temp ${TEMP} ${TEMP} ${TAU_T} iso ${PRES} ${PRES} ${TAU_P}\n" elif ensemble == 'npt-a' or ensemble == 'npt-aniso': ret += "fix 1 all npt temp ${TEMP} ${TEMP} ${TAU_T} aniso ${PRES} ${PRES} ${TAU_P}\n" elif ensemble == 'npt-t' or ensemble == 'npt-tri': ret += "fix 1 all npt temp ${TEMP} ${TEMP} ${TAU_T} tri ${PRES} ${PRES} ${TAU_P}\n" elif ensemble == "nvt": ret += "fix 1 all nvt temp ${TEMP} ${TEMP} ${TAU_T}\n" elif ensemble == 'nve': ret += "fix 1 all nve\n" else: raise RuntimeError("unknown emsemble " + ensemble) ret += "\n" ret += "timestep %f\n" % dt ret += "run ${NSTEPS}\n" return ret
dr = np.linalg.norm(diff) # if (np.linalg.norm(diff- diff_1)) > 1e-12 : # raise RuntimeError si = int(dr / hh) if si < nbins: stat[si] += 1 # count the number of atom1 c0 = 0 for ii in sel_type[0]: c0 += np.sum(atype == ii) # count the number of atom1 c1 = 0 for ii in sel_type[1]: c1 += np.sum(atype == ii) rho1 = c1 / np.linalg.det(box) # compute rdf for ii in range(nbins): vol = 4. / 3. * np.pi * (((ii + 1) * hh)**3 - ((ii) * hh)**3) rho = stat[ii] / vol stat[ii] = rho / rho1 / c0 xx = np.arange(0, max_r - 1e-12, hh) return xx, stat if __name__ == '__main__': import dpdata sys = dpdata.System('out.lmp') xx, stat = rdf(sys, sel_type=[[0], None], max_r=8, nbins=100) res = np.concatenate([xx, stat]).reshape([2, -1]) np.savetxt('rdf.out', res.T)
forces.append(labeled['forces']) forces = np.array(forces) max_devi_f = calc_model_devi_f(forces) model_devi_out = np.zeros((system.get_nframes(), 7)) model_devi_out[:, 0] += np.arange(system.get_nframes()) * trj_freq model_devi_out[:, 4] += max_devi_f if fname is not None: np.savetxt( fname, model_devi_out, fmt=['%d'] + ['%.8e' for _ in range(6)], delimiter='\t', header= 'step\tmax_devi_e\tmin_devi_e\tavg_devi_e\tmax_devi_f\tmin_devi_f\tavg_devi_f' ) return model_devi_out if __name__ == "__main__": system = dpdata.System(sys.argv[1], fmt='gromacs/gro') if os.path.isfile("job.json"): trj_freq = json.load(open("job.json")).get("trj_freq", 10) else: trj_freq = 10 if not os.path.isdir("traj"): os.mkdir("traj") for i in range(system.get_nframes()): system[i].to_gromacs_gro("traj/%d.gromacstrj" % (trj_freq * i)) models = [DP(f"../graph.{ii:03}.pb") for ii in range(4)] write_model_devi_out(system, models, "model_devi.out", trj_freq)
import dpdata import numpy as np import glob import argparse parser = argparse.ArgumentParser() #l1=dpdata.System('/Users/jiedeng/Documents/ml/deepmd-kit/my_example/tail_3.dump') parser.add_argument("--file", "-f", type=str, default='dump.0', help="name of dump file,default dump.0") parser.add_argument("--sigma", "-s", type=float, help="sigma = kb*T") args = parser.parse_args() l1 = dpdata.System(args.file, fmt='lammps/dump') l1.to_deepmd_npy( 'test', set_size=1000000, ) # default set size is 5000 l1.to_deepmd_raw('test') sigma = args.sigma sets = glob.glob('test/*set*') for seti in sets: print(seti) box = np.load(seti + '/box.npy') nsw = box.size // 9 print("the size of the file is: ", nsw) all_te = np.ones((nsw, )) * sigma np.save(seti + '/fparam.npy', all_te) print('done')
def setUp(self): self.system = dpdata.System() self.system.from_pwmat_atomconfig(os.path.join('pwmat', 'atom.config'))
def save(pos, vasp='pos_mgo.vasp', lmp='pos_mgo.lmp'): struct.set_positions(pos) ase.io.write(vasp, struct, format='vasp', vasp5=True, direct=True) ls = dpdata.System(vasp, fmt='vasp/poscar') ls.to_lammps_lmp(lmp)
def test_dump_pwmat_type_map(self): system0 = dpdata.System(os.path.join('pwmat', 'atom.config.oh'), fmt = 'pwmat/atom.config', type_map = ['H', 'O']) system0.to_pwmat_atomconfig('atom.config.tmp.1') system1 = dpdata.System(os.path.join('pwmat', 'atom.config.oh'), fmt = 'pwmat/atom.config', type_map = ['C', 'H', 'A', 'O', 'B']) system1.to_pwmat_atomconfig('atom.config.tmp.2') myfilecmp(self, 'atom.config.tmp.1', 'atom.config.tmp.2')
def take_cluster(old_conf_name, type_map, idx, jdata): cutoff = jdata['cluster_cutoff'] cutoff_hard = jdata.get('cluster_cutoff_hard', None) sys = dpdata.System(old_conf_name, fmt = 'lammps/dump', type_map = type_map) atom_names = sys['atom_names'] atom_types = sys['atom_types'] cell = sys['cells'][0] coords = sys['coords'][0] symbols = [atom_names[atom_type] for atom_type in atom_types] # detect fragment frag_numb, frag_index, graph = _crd2frag(symbols, coords, True, cell, return_bonds=True) # get_distances all_atoms = Atoms(symbols = symbols, positions = coords, pbc=True, cell=cell) all_atoms[idx].tag = 1 distances = all_atoms.get_distances(idx, range(len(all_atoms)), mic=True) distancescutoff = distances < cutoff cutoff_atoms_idx = np.where(distancescutoff)[0] if cutoff_hard is not None: distancescutoff_hard = distances < cutoff_hard cutoff_atoms_idx_hard = np.where(distancescutoff_hard)[0] # make cutoff atoms in molecules taken_atoms_idx = [] added = [] for ii in range(frag_numb): frag_atoms_idx = np.where(frag_index == ii)[0] if cutoff_hard is not None: # drop atoms out of the hard cutoff anyway frag_atoms_idx = np.intersect1d(frag_atoms_idx, cutoff_atoms_idx_hard) if np.any(np.isin(frag_atoms_idx, cutoff_atoms_idx)): if 'cluster_minify' in jdata and jdata['cluster_minify']: # support for organic species take_frag_idx=[] for aa in frag_atoms_idx: if np.any(np.isin(aa, cutoff_atoms_idx)): # atom is in the soft cutoff # pick up anyway take_frag_idx.append(aa) elif np.count_nonzero(np.logical_and(distancescutoff, graph.toarray()[aa]==1)): # atom is between the hard cutoff and the soft cutoff # and has a single bond with the atom inside if all_atoms[aa].symbol == 'H': # for atom H: just add it take_frag_idx.append(aa) else: # for other atoms (C, O, etc.): replace it with a ghost H atom near_atom_idx = np.nonzero(np.logical_and(distancescutoff, graph.toarray()[aa]>0))[0][0] vector = all_atoms[aa].position - all_atoms[near_atom_idx].position new_position = all_atoms[near_atom_idx].position + vector / np.linalg.norm(vector) * 1.09 added.append(Atom('H', new_position)) elif np.count_nonzero(np.logical_and(distancescutoff, graph.toarray()[aa]>1)): # if that atom has a double bond with the atom inside # just pick up the whole fragment (within the hard cutoff) # TODO: use a more fantastic method take_frag_idx=frag_atoms_idx break else: take_frag_idx = frag_atoms_idx taken_atoms_idx.append(take_frag_idx) all_taken_atoms_idx = np.concatenate(taken_atoms_idx) # wrap cutoff_atoms = sum(added, all_atoms[all_taken_atoms_idx]) cutoff_atoms.wrap( center=coords[idx] / cutoff_atoms.get_cell_lengths_and_angles()[0: 3], pbc=True) coords = cutoff_atoms.get_positions() sys.data['coords'] = np.array([coords]) sys.data['atom_types'] = np.array(list(atom_types[all_taken_atoms_idx]) + [atom_names.index('H')]*len(added)) sys.data['atom_pref'] = np.array([cutoff_atoms.get_tags()]) for ii, _ in enumerate(atom_names): sys.data['atom_numbs'][ii] = np.count_nonzero(sys.data['atom_types']==ii) return sys
def make_lammps_input(ensemble, conf_file, graphs, nsteps, dt, neidelay, trj_freq, mass_map, temp, jdata, tau_t=0.1, pres=None, tau_p=0.5, pka_e=None, ele_temp_f=None, ele_temp_a=None, max_seed=1000000, nopbc=False, deepmd_version='0.1'): if (ele_temp_f is not None or ele_temp_a is not None) and LooseVersion(deepmd_version) < LooseVersion('1'): raise RuntimeError( 'the electron temperature is only supported by deepmd-kit >= 1.0.0, please upgrade your deepmd-kit' ) if ele_temp_f is not None and ele_temp_a is not None: raise RuntimeError( 'the frame style ele_temp and atom style ele_temp should not be set at the same time' ) ret = "variable NSTEPS equal %d\n" % nsteps ret += "variable THERMO_FREQ equal %d\n" % trj_freq ret += "variable DUMP_FREQ equal %d\n" % trj_freq ret += "variable TEMP equal %f\n" % temp if ele_temp_f is not None: ret += "variable ELE_TEMP equal %f\n" % ele_temp_f if ele_temp_a is not None: ret += "variable ELE_TEMP equal %f\n" % ele_temp_a ret += "variable PRES equal %f\n" % pres ret += "variable TAU_T equal %f\n" % tau_t ret += "variable TAU_P equal %f\n" % tau_p ret += "\n" ret += "units metal\n" if nopbc: ret += "boundary f f f\n" else: ret += "boundary p p p\n" ret += "atom_style atomic\n" ret += "\n" ret += "neighbor 1.0 bin\n" if neidelay is not None: ret += "neigh_modify delay %d\n" % neidelay ret += "\n" ret += "box tilt large\n" ret += "if \"${restart} > 0\" then \"read_restart dpgen.restart.*\" else \"read_data %s\"\n" % conf_file ret += "change_box all triclinic\n" for jj in range(len(mass_map)): ret += "mass %d %f\n" % (jj + 1, mass_map[jj]) graph_list = "" for ii in graphs: graph_list += ii + " " if LooseVersion(deepmd_version) < LooseVersion('1'): # 0.x ret += "pair_style deepmd %s ${THERMO_FREQ} model_devi.out\n" % graph_list else: # 1.x keywords = "" if jdata.get('use_clusters', False): keywords += "atomic " if jdata.get('use_relative', False): keywords += "relative %s " % jdata['epsilon'] if jdata.get('use_relative_v', False): keywords += "relative_v %s " % jdata['epsilon_v'] if ele_temp_f is not None: keywords += "fparam ${ELE_TEMP}" if ele_temp_a is not None: keywords += "aparam ${ELE_TEMP}" ret += "pair_style deepmd %s out_freq ${THERMO_FREQ} out_file model_devi.out %s\n" % ( graph_list, keywords) ret += "pair_coeff * *\n" ret += "\n" ret += "thermo_style custom step temp pe ke etotal press vol lx ly lz xy xz yz\n" ret += "thermo ${THERMO_FREQ}\n" ret += "dump 1 all custom ${DUMP_FREQ} traj/*.lammpstrj id type x y z fx fy fz\n" ret += "restart 10000 dpgen.restart\n" ret += "\n" if pka_e is None: ret += "if \"${restart} == 0\" then \"velocity all create ${TEMP} %d\"" % ( random.randrange(max_seed - 1) + 1) else: sys = dpdata.System(conf_file, fmt='lammps/lmp') sys_data = sys.data pka_mass = mass_map[sys_data['atom_types'][0] - 1] pka_vn = pka_e * pc.electron_volt / \ (0.5 * pka_mass * 1e-3 / pc.Avogadro * (pc.angstrom / pc.pico) ** 2) pka_vn = np.sqrt(pka_vn) print(pka_vn) pka_vec = _sample_sphere() pka_vec *= pka_vn ret += 'group first id 1\n' ret += 'if \"${restart} == 0\" then \"velocity first set %f %f %f\"\n' % ( pka_vec[0], pka_vec[1], pka_vec[2]) ret += 'fix 2 all momentum 1 linear 1 1 1\n' ret += "\n" if ensemble.split('-')[0] == 'npt': assert (pres is not None) if nopbc: raise RuntimeError('ensemble %s is conflicting with nopbc' % ensemble) if ensemble == "npt" or ensemble == "npt-i" or ensemble == "npt-iso": ret += "fix 1 all npt temp ${TEMP} ${TEMP} ${TAU_T} iso ${PRES} ${PRES} ${TAU_P}\n" elif ensemble == 'npt-a' or ensemble == 'npt-aniso': ret += "fix 1 all npt temp ${TEMP} ${TEMP} ${TAU_T} aniso ${PRES} ${PRES} ${TAU_P}\n" elif ensemble == 'npt-t' or ensemble == 'npt-tri': ret += "fix 1 all npt temp ${TEMP} ${TEMP} ${TAU_T} tri ${PRES} ${PRES} ${TAU_P}\n" elif ensemble == "nvt": ret += "fix 1 all nvt temp ${TEMP} ${TEMP} ${TAU_T}\n" elif ensemble == 'nve': ret += "fix 1 all nve\n" else: raise RuntimeError("unknown emsemble " + ensemble) if nopbc: ret += "velocity all zero linear\n" ret += "fix fm all momentum 1 linear 1 1 1\n" ret += "\n" ret += "timestep %f\n" % dt ret += "run ${NSTEPS} upto\n" return ret
parser.add_argument("--range", "-r", type=str, help="0-2, means from 0 to 2, default is for all folders") parser.add_argument("--run_vasp", "-rv", help="run vasp?, default without input is Yes") args = parser.parse_args() print(args.run_vasp) cwd = os.getcwd() if args.deepmd: print("Check files in {0} ".format(args.deepmd)) # inputpath = args.inputpath # paths = load_paths(inputpath) ls = dpdata.System(args.deepmd, fmt='deepmd/npy') else: print("deepmd path is not provided .") ls = dpdata.System('.', fmt='deepmd/npy') if args.inputfile: print("Check files in {0} ".format(args.inputfile)) inputfile = args.inputfile else: print("No folders point are provided. Use default value folders") inputfile = os.path.join(cwd, 'inputs') # change inputfile to absolute path, chdir occurs when submitting job inputfile = os.path.abspath(inputfile) sel_nsw = None