def setUp(self): filename = os.path.join(data_dir, "..", "POSCAR_NaCl") force_sets_filename = os.path.join(data_dir, "..", "FORCE_SETS_NaCl") born_filename = os.path.join(data_dir, "..", "BORN_NaCl") self.ph = phonopy.load(unitcell_filename=filename, supercell_matrix=[2, 2, 2], calculator='vasp', force_sets_filename=force_sets_filename, is_compact_fc=False) self.ph_nac = phonopy.load(unitcell_filename=filename, supercell_matrix=[2, 2, 2], calculator='vasp', force_sets_filename=force_sets_filename, born_filename=born_filename, is_compact_fc=False)
def __init__(self, phonopy_disp, force_sets, pa='auto', symprec=1e-4, escale='meV'): self.cell = phonopy.load(phonopy_disp, primitive_matrix=pa) # can we get the primitive matrix here? self.phonon = phonopy.Phonopy( self.cell.unitcell, self.cell.supercell_matrix, primitive_matrix=self.cell.primitive_matrix, symprec=symprec) self.phonon.dataset = phonopy.file_IO.parse_FORCE_SETS( filename=force_sets) self.phonon.produce_force_constants() if escale == 'meV': self.scale = THzToEv * 1000 elif escale == 'THz': self.scale = 1 self.path = None self.labels = None self.are_bands_computed = False self.are_neutron_bands_computed = False self.nions = len(self.phonon.primitive.symbols)
def dump_phonopy(pk): n = load_node(pk) unitcell = n.inputs.structure.get_ase() smat = n.outputs.phonon_setting_info['supercell_matrix'] ph = phonopy.load(unitcell=unitcell, supercell_matrix=smat, primitive_matrix='auto') force_sets = n.outputs.force_sets.get_array('force_sets') dataset = n.outputs.phonon_setting_info['displacement_dataset'] ph.dataset = dataset ph.forces = force_sets if 'nac_params' in n.outputs: borns = n.outputs.nac_params.get_array('born_charges') epsilon = n.outputs.nac_params.get_array('epsilon') nac_params = {'born': borns, 'factor': 14.399652, 'dielectric': epsilon} ph.nac_params = nac_params settings = {'force_sets': True, 'displacements': True, 'force_constants': False, 'born_effective_charge': True, 'dielectric_constant': True} # phonopy-params.yaml is written out. ph.save(settings=settings) print("phonopy_params.yaml was made for PK=%d" % pk)
def plot_phonon(kpath, path='./', yaml_fname='phonopy_params.yaml', color='blue', unit="cm^-1"): phonon = load(phonopy_yaml=os.path.join(path, )) cell = phonon._primitive.cell kpts, xs, xs_special, names = kpath(cell, npoints=300, path=kpath) phonon.symmetrize_force_constants() #phonon.symmetrize_force_constants_by_space_group() phonon.set_qpoints_phonon(kpts, is_eigenvectors=True) #phonon.symmetrize_force_constants() freqs, eigvecs = phonon.get_qpoints_phonon() #print(freqs) #print(eigvecs.shape) #print(eigvecs[9,-1,:]) #weight=np.zeros_like(freqs) #for ki in range(freqs.shape[0]): # for i in range(freqs.shape[1]): # weight[ki,i]=np.linalg.norm(eigvecs[ki,i,-3:]) for i in range(freqs.shape[1]): plt.plot(xs, freqs[:, i] * 33.356, color=color, linewidth=1.3, alpha=0.8) #plt.plot(xs, freqs[:, i]*33.356/8.065,color=color,linewidth=1.3,alpha=0.8) #plt.scatter(x, freqs[:, i]*33.356,s=weight[:,i]*10,color='blue',alpha=0.3) plt.xlim(xs[0], xs[-1]) for x in xs_special: plt.axvline(x, color='gray', alpha=0.7) plt.xticks(xs_special, names) plt.ylabel('Frequency (cm$^{-1}$)') plt.show()
def run_phonon(): phonon = phonopy.load(supercell_matrix=[2, 2, 2], primitive_matrix='auto', unitcell_filename="POSCAR_unitcell", force_constants_filename="FORCE_CONSTANTS") phonon.set_mesh([20, 20, 20]) path = [[0, 0, 0], [2 / 3, 1 / 3, 0]] labels = ['$\\Gamma$', 'K'] qpoints, connections = get_band_qpoints_and_path_connections(path, npoints=51) phonon.run_band_structure(qpoints, path_connections=connections, labels=labels, with_eigenvectors=True) phonon.set_total_DOS() phonon.set_thermal_properties() pp = { 'band': phonon.get_band_structure_dict(), 'freq_eigvecs': phonon.get_frequencies_with_eigenvectors(path[0]), 'dos': phonon.get_total_dos_dict(), 'therm': phonon.get_thermal_properties_dict() } with open('pp.pkl', 'wb') as f: pickle.dump(pp, f)
def ph_tipn3() -> Phonopy: """Return Phonopy class instance of anataze TiPN3 4x2x1.""" yaml_filename = os.path.join(current_dir, "phonopy_params_TiPN3.yaml.xz") return phonopy.load(yaml_filename, is_compact_fc=False, log_level=1, produce_fc=True)
def cmpt_vasp(jdata, conf_dir, opt): 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'] supercell_matrix = jdata['supercell_matrix'] conf_path = os.path.abspath(conf_dir) task_path = re.sub('confs', global_task_name, conf_path) task_path = os.path.join(task_path, 'vasp-k%.2f' % kspacing) cwd = os.getcwd() os.chdir(task_path) if os.path.isfile('vasprun.xml'): os.system('phonopy --fc vasprun.xml') os.system( 'phonopy --dim="%d %d %d" -c POSCAR-unitcell band.conf' % (supercell_matrix[0], supercell_matrix[1], supercell_matrix[2])) else: print('vasprun.xml No such file') if opt == 'Y': ph = phonopy.load(supercell_matrix=supercell_matrix, primitive_matrix='auto', unitcell_filename="POSCAR-unitcell", force_constants_filename='FORCE_CONSTANTS') ph.auto_band_structure(plot=True).show()
def ph_zr3n4() -> Phonopy: """Return Phonopy class instance of anataze Zr3N4 1x1x1.""" yaml_filename = os.path.join(current_dir, "phonopy_params_Zr3N4.yaml") return phonopy.load(yaml_filename, is_compact_fc=False, log_level=1, produce_fc=True)
def cmpt_deepmd_lammps(jdata, conf_dir, opt): 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')) supercell_matrix = jdata['supercell_matrix'] conf_path = os.path.abspath(conf_dir) task_path = re.sub('confs', global_task_name, conf_path) task_path = os.path.join(task_path, 'deepmd') os.chdir(task_path) if os.path.isfile('FORCE_CONSTANTS'): os.system( 'phonopy --dim="%d %d %d" -c POSCAR-unitcell band.conf' % (supercell_matrix[0], supercell_matrix[1], supercell_matrix[2])) else: print('FORCE_CONSTANTS No such file') if opt == 'Y': ph = phonopy.load(supercell_matrix=supercell_matrix, primitive_matrix='auto', unitcell_filename="POSCAR-unitcell", force_constants_filename='FORCE_CONSTANTS') ph.auto_band_structure(plot=True).show()
def save_ifc_and_show_phonon( fname='phonopy_params.yaml', ifc_fname='ifc.nc', kmesh=[3, 3, 3], assure_ASR=True, knames=['$\\Gamma$', 'M', 'A', 'Z', 'R', 'M', '$\\Gamma$', 'Z'], kvectors=np.array([[0., 0., 0.], [0.5, 0.5, 0.], [0.5, 0.5, 0.5], [0., 0., 0.5], [0.5, 0.0, 0.5], [0.5, 0.5, 0], [0, 0, 0], [0.0, 0.0, 0.5]]), ): phonon = load(phonopy_yaml=fname) phon = PhonopyWrapper(phonon, mode='ifc') ax = phon.plot_band(color='blue', kvectors=kvectors, knames=knames) phon.save_ifc(fname=ifc_fname, kmesh=kmesh, eval_modify_function=None, assure_ASR=assure_ASR) Rpts, HR = phon.get_ifc(kmesh=kmesh, eval_modify_function=None, assure_ASR=assure_ASR) ifc = IFC(phon.atoms, Rpts, HR) ifc.plot_band(ax=ax, color='red', kvectors=kvectors, knames=knames) plt.ylabel("FC (eV/$\AA^2$) ") plt.show()
def generate_modulations(self): '''Generate the modulations.''' print('Generating modulated structures...') phonon = phonopy.load(self.phonopy_yaml) Na = 3 print('WARNING Na is hard coded') # [q-point, band index (int), amplitude (float), phase (float)] qpt = [0., 0., 0.] # Note: fix qpt A_list = np.asarray(self.amplitude_list) * np.sqrt(Na) phonon_modes = [[qpt, self.nmode - 1, A, 0.0] for A in A_list] dim = [1, 1, 1] phonon.set_modulations(dim, phonon_modes) phonon.write_yaml_modulations() phonon.write_modulations() # Go into MPOSCAR and correct header and mode to relevant directories... os.system('mkdir {}'.format(self.dirname)) os.system('mkdir {}/structures'.format(self.dirname)) os.system('sed -i "s/ 1.0/ 0.529177/g" MPOSCAR*') os.system('mv modulation.yaml {}/structures'.format(self.dirname)) for i in range(self.num_of_modulations): os.system('mv MPOSCAR-{:03d} {}/structures/POSCAR-{:03d}'.format( i + 1, self.dirname, i + 1)) os.system('mv MPOSCAR* {}/structures'.format(self.dirname))
def get_random_displacements(structure, number_of_snapshots, temperature, **data): displacements = [] forces = [] energies = [] for i in range(len(data) // 2): forces.append(data['forces_%d' % (i + 1)].get_array('force_sets')) if 'energies' in data['forces_%d' % (i + 1)].get_arraynames(): energies.append(data['forces_%d' % (i + 1)].get_array('energies')) phonon_setting_info = data['ph_info_%d' % (i + 1)] dataset = phonon_setting_info['displacement_dataset'] disps, _ = get_displacements_and_forces(dataset) displacements.append(disps) d = np.concatenate(displacements, axis=0) f = np.concatenate(forces, axis=0) idx = None if len(energies) == len(forces) and 'include_ratio' in data: all_energies = np.concatenate(energies) if len(all_energies) == len(f): ratio = data['include_ratio'].value if 0 < ratio and ratio < 1: num_include = int(np.ceil(ratio * len(all_energies))) if num_include > len(all_energies): num_include = len(all_energies) idx = np.argsort(all_energies)[:num_include] d = d[idx] f = f[idx] phonon_setting_info = data['ph_info_1'] smat = phonon_setting_info['supercell_matrix'] ph = phonopy.load(unitcell=phonopy_atoms_from_structure(structure), supercell_matrix=smat, primitive_matrix='auto') ph.dataset = {'displacements': d, 'forces': f} ph.produce_force_constants(fc_calculator='alm') _modify_force_constants(ph) if 'random_seed' in data: _random_seed = data['random_seed'].value else: _random_seed = None ph.generate_displacements(number_of_snapshots=number_of_snapshots.value, random_seed=_random_seed, temperature=temperature.value) ret_dict = {'displacement_dataset': Dict(dict=ph.dataset)} if idx is not None: array = DataFactory('array')() array.set_array('supercell_energies', all_energies) array.set_array('included_supercell_indices', idx) ret_dict['supercell_energies'] = array return ret_dict
def ph_nacl_gruneisen() -> Tuple[Phonopy, Phonopy, Phonopy]: """Return Phonopy class instances of NaCl 2x2x2 at three volumes.""" ph0 = phonopy.load( os.path.join(current_dir, "phonopy_params_NaCl-1.00.yaml.xz"), log_level=1, produce_fc=True, ) ph_minus = phonopy.load( os.path.join(current_dir, "phonopy_params_NaCl-0.995.yaml.xz"), log_level=1, produce_fc=True, ) ph_plus = phonopy.load( os.path.join(current_dir, "phonopy_params_NaCl-1.005.yaml.xz"), log_level=1, produce_fc=True, ) return ph0, ph_minus, ph_plus
def _get_phonon(self): phonon = phonopy.load( [[2, 0, 0], [0, 2, 0], [0, 0, 2]], primitive_matrix=[[0, 0.5, 0.5], [0.5, 0, 0.5], [0.5, 0.5, 0]], unitcell_filename=os.path.join(data_dir, "..", "POSCAR_NaCl"), force_sets_filename=os.path.join(data_dir, "..", "FORCE_SETS_NaCl"), born_filename=os.path.join(data_dir, "..", "BORN_NaCl")) return phonon
def ph_nacl_nonac(): yaml_filename = os.path.join(current_dir, "phonopy_disp_NaCl.yaml") force_sets_filename = os.path.join(current_dir, "FORCE_SETS_NaCl") return phonopy.load(yaml_filename, force_sets_filename=force_sets_filename, is_nac=False, is_compact_fc=False, log_level=1, produce_fc=True)
def ph_si() -> Phonopy: """Return Phonopy class instance of Si-prim 2x2x2.""" yaml_filename = os.path.join(current_dir, "phonopy_params_Si.yaml") return phonopy.load( yaml_filename, is_compact_fc=False, log_level=1, produce_fc=True, )
def si_pbesol_iterha_111(): """Return Phono3py instance of Si 1x1x1. * with symmetry * no fc """ yaml_filename = os.path.join(current_dir, "phonopy_params-Si111-iterha.yaml.gz") return phonopy.load(yaml_filename, log_level=1, produce_fc=False)
def _build_phonopy_object_vasp(self): cwd = os.getcwd() os.chdir(os.path.dirname(self.mainfile)) try: phonopy_obj = phonopy.load(self.mainfile) finally: os.chdir(cwd) self._phonopy_obj = phonopy_obj
def get_phonon_from_phonopy_params(phonopy_yaml: str) -> Phonopy: """ Get phonon from phonopy_params.yaml. Args: phonopy_yaml: Phonopy phonopy_params.yaml file. """ phonon = phonopy.load(phonopy_yaml=phonopy_yaml) return phonon
def ph_tio2(): yaml_filename = os.path.join(current_dir, "phonopy_disp_TiO2.yaml") force_sets_filename = os.path.join(current_dir, "FORCE_SETS_TiO2") born_filename = os.path.join(current_dir, "BORN_TiO2") return phonopy.load(yaml_filename, force_sets_filename=force_sets_filename, born_filename=born_filename, is_compact_fc=False, log_level=1, produce_fc=True)
def ph_nacl_nofcsym(): yaml_filename = os.path.join(current_dir, "phonopy_disp_NaCl.yaml") force_sets_filename = os.path.join(current_dir, "FORCE_SETS_NaCl") born_filename = os.path.join(current_dir, "BORN_NaCl") return phonopy.load(yaml_filename, force_sets_filename=force_sets_filename, born_filename=born_filename, symmetrize_fc=False, log_level=1, produce_fc=True)
def _get_phonon(self): phonon = phonopy.load( supercell_matrix=[[2, 0, 0], [0, 2, 0], [0, 0, 2]], primitive_matrix=[[0, 0.5, 0.5], [0.5, 0, 0.5], [0.5, 0.5, 0]], unitcell_filename=os.path.join(data_dir, "..", "POSCAR_NaCl"), force_sets_filename=os.path.join(data_dir, "..", "FORCE_SETS_NaCl"), born_filename=os.path.join(data_dir, "..", "BORN_NaCl")) return phonon
def _get_phonon(self): filename_cell = os.path.join(data_dir, "..", "POSCAR_NaCl") filename_forces = os.path.join(data_dir, "..", "FORCE_SETS_NaCl") filename_born = os.path.join(data_dir, "..", "BORN_NaCl") phonon = load(supercell_matrix=[2, 2, 2], primitive_matrix=[[0, 0.5, 0.5], [0.5, 0, 0.5], [0.5, 0.5, 0]], unitcell_filename=filename_cell, force_sets_filename=filename_forces, born_filename=filename_born) phonon.symmetrize_force_constants() return phonon
def ph_nacl_nonac_compact_fc() -> Phonopy: """Return Phonopy class instance of NaCl 2x2x2 without NAC with compact fc2.""" yaml_filename = os.path.join(current_dir, "phonopy_disp_NaCl.yaml") force_sets_filename = os.path.join(current_dir, "FORCE_SETS_NaCl") return phonopy.load( yaml_filename, force_sets_filename=force_sets_filename, is_nac=False, is_compact_fc=True, log_level=1, produce_fc=True, )
def postprocess(): # os.system('phonolammps in.graphene --dim 2 2 2 -c POSCAR_unitcell') phonon = phonopy.load(supercell_matrix=[2, 2, 2], primitive_matrix='auto', unitcell_filename="POSCAR_unitcell", force_constants_filename="FORCE_CONSTANTS") from phonopy.phonon.band_structure import get_band_qpoints_and_path_connections phonon.set_mesh([20, 20, 20]) path = [[0, 0, 0], [0.5, 0.5, 0]] labels = ["$\\Gamma$", "K"] qpoints, connections = get_band_qpoints_and_path_connections(path, npoints=51) phonon.run_band_structure(qpoints, path_connections=connections, labels=labels) phonon.plot_band_structure() # .savefig('band.png') print(dir(phonon)) def myband(): d = phonon.get_band_structure_dict() q = d['qpoints'] freq = d['frequencies'] fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(6, 3)) print(len(q)) x = q[-1] y = freq[-1] print(x) print(y) print('*' * 50) for i in range(y.shape[1]): ax.plot(x, y[:, i], color='blue') plt.savefig('myband.png') os.system('rsub myband.png') myband() # phonon.auto_band_structure(plot=True).savefig('band.png') # print(phonon.get_mesh_dict()) # phonon.set_total_DOS() # phonon.plot_total_DOS().show() phonon.set_thermal_properties() tp_dict = phonon.get_thermal_properties_dict() with open('tp.pkl', 'wb') as f: pickle.dump(tp_dict, f) phonon.plot_thermal_properties().savefig('therm_cmd.png')
def run_task(self, fw_spec): create_FORCE_CONSTANTS("vasprun.xml", False, 1) (Keylist, Coordslist, prims, transmat) = get_highsympath("POSCAR-unitcell") phonon = phonopy.load(supercell_matrix=self.get("supercell"), primitive_matrix=transmat, unitcell_filename="POSCAR-unitcell", calculator="vasp", is_nac=False, force_constants_filename="FORCE_CONSTANTS") points = get_band_qpoints([np.array(Coordslist)], 51) phonon.run_band_structure(points, with_group_velocities=True) phonon.write_yaml_band_structure()
def ph_tio2() -> Phonopy: """Return Phonopy class instance of anataze TiO2 3x3x1.""" yaml_filename = os.path.join(current_dir, "phonopy_disp_TiO2.yaml") force_sets_filename = os.path.join(current_dir, "FORCE_SETS_TiO2") born_filename = os.path.join(current_dir, "BORN_TiO2") return phonopy.load( yaml_filename, force_sets_filename=force_sets_filename, born_filename=born_filename, is_compact_fc=False, log_level=1, produce_fc=True, )
def ph_nacl_nofcsym() -> Phonopy: """Return Phonopy class instance of NaCl 2x2x2 without symmetrizing fc2.""" yaml_filename = os.path.join(current_dir, "phonopy_disp_NaCl.yaml") force_sets_filename = os.path.join(current_dir, "FORCE_SETS_NaCl") born_filename = os.path.join(current_dir, "BORN_NaCl") return phonopy.load( yaml_filename, force_sets_filename=force_sets_filename, born_filename=born_filename, symmetrize_fc=False, log_level=1, produce_fc=True, )
def __init__(self, phonon=None, *argv, **kwargs): """ Parameters: ======================================== folder: folder of siesta calculation fdf_file: siesta input filename """ try: import phonopy except ImportError: raise ImportError("phonopy is needed. Do you have phonopy installed?") if phonon is None: phonon=phonopy.load(*argv, **kwargs) self.model = PhonopyWrapper(phonon)
def main(scf_name, fc_name, grid): primcell_filename = scf_name q2r_filename = fc_name cell, _ = read_pwscf(primcell_filename) q2r = PH_Q2R(q2r_filename) q2r.run(cell) q2r.write_force_constants() phonon = phonopy.load(supercell_matrix=grid, calculator='qe', unitcell=cell, force_constants_filename="force_constants.hdf5") phonon.save(settings={'force_constants': True}) freq, evec = phonon.get_frequencies_with_eigenvectors([0., 0., 0.])
def run_phonopy(self, params, data): print( '\n\tWARNING: This doesnt work right with PHONOPY yet. The structure factors are bad.\n' ) import phonopy from phonopy.phonon.band_structure import get_band_qpoints_and_path_connections phonon = phonopy.load(unitcell_filename=params.poscar, supercell_matrix=params.supercell, primitive_matrix=params.primitive_matrix, force_sets_filename=params.force_sets_filename) phonon.run_band_structure([list(params.qpoints)], with_eigenvectors=True) self.phonopy_output = phonon.get_band_structure_dict() data.num_Qpoints = params.num_Qpoints data.num_bands = params.num_atoms * 3 data.qpoints = {} data.Qpoints = {} data.cart_Qpoints = {} data.frequencies = {} data.eigenvectors = {} data.cart_eigenvectors = {} for i in range(data.num_Qpoints): data.frequencies[f'{i}'] = self.phonopy_output['frequencies'][0][ i] * constants.thz2mev data.eigenvectors[f'{i}'] = self.phonopy_output['eigenvectors'][0][ i] data.cart_eigenvectors[f'{i}'] = np.copy(data.eigenvectors[f'{i}']) data.qpoints[f'{i}'] = self.phonopy_output['qpoints'][0][i] for b in range(data.num_bands): for j in range(params.num_atoms): data.cart_eigenvectors[f'{i}'][ b, j] = data.cart_eigenvectors[f'{i}'][b, j] / np.sqrt( params.masses[f'{j}']) data.cart_eigenvectors[f'{i}'][ b, j] = data.cart_eigenvectors[f'{i}'][b, j] * np.exp( 1j * np.dot(data.qpoints[f'{i}'], params.cart_positions[j, :])) data.Qpoints[f'{i}'] = params.Qpoints[i, :] data.cart_Qpoints[f'{i}'] = np.matmul( params.reciprocal_lattice_vectors, data.Qpoints[f'{i}'])
import phonopy from phonopy.phonon.band_structure import get_band_qpoints phonon = phonopy.load([[2, 0, 0], [0, 2, 0], [0, 0, 2]], primitive_matrix=[[0, 0.5, 0.5], [0.5, 0, 0.5], [0.5, 0.5, 0]], unitcell_filename="POSCAR", force_sets_filename="FORCE_SETS", born_filename="BORN") points = get_band_qpoints( [[[0.5, 0, 0.5], [0, 0, 0], [0.5, 0.5, 0.5], [0.5, 0.25, 0.75]]], 51) phonon.set_band_structure(points) phonon.plot_band_structure(labels=['X', '$\Gamma$', 'L', 'W']).show()