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 get_band_structure(self, band_paths: list, labels: list = None, npoints: int = 51, with_eigenvectors: bool = False, use_reciprocal_lattice: bool = True): """ Get BandStructure class object. Args: band_paths (list): Band paths. labels (list): Band labels. npoints (int): The number of sampling points. with_eigenvectors (bool): If True, calculte eigenvectors. """ if use_reciprocal_lattice: rec_lattice = self._reciprocal_lattice else: rec_lattice = None qpoints, connections = get_band_qpoints_and_path_connections( band_paths=band_paths, npoints=npoints, rec_lattice=rec_lattice) band_structure = BandStructure( paths=qpoints, dynamical_matrix=self._phonon.get_dynamical_matrix(), with_eigenvectors=with_eigenvectors, is_band_connection=False, group_velocity=None, path_connections=connections, labels=labels, is_legacy_plot=False) return band_structure
def get_phonon_band(structure, supercell_matrix, force_constants, band_paths=None, npoints=51, labels=None, save_data=False, save_fig=False): ''' Return the phonon bandstructure Parameters ---------- structure : pymatgen.Structure Unitcell (not supercell) of interest. supercell_matrix : numpy.ndarray 3x3 matrix of the supercell deformation, e.g. [[3, 0, 0], [0, 3, 0], [0, 0, 3]]. force_constants: list force constants band_paths : list, multi dimention Sets of end points of paths, e.g. [[[0, 0, 0], [0.5, 0.5, 0], [0.5, 0.5, 0.5]], [[0.5, 0.25, 0.75], [0, 0, 0]]] If it equals None, it will determine the path automatically by phononpy npoints: int Number of q-points in each path including end points. labels: list of str The label of high symmetry points, if None, it will determine it automatically by phononpy save_data/save_fig: bool Determine if save the data/figure or not ''' volume = structure.volume formula = structure.composition.reduced_formula filename = "{}-phonon-Vol{:.2f}".format(formula, volume) unitcell = get_phonopy_structure(structure) ph_band_obj = Phonopy(unitcell, supercell_matrix) ph_band_obj.set_force_constants(force_constants) if band_paths: qpoints, connections = get_band_qpoints_and_path_connections( band_paths, npoints=npoints) ph_band_obj.run_band_structure(qpoints, path_connections=connections, labels=labels) else: ph_band_obj.auto_band_structure() if save_fig: fig_band = ph_band_obj.plot_band_structure() fig_band.savefig(fname='{}-band.png'.format(filename)) fig_band.close() if save_data: ph_band_obj.write_yaml_band_structure( filename='{}-band.yaml'.format(filename)) return ph_band_obj
def _get_bandstructure_calc(self, structure, phonon, npoints_band=51): #TODO: add option to save yaml file with eigenvalues in future versions tempfilename = tempfile.gettempprefix() + '.yaml' kpath_dict, kpath_concrete = get_kpath(structure) qpoints, connections = get_band_qpoints_and_path_connections( kpath_concrete, npoints=npoints_band) phonon.run_band_structure(qpoints, path_connections=connections) phonon.write_yaml_band_structure(filename=tempfilename) bs_symm_line = get_ph_bs_symm_line(tempfilename, labels_dict=kpath_dict["kpoints"]) os.remove(tempfilename) return bs_symm_line
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 prepare_phonon_eigs(self,nqpoints=10): print("Need to calculate the mode resolved anharmonic scores, first get the phonon eigenvectors") from core.models.element import atomic_mass_dict from pymatgen.symmetry.bandstructure import HighSymmKpath from core.internal.builders.crystal import map_to_pymatgen_Structure pmg_path = HighSymmKpath(map_to_pymatgen_Structure(self.ref_frame), symprec=1e-3) self._kpath = pmg_path._kpath self.prim = pmg_path.prim self.conv = pmg_path.conventional __qpoints = [[self._kpath['kpoints'][self._kpath['path'][j][i]] for i in range(len(self._kpath['path'][j]))] for j in range(len(self._kpath['path']))] from phonopy.phonon.band_structure import get_band_qpoints_and_path_connections qpoints, connections = get_band_qpoints_and_path_connections(__qpoints, npoints=nqpoints) # now this qpoints will contain points within two high-symmetry points along the Q-path self.phonon.run_band_structure(qpoints, with_eigenvectors=True) _eigvecs = self.phonon.band_structure.__dict__['_eigenvectors'] _eigvals = self.phonon.band_structure.__dict__['_eigenvalues'] self.eigvecs = [] self.eigvals = [] import math self.atomic_masses = [] for a in self.ref_frame.all_atoms(sort=False, unique=False): for _ in range(3): self.atomic_masses.append(1.0 / math.sqrt(atomic_mass_dict[a.label.upper()])) from phonopy.units import VaspToTHz if _eigvecs is not None: for i, eigvecs_on_path in enumerate(_eigvecs): for j, eigvecs_at_q in enumerate(eigvecs_on_path): for k, vec in enumerate(eigvecs_at_q.T): #vec = np.array(vec).reshape(self.ref_frame.total_num_atoms(), 3) self.eigvecs.append(self.atomic_masses*vec) eigv=_eigvals[i][j][k] self.eigvals.append(np.sqrt(abs(eigv))*np.sign(eigv)*VaspToTHz) print('eigenvector shape ', np.shape(vec)) print('Total number of eigenstates ' + str(len(self.eigvals)))
def compute_bands(self, numpoints=101): if self.path is None: assert False, "Band structure path not set, aborting" qpoints, connections = get_band_qpoints_and_path_connections( self.path, npoints=numpoints) self.phonon.run_band_structure(qpoints, path_connections=connections, labels=self.labels) bs = self.phonon.get_band_structure_dict() self.high_symmetry_points = [] for segment in bs['distances']: self.high_symmetry_points.append(min(segment)) self.high_symmetry_points.append(max(segment)) self.segments = bs['distances'] self.q = np.hstack(bs['distances']) self.en = np.vstack(bs['frequencies']) * self.scale self.num_bands = self.en.shape[1] self.are_bands_computed = True
def get_phonon(self, phonon, **kwargs): flag_savefig = kwargs.get('savefig', False) flag_savedata = kwargs.get('savedata', False) flag_band = kwargs.get('band', False) flag_dos = kwargs.get('phonon_dos', False) flag_pdos = kwargs.get('phonon_pdos', False) mesh = kwargs.get('mesh', [50, 50, 50]) labels = kwargs.get('labels', None) if 'unitcell' not in phonon: raise FileNotFoundError( 'There is no phonon result. Please run phonon first.') self.head = ['Temperature', 'F_vib', 'CV_vib', 'S_vib'] self.unit = ['K', 'eV', 'eV/K', 'eV/K'] self.data = np.vstack((phonon.pop('temperatures'), phonon.pop('F_vib'), phonon.pop('CV_vib'), phonon.pop('S_vib'))).T filename = '{}-phonon-Vol{:.2f}'.format(self.formula, self.volume) unitcell = get_phonopy_structure(self.structure) supercell_matrix = phonon['supercell_matrix'] force_constants = phonon['force_constants'] ph = Phonopy(unitcell, supercell_matrix) ph.set_force_constants(force_constants) #for band structure if flag_band: if 'path' in kwargs: qpoints, connections = get_band_qpoints_and_path_connections( path, npoints=51) ph.run_band_structure(qpoints, path_connections=connections, labels=labels) else: ph.auto_band_structure() if flag_savefig: fig_band = ph.plot_band_structure() fig_band.savefig(fname='{}-band.png'.format(filename)) fig_band.close() if flag_savedata: ph.write_yaml_band_structure( filename='{}-band.yaml'.format(filename)) #for dos if flag_dos: ph.run_mesh(mesh) ph.run_total_dos() #phonon_dos_tmp = np.vstack((ph._total_dos._frequency_points, ph._total_dos._dos)) #print(phonon_dos_tmp) #print(type(phonon_dos_tmp)) if flag_savefig: fig_dos = ph.plot_total_dos() fig_dos.savefig(fname='{}-dos.png'.format(filename)) fig_dos.close() if flag_savedata: ph.write_total_dos(filename='{}-dos.dat'.format(filename)) #for pdos. if flag_pdos: ph.run_mesh(mesh, with_eigenvectors=True, is_mesh_symmetry=False) ph.run_projected_dos() if flag_savefig: ph.plot_projected_dos().savefig( fname='{}-pdos.png'.format(filename)) if flag_savedata: ph.write_projected_dos(filename='{}-pdos.dat'.format(filename)) phonon.pop('_id') self.parameter = phonon
def MVibrationauto(self, maxx=4500): import os import numpy as np from pymatgen.io.phonopy import get_phonopy_structure import pymatgen as pmg from pymatgen.io.vasp.outputs import Vasprun from pymatgen.io.vasp import Poscar from pymatgen.symmetry.kpath import KPathSeek, KPathBase from phonopy.phonon.band_structure import get_band_qpoints_and_path_connections from phonopy import Phonopy from phonopy.structure.atoms import Atoms as PhonopyAtoms from pymatgen.phonon.plotter import PhononBSPlotter from pymatgen.phonon.bandstructure import PhononBandStructureSymmLine import csv import pandas as pd import matplotlib.pyplot as plt os.chdir(self.dire) print(os.getcwd()) poscar = Poscar.from_file("POSCAR") structure = poscar.structure scell = [[2, 0, 0], [0, 2, 0], [0, 0, 2]] vrun = Vasprun("vasprun.xml") phonopyAtoms = get_phonopy_structure(structure) phonon = Phonopy(phonopyAtoms, scell) phonon.set_force_constants(-vrun.force_constants) # labels = ["$\\Gamma$", "X", "U", "K", "L"] labels = ['K', "$\\Gamma$", 'L', 'W', 'X'] # bands = [] cd = KPathSeek(structure) cds = cd.kpath # print(cds) for k, v in cds.items(): if "kpoints" in k: dics = v else: dicss = v print(dics) print(dicss) # bands=[] # for k,v in dics.items(): # if k in dicss[0]: # bands.append(v) path = [] # # bandd1=[] # for k,v in dics.items(): # for i in dicss[0]: # if k in i: # bandd1.append(v) # path.append(bandd1) bandd1 = [] for i in dicss[1]: for k, v in dics.items(): if k in i: bandd1.append(v) path.append(bandd1) print(dicss[1]) qpoints, connections = get_band_qpoints_and_path_connections( path, npoints=51) phonon.run_band_structure(qpoints, path_connections=connections, labels=labels) print(path) # kpoints=cd.get_kpoints # print(kpoints) # phonon.set_band_structure(bands,labels=labels) phonon.plot_band_structure().show() phonon.plot_band_structure().savefig("BAND.png", bbox_inches='tight', transparent=True, dpi=300, format='png') # phonon.write_band_structure() mesh = [31, 31, 31] phonon.set_mesh(mesh) phonon.set_total_DOS() phonon.write_total_DOS() phonon.plot_total_DOS().show() phonon.plot_total_DOS().savefig("DOS.png") # c = np.fromfile('total_dos.dat', dtype=float) datContent = [ i.strip().split() for i in open("./total_dos.dat").readlines() ] del datContent[0] x_ax = [] y_ax = [] for i in datContent: x_ax.append(1 / ((3 * (10**8) / (float(i[0]) * (10**12))) * 100)) y_ax.append(float(i[1])) da = {'Density of states': x_ax, 'Frequency': y_ax} df = pd.DataFrame(da) #构造原始数据文件 df.to_excel("Wave number.xlsx") #生成Excel文件,并存到指定文件路径下 fig, ax = plt.subplots() line1 = ax.plot(x_ax, y_ax, c='grey') ax.set_xlim([maxx, 0]) # 以下是XRD图片的格式设置 #设置横纵坐标的名称以及对应字体格式 font2 = { 'family': 'Times New Roman', 'weight': 'bold', } plt.xlabel('Wavenumber ($\mathregular{cm^-}$$\mathregular{^1}$)', font2) plt.ylabel('Density of states', font2) #不显示Y轴的刻度 plt.yticks([]) #设置图例对应格式和字体 font1 = { 'family': 'Times New Roman', 'weight': 'bold', } # ax.legend(edgecolor='none', prop=font1) # plt.legend(edgecolor='none', prop=font1) # plt.set_facecolor('none') ax.set_facecolor('none') #存储为 fig.savefig('FTIR.png', bbox_inches='tight', transparent=True, dpi=300, format='png') #指定分辨率,边界紧,背景透明 plt.show()
def main(): parser = argparse.ArgumentParser(description='', ) parser.add_argument( 'INPUT', nargs='?', default='phonons.sym-{i}.pckl', help= 'pattern for the force files (.npy or .pckl of arrays in eV/A^2), which must be a python format string that uses "{i}"' ) parser.add_argument( '--eq', metavar='EQFILE', help='subtract equilibrium forces from EQFILE (same formats as INPUT)') parser.add_argument( '-1', dest='start_index', default=0, action='store_const', const=1, help='indicate that file indices start from 1 instead of 0') parser.add_argument('--phonopy', required=True, help='phonopy.yaml or phonopy_disp.yaml') parser.add_argument( '--fc-symmetry', action='store_true', help='make force constants symmetric and apply acoustic sum rule') parser.add_argument( '-o', '--output', help= 'output npy file. Each row will be a column eigenvector. (this is the transpose of the eigenvector matrix)' ) parser.add_argument('--write-ase-forces', metavar='PREFIX', help='output force files as $PREFIX.0x+.pckl and etc.') parser.add_argument('--write-force-constants', help='output npy file for force constants') parser.add_argument('--write-frequencies', help='output npy file for frequencies') args = parser.parse_args() effectful_args = [ 'output', 'write_force_constants', 'write_frequencies', 'write_ase_forces' ] if not any(getattr(args, a) for a in effectful_args): parser.error('Nothing to do! Please supply one of: ' + ', '.join('--' + a.replace('_', '-') for a in effectful_args)) phonon = phonopy.load(args.phonopy, produce_fc=False) ndisp = len(phonon.displacements) indices = range(args.start_index, args.start_index + ndisp) force_sets = np.array( [load_array(args.INPUT.format(i=i)) for i in indices]) if args.eq: force_sets -= load_array(args.eq) phonon.set_forces(force_sets) phonon.produce_force_constants() if args.fc_symmetry: phonon.symmetrize_force_constants() if args.write_force_constants: np.save(args.write_force_constants, phonon.get_force_constants()) if args.write_ase_forces: write_ase_forces(args.write_ase_forces, phonon) if not (args.output or args.write_frequencies): return from phonopy.phonon.band_structure import get_band_qpoints_and_path_connections path = [[[0, 0, 0], [0, 0, 0]]] labels = ["$\\Gamma$", "$\\Gamma$"] qpoints, connections = get_band_qpoints_and_path_connections(path, npoints=2) phonon.run_band_structure(qpoints, path_connections=connections, labels=labels, with_eigenvectors=True) frequencies = phonon.band_structure.frequencies[0][0] * THZ_TO_WAVENUMBER print(frequencies) if args.output: np.save(args.output, phonon.band_structure.eigenvectors[0][0].T) if args.write_frequencies: np.save(args.write_frequencies, frequencies)
labels.append(t) print(pm) print(sc) ph = phonopy.load(supercell_matrix=sc, primitive_matrix=pm, unitcell_filename=args.in_fn, is_nac=args.nac, calculator=args.calc, factor=args.factor, force_sets_filename=args.fsetfn) print(ph.primitive) qpoints, connections = get_band_qpoints_and_path_connections( [path], npoints=args.npoints) ph.run_band_structure(qpoints, with_eigenvectors=True, is_band_connection=True, path_connections=connections, labels=labels) band_dict = ph.get_band_structure_dict() dist = band_dict[ 'distances'] # dist is an array of segments array. Corresponds to x-axis freq = band_dict['frequencies'] kpt = qpoints eigs = band_dict['eigenvectors'] # Plotting routine params = {
at.arrays["force"] = forces at.info["virial"] = -1.0 * at.get_volume() * stress at.info["energy"] = energy write("./Ti_{}_{}_scell2.xyz".format(config_type, disp), at) #write("{}_scell.xyz".format(i), at) set_of_forces.append(forces) return set_of_forces cell = get_crystal(config_type) print config_type phonon = phonopy_pre_process(cell, disp, config_type, supercell_matrix=np.eye(3, dtype='intc')) set_of_forces = run(calc, phonon, config_type, disp) phonon.produce_force_constants(forces=set_of_forces) path = [[[0, 0, 0], [-0.5, 0.5, 0.5], [0.25, 0.25, 0.25], [0, 0, 0], [0, 0.5, 0]]] labels = ["$\\Gamma$", "H", "P", "$\\Gamma$", "N"] qpoints, connections = get_band_qpoints_and_path_connections(path, npoints=51) phonon.run_band_structure(qpoints, path_connections=connections, labels=labels) phonon.write_yaml_band_structure(filename="{}_{}_{}.yaml".format( os.path.splitext(model_name)[0], config_type, disp))