def setUp(self): self.norm_str = Strain.from_deformation([[1.02, 0, 0], [0, 1, 0], [0, 0, 1]]) self.ind_str = Strain.from_deformation([[1, 0.02, 0], [0, 1, 0], [0, 0, 1]]) self.non_ind_str = Strain.from_deformation([[1, 0.02, 0.02], [0, 1, 0], [0, 0, 1]]) with warnings.catch_warnings(record=True): warnings.simplefilter("always") self.no_dfm = Strain([[0.0, 0.01, 0.0], [0.01, 0.0002, 0.0], [0.0, 0.0, 0.0]])
def setUp(self): self.norm_str = Strain.from_deformation([[1.02, 0, 0], [0, 1, 0], [0, 0, 1]]) self.ind_str = Strain.from_deformation([[1, 0.02, 0], [0, 1, 0], [0, 0, 1]]) self.non_ind_str = Strain.from_deformation([[1, 0.02, 0.02], [0, 1, 0], [0, 0, 1]]) with warnings.catch_warnings(record=True): warnings.simplefilter("always") self.no_dfm = Strain([[0., 0.01, 0.], [0.01, 0.0002, 0.], [0., 0., 0.]])
def test_energy_density(self): film_elac = ElasticTensor.from_voigt( [[324.32, 187.3, 170.92, 0., 0., 0.], [187.3, 324.32, 170.92, 0., 0., 0.], [170.92, 170.92, 408.41, 0., 0., 0.], [0., 0., 0., 150.73, 0., 0.], [0., 0., 0., 0., 150.73, 0.], [0., 0., 0., 0., 0., 238.74]]) dfm = Deformation([[-9.86004855e-01, 2.27539582e-01, -4.64426035e-17], [-2.47802121e-01, -9.91208483e-01, -7.58675185e-17], [-6.12323400e-17, -6.12323400e-17, 1.00000000e+00]]) self.assertAlmostEqual( film_elac.energy_density(dfm.green_lagrange_strain), 0.00125664672793) film_elac.energy_density( Strain.from_deformation([[0.99774738, 0.11520994, -0.], [-0.11520994, 0.99774738, 0.], [ -0., -0., 1., ]]))
def test_from_strain_stress_list(self): strain_list = [Strain.from_deformation(def_matrix) for def_matrix in self.def_stress_dict['deformations']] stress_list = [stress for stress in self.def_stress_dict['stresses']] with warnings.catch_warnings(record = True): et_fl = -0.1*ElasticTensor.from_strain_stress_list(strain_list, stress_list) self.assertArrayAlmostEqual(et_fl.round(2), [[59.29, 24.36, 22.46, 0, 0, 0], [28.06, 56.91, 22.46, 0, 0, 0], [28.06, 25.98, 54.67, 0, 0, 0], [0, 0, 0, 26.35, 0, 0], [0, 0, 0, 0, 26.35, 0], [0, 0, 0, 0, 0, 26.35]])
def test_from_pseudoinverse(self): strain_list = [Strain.from_deformation(def_matrix) for def_matrix in self.def_stress_dict['deformations']] stress_list = [stress for stress in self.def_stress_dict['stresses']] with warnings.catch_warnings(record=True): et_fl = -0.1*ElasticTensor.from_pseudoinverse(strain_list, stress_list).voigt self.assertArrayAlmostEqual(et_fl.round(2), [[59.29, 24.36, 22.46, 0, 0, 0], [28.06, 56.91, 22.46, 0, 0, 0], [28.06, 25.98, 54.67, 0, 0, 0], [0, 0, 0, 26.35, 0, 0], [0, 0, 0, 0, 26.35, 0], [0, 0, 0, 0, 0, 26.35]])
def run_task(self, fw_spec): v, _ = get_vasprun_outcar(self.get("calc_dir", "."), parse_dos=False, parse_eigen=False) stress = v.ionic_steps[-1]['stress'] defo = self['deformation'] d_ind = np.nonzero(defo - np.eye(3)) delta = Decimal((defo - np.eye(3))[d_ind][0]) # Shorthand is d_X_V, X is voigt index, V is value dtype = "_".join(["d", str(reverse_voigt_map[d_ind][0]), "{:.0e}".format(delta)]) strain = Strain.from_deformation(defo) defo_dict = {'deformation_matrix': defo, 'strain': strain.tolist(), 'stress': stress} return FWAction(mod_spec=[{'_set': { 'deformation_tasks->{}'.format(dtype): defo_dict}}])
def test_energy_density(self): film_elac = ElasticTensor.from_voigt([ [324.32, 187.3, 170.92, 0., 0., 0.], [187.3, 324.32, 170.92, 0., 0., 0.], [170.92, 170.92, 408.41, 0., 0., 0.], [0., 0., 0., 150.73, 0., 0.], [0., 0., 0., 0., 150.73, 0.], [0., 0., 0., 0., 0., 238.74]]) dfm = Deformation([[ -9.86004855e-01,2.27539582e-01,-4.64426035e-17], [ -2.47802121e-01,-9.91208483e-01,-7.58675185e-17], [ -6.12323400e-17,-6.12323400e-17,1.00000000e+00]]) self.assertAlmostEqual(film_elac.energy_density(dfm.green_lagrange_strain), 0.00125664672793) film_elac.energy_density(Strain.from_deformation([[ 0.99774738, 0.11520994, -0. ], [-0.11520994, 0.99774738, 0. ], [-0., -0., 1., ]]))
def run_task(self, fw_spec): v, _ = get_vasprun_outcar(self.get("calc_dir", "."), parse_dos=False, parse_eigen=False) stress = v.ionic_steps[-1]['stress'] defo = self['deformation'] d_ind = np.nonzero(defo - np.eye(3)) delta = Decimal((defo - np.eye(3))[d_ind][0]) # Shorthand is d_X_V, X is voigt index, V is value dtype = "_".join( ["d", str(reverse_voigt_map[d_ind][0]), "{:.0e}".format(delta)]) strain = Strain.from_deformation(defo) defo_dict = { 'deformation_matrix': defo, 'strain': strain.tolist(), 'stress': stress } return FWAction(mod_spec=[{ '_set': { 'deformation_tasks->{}'.format(dtype): defo_dict } }])
def runSimulation(self): if self.args["pymatgen"] == True: starting_struct = singleFromFile(self.args) info = runCalc("all_relax", ["structures","stresses"], [starting_struct], self.args) relaxed_struct = info["structures"][0] relaxed_stress = info["stresses"][0] strains = [] deformed_set = DeformedStructureSet(relaxed_struct, symmetry=True) deformed_structs = deformed_set.deformed_structures symmetry_dict = deformed_set.sym_dict deformations = deformed_set.deformations stresses = runCalc("atom_relax", ["stresses"], deformed_structs, self.args)["stresses"] for i in range(len(deformations)): strains.append(Strain.from_deformation(deformations[i])) for i in range(len(deformations)): for symm in symmetry_dict[deformations[i]]: strains.append(strains[i].transform(symm)) stresses.append(stresses[i].transform(symm)) self.elastic_tensor = ElasticTensor.from_independent_strains(strains,stresses,eq_stress=relaxed_stress,vasp=True).zeroed().voigt
def make_vasp(jdata, conf_dir, norm_def = 2e-3, shear_def = 5e-3) : norm_def = jdata['norm_deform'] shear_def = jdata['shear_deform'] conf_path = os.path.abspath(conf_dir) conf_poscar = os.path.join(conf_path, 'POSCAR') # get equi poscar if 'relax_incar' in jdata.keys(): vasp_str='vasp-relax_incar' else: kspacing = jdata['vasp_params']['kspacing'] vasp_str='vasp-k%.2f' % kspacing equi_path = re.sub('confs', global_equi_name, conf_path) equi_path = os.path.join(equi_path, vasp_str) equi_contcar = os.path.join(equi_path, 'CONTCAR') task_path = re.sub('confs', global_task_name, conf_path) task_path = os.path.join(task_path, vasp_str) os.makedirs(task_path, exist_ok=True) cwd = os.getcwd() os.chdir(task_path) if os.path.isfile('POSCAR') : os.remove('POSCAR') os.symlink(os.path.relpath(equi_contcar), 'POSCAR') os.chdir(cwd) task_poscar = os.path.join(task_path, 'POSCAR') # stress equi_outcar = os.path.join(equi_path, 'OUTCAR') stress = vasp.get_stress(equi_outcar) np.savetxt(os.path.join(task_path, 'equi.stress.out'), stress) # gen strcture ss = Structure.from_file(task_poscar) # gen defomations norm_strains = [-norm_def, -0.5*norm_def, 0.5*norm_def, norm_def] shear_strains = [-shear_def, -0.5*shear_def, 0.5*shear_def, shear_def] dfm_ss = DeformedStructureSet(ss, symmetry = False, norm_strains = norm_strains, shear_strains = shear_strains) n_dfm = len(dfm_ss) # gen incar if 'relax_incar' in jdata.keys(): relax_incar_path = jdata['relax_incar'] assert(os.path.exists(relax_incar_path)) relax_incar_path = os.path.abspath(relax_incar_path) fc = open(relax_incar_path).read() kspacing =float(re.findall((r"KSPACING(.+?)\n"),fc)[0].replace('=','')) kgamma =('T' in re.findall((r"KGAMMA(.+?)\n"),fc)[0]) else : fp_params = jdata['vasp_params'] ecut = fp_params['ecut'] ediff = fp_params['ediff'] npar = fp_params['npar'] kpar = fp_params['kpar'] kspacing = fp_params['kspacing'] kgamma = fp_params['kgamma'] fc = vasp.make_vasp_relax_incar(ecut, ediff, True, False, False, npar=npar,kpar=kpar, kspacing = kspacing, kgamma = kgamma) with open(os.path.join(task_path, 'INCAR'), 'w') as fp : fp.write(fc) # gen potcar with open(task_poscar,'r') as fp : lines = fp.read().split('\n') ele_list = lines[5].split() potcar_map = jdata['potcar_map'] potcar_list = [] for ii in ele_list : assert os.path.exists(os.path.abspath(potcar_map[ii])),"No POTCAR in the potcar_map of %s"%(ii) potcar_list.append(os.path.abspath(potcar_map[ii])) with open(os.path.join(task_path,'POTCAR'), 'w') as outfile: for fname in potcar_list: with open(fname) as infile: outfile.write(infile.read()) # gen kpoints fc = vasp.make_kspacing_kpoints(task_poscar, kspacing, kgamma) with open(os.path.join(task_path,'KPOINTS'), 'w') as fp: fp.write(fc) # gen tasks cwd = os.getcwd() for ii in range(n_dfm) : # make dir dfm_path = os.path.join(task_path, 'dfm-%03d' % ii) os.makedirs(dfm_path, exist_ok=True) os.chdir(dfm_path) for jj in ['POSCAR', 'POTCAR', 'INCAR', 'KPOINTS'] : if os.path.isfile(jj): os.remove(jj) # make conf dfm_ss.deformed_structures[ii].to('POSCAR', 'POSCAR') # record strain strain = Strain.from_deformation(dfm_ss.deformations[ii]) np.savetxt('strain.out', strain) # link incar, potcar, kpoints os.symlink(os.path.relpath(os.path.join(task_path, 'INCAR')), 'INCAR') os.symlink(os.path.relpath(os.path.join(task_path, 'POTCAR')), 'POTCAR') os.symlink(os.path.relpath(os.path.join(task_path, 'KPOINTS')), 'KPOINTS') cwd = os.getcwd()
def make_lammps(jdata, conf_dir,task_type) : fp_params = jdata['lammps_params'] model_dir = fp_params['model_dir'] type_map = fp_params['type_map'] model_dir = os.path.abspath(model_dir) model_name =fp_params['model_name'] if not model_name and task_type =='deepmd': models = glob.glob(os.path.join(model_dir, '*pb')) model_name = [os.path.basename(ii) for ii in models] assert len(model_name)>0,"No deepmd model in the model_dir" else: models = [os.path.join(model_dir,ii) for ii in model_name] model_param = {'model_name' : fp_params['model_name'], 'param_type': fp_params['model_param_type']} ntypes = len(type_map) norm_def = jdata['norm_deform'] shear_def = jdata['shear_deform'] conf_path = os.path.abspath(conf_dir) conf_poscar = os.path.join(conf_path, 'POSCAR') # get equi poscar equi_path = re.sub('confs', global_equi_name, conf_path) equi_path = os.path.join(equi_path, task_type) equi_dump = os.path.join(equi_path, 'dump.relax') task_path = re.sub('confs', global_task_name, conf_path) task_path = os.path.join(task_path, task_type) os.makedirs(task_path, exist_ok=True) task_poscar = os.path.join(task_path, 'POSCAR') lammps.poscar_from_last_dump(equi_dump, task_poscar, type_map) # get equi stress equi_log = os.path.join(equi_path, 'log.lammps') stress = lammps.get_stress(equi_log) np.savetxt(os.path.join(task_path, 'equi.stress.out'), stress) # gen strcture # ss = Structure.from_file(conf_poscar) # print(ss) # ss = ss.from_file(task_poscar) # print(ss) ss = Structure.from_file(task_poscar) # gen defomations norm_strains = [-norm_def, -0.5*norm_def, 0.5*norm_def, norm_def] shear_strains = [-shear_def, -0.5*shear_def, 0.5*shear_def, shear_def] print('gen with norm '+str(norm_strains)) print('gen with shear '+str(shear_strains)) dfm_ss = DeformedStructureSet(ss, symmetry = False, norm_strains = norm_strains, shear_strains = shear_strains) n_dfm = len(dfm_ss) # gen tasks cwd = os.getcwd() # make lammps.in if task_type=='deepmd': fc = lammps.make_lammps_elastic('conf.lmp', ntypes, lammps.inter_deepmd, model_name) elif task_type=='meam': fc = lammps.make_lammps_elastic('conf.lmp', ntypes, lammps.inter_meam, model_param) f_lammps_in = os.path.join(task_path, 'lammps.in') with open(f_lammps_in, 'w') as fp : fp.write(fc) cwd = os.getcwd() os.chdir(task_path) for ii in model_name : if os.path.exists(ii) : os.remove(ii) for (ii,jj) in zip(models, model_name) : os.symlink(os.path.relpath(ii), jj) share_models = [os.path.join(task_path,ii) for ii in model_name] for ii in range(n_dfm) : # make dir dfm_path = os.path.join(task_path, 'dfm-%03d' % ii) os.makedirs(dfm_path, exist_ok=True) os.chdir(dfm_path) for jj in ['conf.lmp', 'lammps.in'] + model_name : if os.path.isfile(jj): os.remove(jj) # make conf dfm_ss.deformed_structures[ii].to('POSCAR', 'POSCAR') lammps.cvt_lammps_conf('POSCAR', 'conf.lmp') ptypes = vasp.get_poscar_types('POSCAR') lammps.apply_type_map('conf.lmp', type_map, ptypes) # record strain strain = Strain.from_deformation(dfm_ss.deformations[ii]) np.savetxt('strain.out', strain) # link lammps.in os.symlink(os.path.relpath(f_lammps_in), 'lammps.in') # link models for (ii,jj) in zip(share_models, model_name) : os.symlink(os.path.relpath(ii), jj) cwd = os.getcwd()
def make_vasp(jdata, conf_dir, norm_def=2e-3, shear_def=5e-3): fp_params = jdata['vasp_params'] ecut = fp_params['ecut'] ediff = fp_params['ediff'] npar = fp_params['npar'] kpar = fp_params['kpar'] kspacing = fp_params['kspacing'] kgamma = fp_params['kgamma'] strain_start = jdata['strain_start'] strain_end = jdata['strain_end'] strain_step = jdata['strain_step'] strain_direct = jdata['strain_direct'] conf_path = os.path.abspath(conf_dir) conf_poscar = os.path.join(conf_path, 'POSCAR') # get equi poscar equi_path = re.sub('confs', global_equi_name, conf_path) equi_path = os.path.join(equi_path, 'vasp-k%.2f' % kspacing) equi_contcar = os.path.join(equi_path, 'CONTCAR') task_path = re.sub('confs', global_task_name, conf_path) task_path = os.path.join(task_path, 'vasp-k%.2f' % kspacing) os.makedirs(task_path, exist_ok=True) cwd = os.getcwd() os.chdir(task_path) if os.path.isfile('POSCAR'): os.remove('POSCAR') os.symlink(os.path.relpath(equi_contcar), 'POSCAR') os.chdir(cwd) task_poscar = os.path.join(task_path, 'POSCAR') # stress equi_outcar = os.path.join(equi_path, 'OUTCAR') stress = vasp.get_stress(equi_outcar) np.savetxt(os.path.join(task_path, 'equi.stress.out'), stress) # gen strcture ss = Structure.from_file(task_poscar) # gen defomations norm_strains = np.arange(strain_start, strain_end, strain_step) print('gen with norm ' + str(norm_strains)) deformations = [] for ii in norm_strains: strain = Strain.from_index_amount(strain_direct, ii) deformations.append(strain.get_deformation_matrix()) deformed_structures = [ defo.apply_to_structure(ss) for defo in deformations ] n_dfm = len(deformed_structures) # gen incar fc = vasp.make_vasp_relax_incar(ecut, ediff, True, False, False, npar=npar, kpar=kpar, kspacing=None, kgamma=None) with open(os.path.join(task_path, 'INCAR'), 'w') as fp: fp.write(fc) # gen potcar with open(task_poscar, 'r') as fp: lines = fp.read().split('\n') ele_list = lines[5].split() potcar_map = jdata['potcar_map'] potcar_list = [] for ii in ele_list: assert (os.path.exists(potcar_map[ii])) potcar_list.append(potcar_map[ii]) with open(os.path.join(task_path, 'POTCAR'), 'w') as outfile: for fname in potcar_list: with open(fname) as infile: outfile.write(infile.read()) # gen kpoints fc = vasp.make_kspacing_kpoints(task_poscar, kspacing, kgamma) with open(os.path.join(task_path, 'KPOINTS'), 'w') as fp: fp.write(fc) # gen tasks cwd = os.getcwd() for ii in range(n_dfm): # make dir dfm_path = os.path.join(task_path, 'dfm-%03d' % ii) os.makedirs(dfm_path, exist_ok=True) os.chdir(dfm_path) for jj in ['POSCAR', 'POTCAR', 'INCAR', 'KPOINTS']: if os.path.isfile(jj): os.remove(jj) # make conf deformed_structures[ii].to('POSCAR', 'POSCAR') # record strain strain = Strain.from_deformation(deformations[ii]) np.savetxt('strain.out', strain) # link incar, potcar, kpoints os.symlink(os.path.relpath(os.path.join(task_path, 'INCAR')), 'INCAR') os.symlink(os.path.relpath(os.path.join(task_path, 'POTCAR')), 'POTCAR') os.symlink(os.path.relpath(os.path.join(task_path, 'KPOINTS')), 'KPOINTS') cwd = os.getcwd()
def make_lammps(jdata, conf_dir, task_type): fp_params = jdata['lammps_params'] model_dir = fp_params['model_dir'] type_map = fp_params['type_map'] model_dir = os.path.abspath(model_dir) model_name = fp_params['model_name'] if not model_name: models = glob.glob(os.path.join(model_dir, '*pb')) model_name = [os.path.basename(ii) for ii in models] else: models = [os.path.join(model_dir, ii) for ii in model_name] model_param = { 'model_name': fp_params['model_name'], 'param_type': fp_params['model_param_type'] } ntypes = len(type_map) strain_start = jdata['strain_start'] strain_end = jdata['strain_end'] strain_step = jdata['strain_step'] strain_direct = jdata['strain_direct'] conf_path = os.path.abspath(conf_dir) conf_poscar = os.path.join(conf_path, 'POSCAR') # get equi poscar equi_path = re.sub('confs', global_equi_name, conf_path) equi_path = os.path.join(equi_path, task_type) equi_dump = os.path.join(equi_path, 'dump.relax') task_path = re.sub('confs', global_task_name, conf_path) task_path = os.path.join(task_path, task_type) os.makedirs(task_path, exist_ok=True) task_poscar = os.path.join(task_path, 'POSCAR') lammps.poscar_from_last_dump(equi_dump, task_poscar, type_map) # get equi stress equi_log = os.path.join(equi_path, 'log.lammps') stress = lammps.get_stress(equi_log) np.savetxt(os.path.join(task_path, 'equi.stress.out'), stress) # gen strcture ss = Structure.from_file(task_poscar) # gen defomations norm_strains = np.arange(strain_start, strain_end, strain_step) print('gen with norm ' + str(norm_strains)) deformations = [] for ii in norm_strains: strain = Strain.from_index_amount(strain_direct, ii) deformations.append(strain.get_deformation_matrix()) deformed_structures = [ defo.apply_to_structure(ss) for defo in deformations ] n_dfm = len(deformed_structures) # gen tasks cwd = os.getcwd() # make lammps.in if task_type == 'deepmd': fc = lammps.make_lammps_elastic('conf.lmp', ntypes, lammps.inter_deepmd, model_name) elif task_type == 'meam': fc = lammps.make_lammps_elastic('conf.lmp', ntypes, lammps.inter_meam, model_param) f_lammps_in = os.path.join(task_path, 'lammps.in') with open(f_lammps_in, 'w') as fp: fp.write(fc) cwd = os.getcwd() if task_type == 'deepmd': os.chdir(task_path) for ii in model_name: if os.path.exists(ii): os.remove(ii) for (ii, jj) in zip(models, model_name): os.symlink(os.path.relpath(ii), jj) share_models = glob.glob(os.path.join(task_path, '*pb')) else: share_models = models for ii in range(n_dfm): # make dir dfm_path = os.path.join(task_path, 'dfm-%03d' % ii) os.makedirs(dfm_path, exist_ok=True) os.chdir(dfm_path) for jj in ['conf.lmp', 'lammps.in'] + model_name: if os.path.isfile(jj): os.remove(jj) # make conf deformed_structures[ii].to('POSCAR', 'POSCAR') lammps.cvt_lammps_conf('POSCAR', 'conf.lmp') ptypes = vasp.get_poscar_types('POSCAR') lammps.apply_type_map('conf.lmp', type_map, ptypes) # record strain strain = Strain.from_deformation(deformations[ii]) np.savetxt('strain.out', strain) # link lammps.in os.symlink(os.path.relpath(f_lammps_in), 'lammps.in') # link models for (ii, jj) in zip(share_models, model_name): os.symlink(os.path.relpath(ii), jj) cwd = os.getcwd()
def make_confs(self, path_to_work, path_to_equi, refine=False): path_to_work = os.path.abspath(path_to_work) path_to_equi = os.path.abspath(path_to_equi) task_list = [] cwd = os.getcwd() norm_def = self.norm_deform shear_def = self.shear_deform norm_strains = [-norm_def, -0.5 * norm_def, 0.5 * norm_def, norm_def] shear_strains = [ -shear_def, -0.5 * shear_def, 0.5 * shear_def, shear_def ] print('gen with norm ' + str(norm_strains)) print('gen with shear ' + str(shear_strains)) equi_contcar = os.path.join(path_to_equi, 'CONTCAR') if not os.path.exists(equi_contcar): raise RuntimeError("please do relaxation first") ss = Structure.from_file(equi_contcar) dfm_ss = DeformedStructureSet(ss, symmetry=False, norm_strains=norm_strains, shear_strains=shear_strains) n_dfm = len(dfm_ss) os.chdir(path_to_work) if os.path.isfile('POSCAR'): os.remove('POSCAR') os.symlink(os.path.relpath(equi_contcar), 'POSCAR') # task_poscar = os.path.join(output, 'POSCAR') # stress equi_outcar = os.path.join(path_to_equi, 'OUTCAR') equi_log = os.path.join(path_to_equi, 'log.lammps') if os.path.exists(equi_outcar): stress = vasp.get_stress(equi_outcar) np.savetxt('equi.stress.out', stress) elif os.path.exists(equi_log): stress = lammps.get_stress(equi_log) np.savetxt('equi.stress.out', stress) os.chdir(cwd) if refine: task_list = make_refine(self.parameter['init_from_suffix'], self.parameter['output_suffix'], path_to_work, n_dfm) os.chdir(cwd) else: for ii in range(n_dfm): output_task = os.path.join(path_to_work, 'task.%06d' % ii) os.makedirs(output_task, exist_ok=True) os.chdir(output_task) for jj in [ 'INCAR', 'POTCAR', 'POSCAR', 'conf.lmp', 'in.lammps' ]: if os.path.exists(jj): os.remove(jj) task_list.append(output_task) dfm_ss.deformed_structures[ii].to('POSCAR', 'POSCAR') # record strain strain = Strain.from_deformation(dfm_ss.deformations[ii]) np.savetxt('strain.out', strain) os.chdir(cwd) return task_list
def make_deepmd_lammps(jdata, conf_dir) : deepmd_model_dir = jdata['deepmd_model_dir'] deepmd_type_map = jdata['deepmd_type_map'] ntypes = len(deepmd_type_map) deepmd_model_dir = os.path.abspath(deepmd_model_dir) deepmd_models = glob.glob(os.path.join(deepmd_model_dir, '*pb')) deepmd_models_name = [os.path.basename(ii) for ii in deepmd_models] norm_def = jdata['norm_deform'] shear_def = jdata['shear_deform'] conf_path = os.path.abspath(conf_dir) conf_poscar = os.path.join(conf_path, 'POSCAR') # get equi poscar equi_path = re.sub('confs', global_equi_name, conf_path) equi_path = os.path.join(equi_path, 'deepmd') equi_dump = os.path.join(equi_path, 'dump.relax') task_path = re.sub('confs', global_task_name, conf_path) task_path = os.path.join(task_path, 'deepmd') os.makedirs(task_path, exist_ok=True) task_poscar = os.path.join(task_path, 'POSCAR') lammps.poscar_from_last_dump(equi_dump, task_poscar, deepmd_type_map) # get equi stress equi_log = os.path.join(equi_path, 'log.lammps') stress = lammps.get_stress(equi_log) np.savetxt(os.path.join(task_path, 'equi.stress.out'), stress) # gen strcture # ss = Structure.from_file(conf_poscar) # print(ss) # ss = ss.from_file(task_poscar) # print(ss) ss = Structure.from_file(task_poscar) # gen defomations norm_strains = [-norm_def, -0.5*norm_def, 0.5*norm_def, norm_def] shear_strains = [-shear_def, -0.5*shear_def, 0.5*shear_def, shear_def] print('gen with norm '+str(norm_strains)) print('gen with shear '+str(shear_strains)) dfm_ss = DeformedStructureSet(ss, symmetry = False, norm_strains = norm_strains, shear_strains = shear_strains) n_dfm = len(dfm_ss) # gen tasks cwd = os.getcwd() # make lammps.in fc = lammps.make_lammps_elastic('conf.lmp', ntypes, lammps.inter_deepmd, deepmd_models_name) f_lammps_in = os.path.join(task_path, 'lammps.in') with open(f_lammps_in, 'w') as fp : fp.write(fc) cwd = os.getcwd() for ii in range(n_dfm) : # make dir dfm_path = os.path.join(task_path, 'dfm-%03d' % ii) os.makedirs(dfm_path, exist_ok=True) os.chdir(dfm_path) for jj in ['conf.lmp', 'lammps.in'] + deepmd_models_name : if os.path.isfile(jj): os.remove(jj) # make conf dfm_ss.deformed_structures[ii].to('POSCAR', 'POSCAR') lammps.cvt_lammps_conf('POSCAR', 'conf.lmp') ptypes = vasp.get_poscar_types('POSCAR') lammps.apply_type_map('conf.lmp', deepmd_type_map, ptypes) # record strain strain = Strain.from_deformation(dfm_ss.deformations[ii]) np.savetxt('strain.out', strain) # link lammps.in os.symlink(os.path.relpath(f_lammps_in), 'lammps.in') # link models for (ii,jj) in zip(deepmd_models, deepmd_models_name) : os.symlink(os.path.relpath(ii), jj) cwd = os.getcwd()
def make_confs(self, path_to_work, path_to_equi, refine=False): path_to_work = os.path.abspath(path_to_work) if os.path.exists(path_to_work): dlog.warning('%s already exists' % path_to_work) else: os.makedirs(path_to_work) path_to_equi = os.path.abspath(path_to_equi) if 'start_confs_path' in self.parameter and os.path.exists( self.parameter['start_confs_path']): init_path_list = glob.glob( os.path.join(self.parameter['start_confs_path'], '*')) struct_init_name_list = [] for ii in init_path_list: struct_init_name_list.append(ii.split('/')[-1]) struct_output_name = path_to_work.split('/')[-2] assert struct_output_name in struct_init_name_list path_to_equi = os.path.abspath( os.path.join(self.parameter['start_confs_path'], struct_output_name, 'relaxation', 'relax_task')) task_list = [] cwd = os.getcwd() equi_contcar = os.path.join(path_to_equi, 'CONTCAR') os.chdir(path_to_work) if os.path.isfile('POSCAR'): os.remove('POSCAR') if os.path.islink('POSCAR'): os.remove('POSCAR') os.symlink(os.path.relpath(equi_contcar), 'POSCAR') # task_poscar = os.path.join(output, 'POSCAR') # stress, deal with unsupported stress in dpdata #with open(os.path.join(path_to_equi, 'result.json')) as fin: # equi_result = json.load(fin) #equi_stress = np.array(equi_result['stress']['data'])[-1] equi_result = loadfn(os.path.join(path_to_equi, 'result.json')) equi_stress = equi_result['stress'][-1] dumpfn(equi_stress, 'equi.stress.json', indent=4) os.chdir(cwd) if refine: print('elastic refine starts') task_list = make_refine(self.parameter['init_from_suffix'], self.parameter['output_suffix'], path_to_work) # record strain # df = Strain.from_deformation(dfm_ss.deformations[idid]) # dumpfn(df.as_dict(), 'strain.json', indent=4) init_from_path = re.sub(self.parameter['output_suffix'][::-1], self.parameter['init_from_suffix'][::-1], path_to_work[::-1], count=1)[::-1] task_list_basename = list(map(os.path.basename, task_list)) for ii in task_list_basename: init_from_task = os.path.join(init_from_path, ii) output_task = os.path.join(path_to_work, ii) os.chdir(output_task) if os.path.isfile('strain.json'): os.remove('strain.json') copyfile(os.path.join(init_from_task, 'strain.json'), 'strain.json') #os.symlink(os.path.relpath( # os.path.join((re.sub(self.parameter['output_suffix'], self.parameter['init_from_suffix'], ii)), # 'strain.json')), # 'strain.json') os.chdir(cwd) else: norm_def = self.norm_deform shear_def = self.shear_deform norm_strains = [ -norm_def, -0.5 * norm_def, 0.5 * norm_def, norm_def ] shear_strains = [ -shear_def, -0.5 * shear_def, 0.5 * shear_def, shear_def ] if not os.path.exists(equi_contcar): raise RuntimeError("please do relaxation first") ss = Structure.from_file(equi_contcar) dfm_ss = DeformedStructureSet(ss, symmetry=False, norm_strains=norm_strains, shear_strains=shear_strains) n_dfm = len(dfm_ss) print('gen with norm ' + str(norm_strains)) print('gen with shear ' + str(shear_strains)) for ii in range(n_dfm): output_task = os.path.join(path_to_work, 'task.%06d' % ii) os.makedirs(output_task, exist_ok=True) os.chdir(output_task) for jj in [ 'INCAR', 'POTCAR', 'POSCAR', 'conf.lmp', 'in.lammps' ]: if os.path.exists(jj): os.remove(jj) task_list.append(output_task) dfm_ss.deformed_structures[ii].to('POSCAR', 'POSCAR') # record strain df = Strain.from_deformation(dfm_ss.deformations[ii]) dumpfn(df.as_dict(), 'strain.json', indent=4) os.chdir(cwd) return task_list
def get_wf_elastic_constant(structure, metadata, strain_states=None, stencils=None, db_file=None, conventional=False, order=2, vasp_input_set=None, analysis=True, sym_reduce=False, tag='elastic', copy_vasp_outputs=False, **kwargs): """ Returns a workflow to calculate elastic constants. Firework 1 : write vasp input set for structural relaxation, run vasp, pass run location, database insertion. Firework 2 - number of total deformations: Static runs on the deformed structures last Firework : Analyze Stress/Strain data and fit the elastic tensor Args: structure (Structure): input structure to be optimized and run. strain_states (list of Voigt-notation strains): list of ratios of nonzero elements of Voigt-notation strain, e. g. [(1, 0, 0, 0, 0, 0), (0, 1, 0, 0, 0, 0), etc.]. stencils (list of floats, or list of list of floats): values of strain to multiply by for each strain state, i. e. stencil for the perturbation along the strain state direction, e. g. [-0.01, -0.005, 0.005, 0.01]. If a list of lists, stencils must correspond to each strain state provided. db_file (str): path to file containing the database credentials. conventional (bool): flag to convert input structure to conventional structure, defaults to False. order (int): order of the tensor expansion to be determined. Defaults to 2 and currently supports up to 3. vasp_input_set (VaspInputSet): vasp input set to be used. Defaults to static set with ionic relaxation parameters set. Take care if replacing this, default ensures that ionic relaxation is done and that stress is calculated for each vasp run. analysis (bool): flag to indicate whether analysis task should be added and stresses and strains passed to that task sym_reduce (bool): Whether or not to apply symmetry reductions tag (str): copy_vasp_outputs (bool): whether or not to copy previous vasp outputs. kwargs (keyword arguments): additional kwargs to be passed to get_wf_deformations Returns: Workflow """ # Convert to conventional if specified if conventional: structure = SpacegroupAnalyzer( structure).get_conventional_standard_structure() uis_elastic = { "IBRION": 2, "NSW": 99, "ISIF": 2, "ISTART": 1, "PREC": "High" } vis = vasp_input_set or MPStaticSet(structure, user_incar_settings=uis_elastic) strains = [] if strain_states is None: strain_states = get_default_strain_states(order) if stencils is None: stencils = [np.linspace(-0.01, 0.01, 5 + (order - 2) * 2)] * len(strain_states) if np.array(stencils).ndim == 1: stencils = [stencils] * len(strain_states) for state, stencil in zip(strain_states, stencils): strains.extend( [Strain.from_voigt(s * np.array(state)) for s in stencil]) # Remove zero strains strains = [strain for strain in strains if not (abs(strain) < 1e-10).all()] # Adding the zero strains for the purpose of calculating at finite pressure or thermal expansion _strains = [Strain.from_deformation([[1, 0, 0], [0, 1, 0], [0, 0, 1]])] strains.extend(_strains) """ """ vstrains = [strain.voigt for strain in strains] if np.linalg.matrix_rank(vstrains) < 6: # TODO: check for sufficiency of input for nth order raise ValueError( "Strain list is insufficient to fit an elastic tensor") deformations = [s.get_deformation_matrix() for s in strains] """ print(strains) print(deformations) """ if sym_reduce: # Note this casts deformations to a TensorMapping # with unique deformations as keys to symmops deformations = symmetry_reduce(deformations, structure) wf_elastic = get_wf_deformations(structure, deformations, tag=tag, db_file=db_file, vasp_input_set=vis, copy_vasp_outputs=copy_vasp_outputs, **kwargs) if analysis: defo_fws_and_tasks = get_fws_and_tasks( wf_elastic, fw_name_constraint="deformation", task_name_constraint="Transmuted") for idx_fw, idx_t in defo_fws_and_tasks: defo = \ wf_elastic.fws[idx_fw].tasks[idx_t]['transformation_params'][0][ 'deformation'] pass_dict = { 'strain': Deformation(defo).green_lagrange_strain.tolist(), 'stress': '>>output.ionic_steps.-1.stress', 'deformation_matrix': defo } if sym_reduce: pass_dict.update({'symmops': deformations[defo]}) mod_spec_key = "deformation_tasks->{}".format(idx_fw) pass_task = pass_vasp_result(pass_dict=pass_dict, mod_spec_key=mod_spec_key) wf_elastic.fws[idx_fw].tasks.append(pass_task) fw_analysis = Firework(ElasticTensorToDb(structure=structure, db_file=db_file, order=order, fw_spec_field='tags', metadata=metadata, vasp_input_set=vis), name="Analyze Elastic Data", spec={"_allow_fizzled_parents": True}) wf_elastic.append_wf(Workflow.from_Firework(fw_analysis), wf_elastic.leaf_fw_ids) wf_elastic.name = "{}:{}".format(structure.composition.reduced_formula, "elastic constants") return wf_elastic
def make_vasp(jdata, conf_dir): default_norm_def = 2e-3 default_shear_def = 5e-3 norm_def = jdata.get('norm_deform', default_norm_def) shear_def = jdata.get('shear_deform', default_shear_def) conf_path = os.path.abspath(conf_dir) conf_poscar = os.path.join(conf_path, 'POSCAR') if 'relax_incar' in jdata.keys(): vasp_str = 'vasp-relax_incar' else: kspacing = jdata['vasp_params']['kspacing'] vasp_str = 'vasp-k%.2f' % kspacing # get equi poscar equi_path = re.sub('confs', global_equi_name, conf_path) equi_path = os.path.join(equi_path, vasp_str) equi_contcar = os.path.join(equi_path, 'CONTCAR') task_path = re.sub('confs', global_task_name, conf_path) task_path = os.path.join(task_path, vasp_str) os.makedirs(task_path, exist_ok=True) cwd = os.getcwd() os.chdir(task_path) if os.path.isfile('POSCAR'): os.remove('POSCAR') os.symlink(os.path.relpath(equi_contcar), 'POSCAR') os.chdir(cwd) task_poscar = os.path.join(task_path, 'POSCAR') # stress equi_outcar = os.path.join(equi_path, 'OUTCAR') stress = vasp.get_stress(equi_outcar) np.savetxt(os.path.join(task_path, 'equi.stress.out'), stress) # gen strcture ss = Structure.from_file(task_poscar) # gen defomations norm_strains = [-norm_def, -0.5 * norm_def, 0.5 * norm_def, norm_def] shear_strains = [-shear_def, -0.5 * shear_def, 0.5 * shear_def, shear_def] dfm_ss = DeformedStructureSet(ss, symmetry=False, norm_strains=norm_strains, shear_strains=shear_strains) n_dfm = len(dfm_ss) # gen incar if 'relax_incar' in jdata.keys(): relax_incar_path = jdata['relax_incar'] assert (os.path.exists(relax_incar_path)) relax_incar_path = os.path.abspath(relax_incar_path) incar = incar_upper(Incar.from_file(relax_incar_path)) if incar.get('ISIF') != 2: dlog.info("%s:%s setting ISIF to 2" % (__file__, make_vasp.__name__)) incar['ISIF'] = 2 fc = incar.get_string() kspacing = incar['KSPACING'] kgamma = incar['KGAMMA'] else: fp_params = jdata['vasp_params'] ecut = fp_params['ecut'] ediff = fp_params['ediff'] npar = fp_params['npar'] kpar = fp_params['kpar'] kspacing = fp_params['kspacing'] kgamma = fp_params['kgamma'] fc = vasp.make_vasp_relax_incar(ecut, ediff, True, False, False, npar=npar, kpar=kpar, kspacing=kspacing, kgamma=kgamma) with open(os.path.join(task_path, 'INCAR'), 'w') as fp: fp.write(fc) # gen potcar with open(task_poscar, 'r') as fp: lines = fp.read().split('\n') ele_list = lines[5].split() potcar_map = jdata['potcar_map'] potcar_list = [] for ii in ele_list: assert os.path.exists(os.path.abspath( potcar_map[ii])), "No POTCAR in the potcar_map of %s" % (ii) potcar_list.append(os.path.abspath(potcar_map[ii])) with open(os.path.join(task_path, 'POTCAR'), 'w') as outfile: for fname in potcar_list: with open(fname) as infile: outfile.write(infile.read()) # gen kpoints fc = vasp.make_kspacing_kpoints(task_poscar, kspacing, kgamma) with open(os.path.join(task_path, 'KPOINTS'), 'w') as fp: fp.write(fc) # gen tasks cwd = os.getcwd() for ii in range(n_dfm): # make dir dfm_path = os.path.join(task_path, 'dfm-%03d' % ii) os.makedirs(dfm_path, exist_ok=True) os.chdir(dfm_path) for jj in ['POSCAR', 'POTCAR', 'INCAR', 'KPOINTS']: if os.path.isfile(jj): os.remove(jj) # make conf dfm_ss.deformed_structures[ii].to('POSCAR', 'POSCAR') # record strain strain = Strain.from_deformation(dfm_ss.deformations[ii]) np.savetxt('strain.out', strain) # link incar, potcar, kpoints os.symlink(os.path.relpath(os.path.join(task_path, 'INCAR')), 'INCAR') os.symlink(os.path.relpath(os.path.join(task_path, 'POTCAR')), 'POTCAR') os.symlink(os.path.relpath(os.path.join(task_path, 'KPOINTS')), 'KPOINTS') #copy cvasp if ('cvasp' in jdata) and (jdata['cvasp'] == True): shutil.copyfile(cvasp_file, os.path.join(dfm_path, 'cvasp.py')) os.chdir(cwd)