Esempio n. 1
0
def phonons(model, bulk, supercell, dx, mesh=None, points=None, n_points=50):

    import model

    unitcell = PhonopyAtoms(symbols=bulk.get_chemical_symbols(),
                            cell=bulk.get_cell(),
                            scaled_positions=bulk.get_scaled_positions())
    phonon = Phonopy(unitcell, supercell)
    phonon.generate_displacements(distance=dx)

    sets_of_forces = []

    for s in phonon.get_supercells_with_displacements():
        at = Atoms(cell=s.get_cell(),
                   symbols=s.get_chemical_symbols(),
                   scaled_positions=s.get_scaled_positions(),
                   pbc=3 * [True])
        at.set_calculator(model.calculator)
        sets_of_forces.append(at.get_forces())

    phonon.set_forces(sets_of_forces=sets_of_forces)
    phonon.produce_force_constants()

    properties = {}

    if mesh is not None:
        phonon.set_mesh(mesh, is_gamma_center=True)
        qpoints, weights, frequencies, eigvecs = phonon.get_mesh()

        properties["frequencies"] = frequencies.tolist()
        properties["weights"] = weights.tolist()

    if points is not None:
        bands = []
        for i in range(len(points) - 1):
            band = []
            for r in np.linspace(0, 1, n_points):
                band.append(points[i] + (points[i + 1] - points[i]) * r)
            bands.append(band)

        phonon.set_band_structure(bands,
                                  is_eigenvectors=True,
                                  is_band_connection=False)
        band_q_points, band_distances, band_frequencies, band_eigvecs = phonon.get_band_structure(
        )

        band_distance_max = np.max(band_distances)
        band_distances = [(_b / band_distance_max).tolist()
                          for _b in band_distances]

        band_frequencies = [_b.tolist() for _b in band_frequencies]

        properties["band_q_points"] = band_q_points
        properties["band_distances"] = band_distances
        properties["band_frequencies"] = band_frequencies
        properties["band_eigvecs"] = band_eigvecs

    properties["phonopy"] = phonon

    return properties
Esempio n. 2
0
import phonopy.interface.vasp as vasp
import numpy as np
import lxml.etree as etree
from phonopy import Phonopy
from phonopy.structure.atoms import Atoms as PhonopyAtoms


vasprun = etree.iterparse('vasprun.xml', tag='varray')
fc = vasp.get_force_constants_vasprun_xml(vasprun)

primitive = vasp.get_atoms_from_poscar(open('POSCAR-p'),'W')
superc =  vasp.get_atoms_from_poscar(open('POSCAR'),'W')

print superc.get_scaled_positions()

a = 5.404
bulk = PhonopyAtoms(symbols=['W'] * 216,
                    positions=superc.get_scaled_positions())
bulk.set_cell(np.diag((a, a, a)))
phonon = Phonopy(bulk,[[1,0,0],[0,1,0],[0,0,1]],primitive_matrix=[[-0.5, 0.5, 0.5],[0.5, -0.5, 0.5],[0.5, 0.5, -0.5]])

phonon.set_force_constants(fc)

mesh = [3, 3, 3]
phonon.set_mesh(mesh)
qpoints, weights, frequencies, eigvecs = phonon.get_mesh()


phonon.set_total_DOS()
phonon.plot_total_DOS().show()
Esempio n. 3
0
class PhonopyJob(AtomisticParallelMaster):
    """

    Args:
        project:
        job_name:
    """
    def __init__(self, project, job_name):
        super(PhonopyJob, self).__init__(project, job_name)
        self.__name__ = "PhonopyJob"
        self.__version__ = "0.0.1"
        self.input["interaction_range"] = (10.0,
                                           "Minimal size of supercell, Ang")
        self.input["factor"] = (
            VaspToTHz,
            "Frequency unit conversion factor (default for VASP)",
        )
        self.input["displacement"] = (0.01, "atoms displacement, Ang")
        self.input["dos_mesh"] = (20, "mesh size for DOS calculation")

        self.phonopy = None
        self._job_generator = PhonopyJobGenerator(self)
        self._disable_phonopy_pickle = False
        s.publication_add(phonopy_publication())

    @property
    def phonopy_pickling_disabled(self):
        return self._disable_phonopy_pickle

    @phonopy_pickling_disabled.setter
    def phonopy_pickling_disabled(self, disable):
        self._disable_phonopy_pickle = disable

    @property
    def _phonopy_unit_cell(self):
        if self.structure is not None:
            return atoms_to_phonopy(self.structure)
        else:
            return None

    def _enable_phonopy(self):
        if self.phonopy is None:
            if self.structure is not None:
                self.phonopy = Phonopy(
                    unitcell=self._phonopy_unit_cell,
                    supercell_matrix=self._phonopy_supercell_matrix(),
                    factor=self.input["factor"],
                )
                self.phonopy.generate_displacements(
                    distance=self.input["displacement"])
                self.to_hdf()
            else:
                raise ValueError(
                    "No reference job/ No reference structure found.")

    def list_structures(self):
        if self.structure is not None:
            self._enable_phonopy()
            return [struct for _, struct in self._job_generator.parameter_list]
        else:
            return []

    def _phonopy_supercell_matrix(self):
        if self.structure is not None:
            supercell_range = np.ceil(
                self.input["interaction_range"] / np.array([
                    np.linalg.norm(vec)
                    for vec in self._phonopy_unit_cell.get_cell()
                ]))
            return np.eye(3) * supercell_range
        else:
            return np.eye(3)

    def run_static(self):
        # Initialise the phonopy object before starting the first calculation.
        self._enable_phonopy()
        super(PhonopyJob, self).run_static()

    def run_if_interactive(self):
        self._enable_phonopy()
        super(PhonopyJob, self).run_if_interactive()

    def to_hdf(self, hdf=None, group_name=None):
        """
        Store the PhonopyJob in an HDF5 file

        Args:
            hdf (ProjectHDFio): HDF5 group object - optional
            group_name (str): HDF5 subgroup name - optional
        """
        super(PhonopyJob, self).to_hdf(hdf=hdf, group_name=group_name)
        if self.phonopy is not None and not self._disable_phonopy_pickle:
            with self.project_hdf5.open("output") as hdf5_output:
                hdf5_output["phonopy_pickeled"] = codecs.encode(
                    pickle.dumps(self.phonopy), "base64").decode()

    def from_hdf(self, hdf=None, group_name=None):
        """
        Restore the PhonopyJob from an HDF5 file

        Args:
            hdf (ProjectHDFio): HDF5 group object - optional
            group_name (str): HDF5 subgroup name - optional
        """
        super(PhonopyJob, self).from_hdf(hdf=hdf, group_name=group_name)
        with self.project_hdf5.open("output") as hdf5_output:
            if "phonopy_pickeled" in hdf5_output.list_nodes():
                self.phonopy = pickle.loads(
                    codecs.decode(hdf5_output["phonopy_pickeled"].encode(),
                                  "base64"))
                if "dos_total" in hdf5_output.list_nodes():
                    self._dos_total = hdf5_output["dos_total"]
                if "dos_energies" in hdf5_output.list_nodes():
                    self._dos_energies = hdf5_output["dos_energies"]

    def collect_output(self):
        """

        Returns:

        """
        if self.server.run_mode.interactive:
            forces_lst = self.project_hdf5.inspect(
                self.child_ids[0])["output/generic/forces"]
        else:
            forces_lst = [
                self.project_hdf5.inspect(job_id)["output/generic/forces"][-1]
                for job_id in self._get_jobs_sorted()
            ]
        self.phonopy.set_forces(forces_lst)
        self.phonopy.produce_force_constants()
        self.phonopy.set_mesh(mesh=[self.input["dos_mesh"]] * 3)
        qpoints, weights, frequencies, eigvecs = self.phonopy.get_mesh()
        self.phonopy.set_total_DOS()
        erg, dos = self.phonopy.get_total_DOS()

        self.to_hdf()

        with self.project_hdf5.open("output") as hdf5_out:
            hdf5_out["dos_total"] = dos
            hdf5_out["dos_energies"] = erg
            hdf5_out["qpoints"] = qpoints
            hdf5_out["supercell_matrix"] = self._phonopy_supercell_matrix()
            hdf5_out[
                "displacement_dataset"] = self.phonopy.get_displacement_dataset(
                )
            hdf5_out[
                "dynamical_matrix"] = self.phonopy.dynamical_matrix.get_dynamical_matrix(
                )
            hdf5_out["force_constants"] = self.phonopy.force_constants

    def write_phonopy_force_constants(self,
                                      file_name="FORCE_CONSTANTS",
                                      cwd=None):
        """

        Args:
            file_name:
            cwd:

        Returns:

        """
        if cwd is not None:
            file_name = posixpath.join(cwd, file_name)
        write_FORCE_CONSTANTS(force_constants=self.phonopy.force_constants,
                              filename=file_name)

    def get_hesse_matrix(self):
        """

        Returns:

        """
        unit_conversion = (
            scipy.constants.physical_constants["Hartree energy in eV"][0] /
            scipy.constants.physical_constants["Bohr radius"][0]**2 *
            scipy.constants.angstrom**2)
        force_shape = np.shape(self.phonopy.force_constants)
        force_reshape = force_shape[0] * force_shape[2]
        return (np.transpose(self.phonopy.force_constants,
                             (0, 2, 1, 3)).reshape(
                                 (force_reshape, force_reshape)) /
                unit_conversion)

    def get_thermal_properties(self,
                               t_min=1,
                               t_max=1500,
                               t_step=50,
                               temperatures=None):
        """

        Args:
            t_min:
            t_max:
            t_step:
            temperatures:

        Returns:

        """
        self.phonopy.set_thermal_properties(t_step=t_step,
                                            t_max=t_max,
                                            t_min=t_min,
                                            temperatures=temperatures)
        return thermal(*self.phonopy.get_thermal_properties())

    @property
    def dos_total(self):
        """

        Returns:

        """
        return self["output/dos_total"]

    @property
    def dos_energies(self):
        """

        Returns:

        """
        return self["output/dos_energies"]

    @property
    def dynamical_matrix(self):
        """

        Returns:

        """
        return np.real_if_close(
            self.phonopy.get_dynamical_matrix().get_dynamical_matrix())

    def dynamical_matrix_at_q(self, q):
        """

        Args:
            q:

        Returns:

        """
        return np.real_if_close(self.phonopy.get_dynamical_matrix_at_q(q))

    def plot_dos(self, ax=None, *args, **qwargs):
        """

        Args:
            *args:
            ax:
            **qwargs:

        Returns:

        """
        try:
            import pylab as plt
        except ImportError:
            import matplotlib.pyplot as plt
        if ax is None:
            fig, ax = plt.subplots(1, 1)
        ax.plot(self["output/dos_energies"], self["output/dos_total"], *args,
                **qwargs)
        ax.set_xlabel("Frequency [THz]")
        ax.set_ylabel("DOS")
        ax.set_title("Phonon DOS vs Energy")
        return ax
Esempio n. 4
0
    #We need to get the forces on these atoms...
    forces = []
    print 'There are', len(supercells), 'displacement patterns'
    for sc in supercells:
        cell = aseAtoms(symbols=sc.get_chemical_symbols(), scaled_positions=sc.get_scaled_positions(),
                        cell=sc.get_cell(), pbc=(1,1,1))
        cell = Atoms(cell)
        cell.set_calculator(pot)
        forces.append(cell.get_forces())

    phonon.set_forces(forces)
    phonon.produce_force_constants()

    mesh = [nqx, nqy, nqz]
    phonon.set_mesh(mesh, is_eigenvectors=True)
    qpoints, weights, frequencies, eigvecs = phonon.get_mesh()

    #SHOW DOS STRUCTURE
    phonon.set_total_DOS(freq_min=0.0, freq_max=12.0, tetrahedron_method=False)
    phonon.get_total_DOS()
    phonon.write_total_DOS()
    phonon.plot_total_DOS().show()

    #BAND STRUCTURE
    phonon.set_band_structure(paths, is_eigenvectors=False, is_band_connection=True)
    phonon.get_band_structure()
    ph_plot = phonon.plot_band_structure(labels=["G", "N", "P"])
    ph_plot.show()
    #WRITE ANIMATION MODE
    phonon.write_animation()
    #TEMPERATURE
Esempio n. 5
0
 def __init__(self, numbatom=125, supercell=5):
     
     #species = 'WRe_0.25_conv'
     species = 'WRe_0.00'
     #species = 'Re'
     ###read force constants from vasprun.xml###
     vasprun = etree.iterparse('vasprun.xml', tag='varray')
     #fc = vasp.get_force_constants_vasprun_xml(vasprun,1) #pass xml input and species atomic weight.
     ###########################################
     
     ########### read positionsl ###############
     primitive = vasp.get_atoms_from_poscar(open('POSCAR-p'),'W')
     superc =  vasp.get_atoms_from_poscar(open('POSCAR'),'W')
     ###########################################
     numbatom =  superc.get_number_of_atoms()
     #print primitive.get_cell()
     #print primitive.get_scaled_positions()
     #print superc.get_scaled_positions()
     
     print numbatom, species, os.getcwd()
     if species=='W':
     #Tungsten
         fc = vasp.get_force_constants_vasprun_xml(vasprun,1,0,64)
         s = 4.
         a = superc.get_cell()[0][0]*2.
         print a
         bulk = PhonopyAtoms(symbols=['W'] * 1,
                             scaled_positions= primitive.get_scaled_positions())
         bulk.set_cell(np.diag((a, a, a)))
         phonon = Phonopy(bulk,
                          [[s,0.,0.],[0.,s,0.],[0.,0.,s]],
                          primitive_matrix=[[-0.5, 0.5, 0.5],[0.5, -0.5, 0.5],[0.5, 0.5, -0.5]],
                          distance=0.01, factor=15.633302)
         print fc
         phonon.set_force_constants(fc[0])
         phonon.set_dynamical_matrix()
         #print phonon.get_dynamical_matrix_at_q([0,0,0])
         mesh = [100, 100, 100]
         phonon.set_mesh(mesh)
         qpoints, weights, frequencies, eigvecs = phonon.get_mesh()
         print frequencies
         phonon.set_total_DOS()
         
         phonon.set_thermal_properties(t_step=10,
                                       t_max=3700,
                                       t_min=0)
         
     elif species=='W_conv_2x2x2':
     #Tungsten
         fc = vasp.get_force_constants_vasprun_xml(vasprun,1,2)
         s = 2.
         a = superc.get_cell()[0][0]*2.
         print a
         bulk = PhonopyAtoms(symbols=['W','W'] * 1,
                             scaled_positions= primitive.get_scaled_positions())
         bulk.set_cell(np.diag((a, a, a)))
         phonon = Phonopy(bulk,
                          [[s,0.,0.],[0.,s,0.],[0.,0.,s]],
                          primitive_matrix=[[-0.5, 0.5, 0.5],[0.5, -0.5, 0.5],[0.5, 0.5, -0.5]],
                          distance=0.01, factor=15.633302)
         print fc
         phonon.set_force_constants(fc[0])
         phonon.set_dynamical_matrix()
         #print phonon.get_dynamical_matrix_at_q([0,0,0])
         mesh = [100, 100, 100]
         phonon.set_mesh(mesh)
         qpoints, weights, frequencies, eigvecs = phonon.get_mesh()
         print frequencies
         phonon.set_total_DOS()
         
         phonon.set_thermal_properties(t_step=10,
                                       t_max=3700,
                                       t_min=0)
     
     elif species=='W_conv':
     #Tungsten
         fc = vasp.get_force_constants_vasprun_xml(vasprun,1,2)
         s = 4.
         a = superc.get_cell()[0][0]*2.
         print a
         bulk = PhonopyAtoms(symbols=['W','W'] * 1,
                             scaled_positions= primitive.get_scaled_positions())
         bulk.set_cell(np.diag((a, a, a)))
         phonon = Phonopy(bulk,
                          [[s,0.,0.],[0.,s,0.],[0.,0.,s]],
                          primitive_matrix=[[-0.5, 0.5, 0.5],[0.5, -0.5, 0.5],[0.5, 0.5, -0.5]],
                          distance=0.01, factor=15.633302)
         print fc
         phonon.set_force_constants(fc[0])
         phonon.set_dynamical_matrix()
         #print phonon.get_dynamical_matrix_at_q([0,0,0])
         mesh = [100, 100, 100]
         phonon.set_mesh(mesh)
         qpoints, weights, frequencies, eigvecs = phonon.get_mesh()
         print frequencies
         phonon.set_total_DOS()
         
         phonon.set_thermal_properties(t_step=10,
                                       t_max=3700,
                                       t_min=0)
     
     elif species=='WRe_0.25_conv':
     #Tungsten
         fc = vasp.get_force_constants_vasprun_xml(vasprun,8,2,64)
         s = 4.
         a = superc.get_cell()[0][0]*2.
         print a, primitive.get_scaled_positions()
         bulk = PhonopyAtoms(symbols=['W','W'] * 1,
                             scaled_positions= primitive.get_scaled_positions())
         bulk.set_cell(np.diag((a, a, a)))
         phonon = Phonopy(bulk,
                          [[s,0.,0.],[0.,s,0.],[0.,0.,s]],
                          primitive_matrix=[[-0.5, 0.5, 0.5],[0.5, -0.5, 0.5],[0.5, 0.5, -0.5]],
                          distance=0.01, factor=15.633302)
         print fc
         phonon.set_force_constants(fc[0])
         phonon.set_dynamical_matrix()
         #print phonon.get_dynamical_matrix_at_q([0,0,0])
         mesh = [100, 100, 100]
         phonon.set_mesh(mesh)
         qpoints, weights, frequencies, eigvecs = phonon.get_mesh()
         #print frequencies
         phonon.set_total_DOS()
         
         phonon.set_thermal_properties(t_step=10,
                                       t_max=3700,
                                       t_min=0)
     
     elif species == 'WRe_B2': 
         fc = vasp.get_force_constants_vasprun_xml(vasprun,1,1)
         s = 5.
         a = superc.get_cell()[0][0]*2.
         print a
         bulk = PhonopyAtoms(symbols=['W','Re'] * 1,
                             scaled_positions= primitive.get_scaled_positions())
         bulk.set_cell(np.diag((a, a, a)))
         phonon = Phonopy(bulk,
                          [[s,0.,0.],[0.,s,0.],[0.,0.,s]],
                          primitive_matrix=[[-0.5, 0.5, 0.5],[0.5, -0.5, 0.5],[0.5, 0.5, -0.5]],
                          distance=0.01, factor=15.633302)
         print fc
         phonon.set_force_constants(fc[0])
         phonon.set_dynamical_matrix()
         #print phonon.get_dynamical_matrix_at_q([0,0,0])
         mesh = [100, 100, 100]
         phonon.set_mesh(mesh)
         qpoints, weights, frequencies, eigvecs = phonon.get_mesh()
         print frequencies
         phonon.set_total_DOS()
         
         phonon.set_thermal_properties(t_step=10,
                                       t_max=3700,
                                       t_min=0)
     elif species == 'WRe_0.00': 
         fc = vasp.get_force_constants_vasprun_xml(vasprun,1,0,numbatom)
         s = supercell
         a = superc.get_cell()[0][0]*2.
         print a
         bulk = PhonopyAtoms(symbols=['W'] * 1,
                             scaled_positions= primitive.get_scaled_positions())
         bulk.set_cell(np.diag((a, a, a)))
         phonon = Phonopy(bulk,
                          [[s,0.,0.],[0.,s,0.],[0.,0.,s]],
                          primitive_matrix=[[-0.5, 0.5, 0.5],[0.5, -0.5, 0.5],[0.5, 0.5, -0.5]],
                          distance=0.01, factor=15.633302)
         print fc
         phonon.set_force_constants(fc[0])
         phonon.set_dynamical_matrix()
         #print phonon.get_dynamical_matrix_at_q([0,0,0])
         mesh = [200, 200, 200]
         phonon.set_mesh(mesh)
         qpoints, weights, frequencies, eigvecs = phonon.get_mesh()
         print frequencies
         phonon.set_total_DOS()
         
         phonon.set_thermal_properties(t_step=10,
                                       t_max=3700,
                                       t_min=0)
     elif species == 'WRe_0.03': 
         fc = vasp.get_force_constants_vasprun_xml(vasprun,2,0)
         s = 2.
         a = superc.get_cell()[0][0]*2.
         print a
         bulk = PhonopyAtoms(symbols=['W'] * 1,
                             scaled_positions= primitive.get_scaled_positions())
         bulk.set_cell(np.diag((a, a, a)))
         phonon = Phonopy(bulk,
                          [[s,0.,0.],[0.,s,0.],[0.,0.,s]],
                          primitive_matrix=[[-0.5, 0.5, 0.5],[0.5, -0.5, 0.5],[0.5, 0.5, -0.5]],
                          distance=0.01, factor=15.633302)
         print fc
         phonon.set_force_constants(fc[0])
         phonon.set_dynamical_matrix()
         #print phonon.get_dynamical_matrix_at_q([0,0,0])
         mesh = [100, 100, 100]
         phonon.set_mesh(mesh)
         qpoints, weights, frequencies, eigvecs = phonon.get_mesh()
         print frequencies
         phonon.set_total_DOS()
         
         phonon.set_thermal_properties(t_step=10,
                                       t_max=3700,
                                       t_min=0)
     elif species == 'WRe_0.06': 
         fc = vasp.get_force_constants_vasprun_xml(vasprun,3,0)
         s = 2.
         a = superc.get_cell()[0][0]*2.
         print a
         bulk = PhonopyAtoms(symbols=['W'] * 1,
                             scaled_positions= primitive.get_scaled_positions())
         bulk.set_cell(np.diag((a, a, a)))
         phonon = Phonopy(bulk,
                          [[s,0.,0.],[0.,s,0.],[0.,0.,s]],
                          primitive_matrix=[[-0.5, 0.5, 0.5],[0.5, -0.5, 0.5],[0.5, 0.5, -0.5]],
                          distance=0.01, factor=15.633302)
         print fc
         phonon.set_force_constants(fc[0])
         phonon.set_dynamical_matrix()
         #print phonon.get_dynamical_matrix_at_q([0,0,0])
         mesh = [100, 100, 100]
         phonon.set_mesh(mesh)
         qpoints, weights, frequencies, eigvecs = phonon.get_mesh()
         print frequencies
         phonon.set_total_DOS()
         
         phonon.set_thermal_properties(t_step=10,
                                       t_max=3700,
                                       t_min=0)
     
     elif species == 'WRe_0.09': 
         fc = vasp.get_force_constants_vasprun_xml(vasprun,4,0)
         s = 2.
         a = superc.get_cell()[0][0]*2.
         print a
         bulk = PhonopyAtoms(symbols=['W'] * 1,
                             scaled_positions= primitive.get_scaled_positions())
         bulk.set_cell(np.diag((a, a, a)))
         phonon = Phonopy(bulk,
                          [[s,0.,0.],[0.,s,0.],[0.,0.,s]],
                          primitive_matrix=[[-0.5, 0.5, 0.5],[0.5, -0.5, 0.5],[0.5, 0.5, -0.5]],
                          distance=0.01, factor=15.633302)
         print fc
         phonon.set_force_constants(fc[0])
         phonon.set_dynamical_matrix()
         #print phonon.get_dynamical_matrix_at_q([0,0,0])
         mesh = [100, 100, 100]
         phonon.set_mesh(mesh)
         qpoints, weights, frequencies, eigvecs = phonon.get_mesh()
         print frequencies
         phonon.set_total_DOS()
         
         phonon.set_thermal_properties(t_step=10,
                                       t_max=3700,
                                       t_min=0)
     elif species == 'WRe_0.12': 
         fc = vasp.get_force_constants_vasprun_xml(vasprun,5,0)
         s = 2.
         a = superc.get_cell()[0][0]*2.
         print a
         bulk = PhonopyAtoms(symbols=['W'] * 1,
                             scaled_positions= primitive.get_scaled_positions())
         bulk.set_cell(np.diag((a, a, a)))
         phonon = Phonopy(bulk,
                          [[s,0.,0.],[0.,s,0.],[0.,0.,s]],
                          primitive_matrix=[[-0.5, 0.5, 0.5],[0.5, -0.5, 0.5],[0.5, 0.5, -0.5]],
                          distance=0.01, factor=15.633302)
         print fc
         phonon.set_force_constants(fc[0])
         phonon.set_dynamical_matrix()
         #print phonon.get_dynamical_matrix_at_q([0,0,0])
         mesh = [100, 100, 100]
         phonon.set_mesh(mesh)
         qpoints, weights, frequencies, eigvecs = phonon.get_mesh()
         print frequencies
         phonon.set_total_DOS()
         
         phonon.set_thermal_properties(t_step=10,
                                       t_max=3700,
                                       t_min=0)
     
     elif species == 'WRe_0.18': 
         fc = vasp.get_force_constants_vasprun_xml(vasprun,6,0)
         s = 2.
         a = superc.get_cell()[0][0]*2.
         print a
         bulk = PhonopyAtoms(symbols=['W'] * 1,
                             scaled_positions= primitive.get_scaled_positions())
         bulk.set_cell(np.diag((a, a, a)))
         phonon = Phonopy(bulk,
                          [[s,0.,0.],[0.,s,0.],[0.,0.,s]],
                          primitive_matrix=[[-0.5, 0.5, 0.5],[0.5, -0.5, 0.5],[0.5, 0.5, -0.5]],
                          distance=0.01, factor=15.633302)
         print fc
         phonon.set_force_constants(fc[0])
         phonon.set_dynamical_matrix()
         #print phonon.get_dynamical_matrix_at_q([0,0,0])
         mesh = [100, 100, 100]
         phonon.set_mesh(mesh)
         qpoints, weights, frequencies, eigvecs = phonon.get_mesh()
         print frequencies
         phonon.set_total_DOS()
         
         phonon.set_thermal_properties(t_step=10,
                                       t_max=3700,
                                       t_min=0)
     elif species == 'WRe_0.25': 
         fc = vasp.get_force_constants_vasprun_xml(vasprun,7,0)
         s = 2.
         a = primitive.get_cell()[0][0]*2.
         print a, primitive.get_scaled_positions()
         bulk = PhonopyAtoms(symbols=['W'] * 1,
                             scaled_positions= primitive.get_scaled_positions())
         bulk.set_cell(np.diag((a, a, a)))
         phonon = Phonopy(bulk,
                          [[s,0.,0.],[0.,s,0.],[0.,0.,s]],
                          primitive_matrix=[[-0.5, 0.5, 0.5],[0.5, -0.5, 0.5],[0.5, 0.5, -0.5]],
                          distance=0.01, factor=15.633302)
         print fc
         phonon.set_force_constants(fc[0])
         phonon.set_dynamical_matrix()
         #print phonon.get_dynamical_matrix_at_q([0,0,0])
         mesh = [100, 100, 100]
         phonon.set_mesh(mesh)
         qpoints, weights, frequencies, eigvecs = phonon.get_mesh()
         print frequencies
         phonon.set_total_DOS()
         #phonon.set_partial_DOS()
         phonon.set_thermal_properties(t_step=10,
                                       t_max=3700,
                                       t_min=0)    
     
     elif species == 'WRe_0.50': 
         fc = vasp.get_force_constants_vasprun_xml(vasprun,8,0)
         s = 2.
         a = superc.get_cell()[0][0]*2.
         print a
         bulk = PhonopyAtoms(symbols=['W'] * 1,
                             scaled_positions= primitive.get_scaled_positions())
         bulk.set_cell(np.diag((a, a, a)))
         phonon = Phonopy(bulk,
                          [[s,0.,0.],[0.,s,0.],[0.,0.,s]],
                          primitive_matrix=[[-0.5, 0.5, 0.5],[0.5, -0.5, 0.5],[0.5, 0.5, -0.5]],
                          distance=0.01, factor=15.633302)
         #print fc
         phonon.set_force_constants(fc[0])
         phonon.set_dynamical_matrix()
         #print phonon.get_dynamical_matrix_at_q([0,0,0])
         mesh = [100, 100, 100]
         phonon.set_mesh(mesh)
         qpoints, weights, frequencies, eigvecs = phonon.get_mesh()
         #print frequencies
         phonon.set_total_DOS()
         #phonon.set_partial_DOS()
         phonon.set_thermal_properties(t_step=10,
                                       t_max=3700,
                                       t_min=0)    
         
         
     elif species == 'Au': 
         fc = vasp.get_force_constants_vasprun_xml(vasprun,1,0)
         #Gold
         s = 5.
         a = superc.get_cell()[0][0]
         bulk = PhonopyAtoms(symbols=['Au'] * 1,
                             scaled_positions= primitive.get_scaled_positions())
         bulk.set_cell(np.diag((a, a, a)))
         phonon = Phonopy(bulk,
                          [[s,0.,0.],[0.,s,0.],[0.,0.,s]],
                          primitive_matrix=[[0.5, 0.5, 0.0],[0.0, 0.5, 0.5],[0.5, 0.0, 0.5]],
                          distance=0.01, factor=15.633302)
         
         phonon.set_force_constants(fc[0])
         phonon.set_dynamical_matrix()
         #print phonon.get_dynamical_matrix_at_q([0,0,0])
         mesh = [100, 100, 100]
         phonon.set_mesh(mesh)
         qpoints, weights, frequencies, eigvecs = phonon.get_mesh()
         print frequencies
         phonon.set_total_DOS()
         phonon.set_partial_DOS()
         phonon.set_thermal_properties(t_step=10,
                                       t_max=1300,
                                       t_min=0)
     
     elif species == 'Mo': 
         fc = vasp.get_force_constants_vasprun_xml(vasprun,10,0)
         s = 5.
         a = superc.get_cell()[0][0]*2.
         print a
         bulk = PhonopyAtoms(symbols=['Mo'] * 1,
                             scaled_positions= primitive.get_scaled_positions())
         bulk.set_cell(np.diag((a, a, a)))
         phonon = Phonopy(bulk,
                          [[s,0.,0.],[0.,s,0.],[0.,0.,s]],
                          primitive_matrix=[[-0.5, 0.5, 0.5],[0.5, -0.5, 0.5],[0.5, 0.5, -0.5]],
                          distance=0.01, factor=15.633302)
         print fc
         phonon.set_force_constants(fc[0])
         phonon.set_dynamical_matrix()
         #print phonon.get_dynamical_matrix_at_q([0,0,0])
         mesh = [100, 100, 100]
         phonon.set_mesh(mesh)
         qpoints, weights, frequencies, eigvecs = phonon.get_mesh()
         print frequencies
         phonon.set_total_DOS()
         
         phonon.set_thermal_properties(t_step=10,
                                       t_max=2500,
                                       t_min=0)
     
     
     elif species == 'Re': 
         fc = vasp.get_force_constants_vasprun_xml(vasprun,9,0)
         s = 5.
         a = superc.get_cell()[0][0]*2.
         print a
         bulk = PhonopyAtoms(symbols=['Re'] * 1,
                             scaled_positions= primitive.get_scaled_positions())
         bulk.set_cell(np.diag((a, a, a)))
         phonon = Phonopy(bulk,
                          [[s,0.,0.],[0.,s,0.],[0.,0.,s]],
                          primitive_matrix=[[-0.5, 0.5, 0.5],[0.5, -0.5, 0.5],[0.5, 0.5, -0.5]],
                          distance=0.01, factor=15.633302)
         print fc
         phonon.set_force_constants(fc[0])
         phonon.set_dynamical_matrix()
         #print phonon.get_dynamical_matrix_at_q([0,0,0])
         mesh = [100, 100, 100]
         phonon.set_mesh(mesh)
         qpoints, weights, frequencies, eigvecs = phonon.get_mesh()
         print frequencies
         phonon.set_total_DOS()
         
         phonon.set_thermal_properties(t_step=10,
                                       t_max=2500,
                                       t_min=0)
     
     
     f = open('F_TV','w')
     for t, free_energy, entropy, cv in np.array(phonon.get_thermal_properties()).T:
         #print t, cv
         #print ("%12.3f " + "%15.7f" * 3) % ( t, free_energy, entropy, cv )
         f.write(("%12.3f " + "%15.7f" + "\n") % ( t, free_energy))
     f.close()
     
     fc = open('thermal_properties','w')
     for t, free_energy, entropy, cv in np.array(phonon.get_thermal_properties()).T:
         fc.write(("%12.3f " + "%15.7f" *3 + "\n") % ( t, free_energy, entropy, cv ))
     fc.close()
     
     #phonon.plot_thermal_properties().show()
     
     #phonon.plot_total_DOS().show()
     phonon.write_total_DOS()
     #phonon.write_partial_DOS()
     phonon.write_yaml_thermal_properties()
     
     bands = []
     
     #### PRIMITIVE
     
     q_start  = np.array([0.0, 0.0, 0.0])
     #q_start  = np.array([0.5, 0.5, 0.0])
     q_end    = np.array([-0.5, 0.5, 0.5])
     #q_end    = np.array([0., 0., 0.])
     band = []
     for i in range(101):
         band.append(q_start + (q_end - q_start) / 100 * i)
     bands.append(band)
     
     band = []
     
     
     q_start  = np.array([-0.5, 0.5, 0.5])
     #q_start  = np.array([0., 0., 0.])
     q_end    = np.array([0.25, 0.25, 0.25])
     #q_end    = np.array([1., 0., 0.])
     
     for i in range(101):
         #band.append([-0.5+3*1/400*i, 0.5-1/400*i, 0.5-1/400*i])
         band.append(q_start + (q_end - q_start) / 100 * i)
     bands.append(band)
     #print band
     q_start  = np.array([0.25, 0.25, 0.25])
     q_end    = np.array([0., 0., 0.])
     band = []
     for i in range(101):
         band.append(q_start + (q_end - q_start) / 100 * i)
     bands.append(band)
     
     q_start  = np.array([0., 0., 0.])
     q_end    = np.array([0.0, 0., 0.5])
     band = []
     for i in range(101):
         band.append(q_start + (q_end - q_start) / 100 * i)
     bands.append(band)
     
     #q_start  = np.array([0.0, 0.0, 0.0])
     #q_end    = np.array([0.5, 0.5, 0.5])
     #band = []
     #for i in range(101):
     #    band.append(q_start + (q_end - q_start) / 100 * i)
     #bands.append(band)
     
     """
     ###### CONVENTIONAL CELL ######
     q_start  = np.array([0.0, 0.0, 0.0])
     q_end    = np.array([-0.5, 0.5, 0.5])
     band = []
     for i in range(101):
         band.append(q_start + (q_end - q_start) / 100 * i)
     bands.append(band)
     
     
     q_start  = np.array([-0.5, 0.5, 0.5])
     q_end    = np.array([1./4., 1./4., 1./4.])
     band = []
     for i in range(101):
         band.append(q_start + (q_end - q_start) / 100 * i)
     bands.append(band)
     q_start  = np.array([1./4., 1./4., 1./4.])
     q_end    = np.array([0.0, 0.0, 0.0])
     band = []
     for i in range(101):
         band.append(q_start + (q_end - q_start) / 100 * i)
     bands.append(band)
     q_start  = np.array([0.0, 0.0, 0.0])
     q_end    = np.array([0.5, 0.0, 0.0])
     band = []
     for i in range(101):
         band.append(q_start + (q_end - q_start) / 100 * i)
     bands.append(band)
     """
     phonon.set_band_structure(bands)
     #phonon.plot_band_structure().show()
     
     q_points, distances, frequencies, eigvecs = phonon.get_band_structure()
     disp = {'q':q_points, 'distances':distances, 'frequencies':frequencies, 'eigvecs':eigvecs}
     f = open('ph_dispersion.pkl','w')
     pickle.dump(disp, f)
     f.close()
Esempio n. 6
0
import numpy as np
from phonopy import Phonopy
from phonopy.interface.vasp import read_vasp
from phonopy.file_IO import parse_FORCE_SETS, parse_BORN
import matplotlib.pyplot as plt

unitcell = read_vasp("POSCAR")
phonon = Phonopy(unitcell, [[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]])

force_sets = parse_FORCE_SETS()
phonon.set_displacement_dataset(force_sets)
phonon.produce_force_constants()
primitive = phonon.get_primitive()
nac_params = parse_BORN(primitive, filename="BORN")
phonon.set_nac_params(nac_params)
phonon.set_group_velocity()
phonon.set_mesh([31, 31, 31])
qpoints, weights, frequencies, _ = phonon.get_mesh()
group_velocity = phonon.get_group_velocity()
gv_norm = np.sqrt((group_velocity**2).sum(axis=2))
for i, (f, g) in enumerate(zip(frequencies.T, gv_norm.T)):
    plt.plot(f, g, 'o', label=('band%d' % (i + 1)))
plt.legend()
plt.xlabel("Frequency (THz)")
plt.ylabel("|group-velocity| (THz.A)")
plt.show()
class thermal_conductivity():
    def __init__(self, primitive_cell, super_cell):
        self.primitive_cell = primitive_cell
        self.super_cell = super_cell

    def input_files(self, path_POSCAR, path_FORCECONSTANT):
        bulk = read_vasp(path_POSCAR)
        self.phonon = Phonopy(bulk,
                              self.super_cell,
                              primitive_matrix=self.primitive_cell)
        force_constants = file_IO.parse_FORCE_CONSTANTS(path_FORCECONSTANT)
        self.phonon.set_force_constants(force_constants)
        return self.phonon

    def set_mesh(self, mesh):
        self.phonon.set_mesh(mesh, is_eigenvectors=True)

    def set_point_defect_parameter(self, fi, defect_mass, defect_fc_ratio):

        self.mass = self.phonon.get_primitive().get_masses().sum(
        ) / self.phonon.get_primitive().get_number_of_atoms()
        self.cellvol = self.phonon.get_primitive().get_volume()
        self.mass_fc_factor = self.cellvol * 10**-30 / 2.0 / 4 / np.pi * (
            fi *
            ((self.mass - defect_mass) / self.mass + 2 * defect_fc_ratio)**2)

    def kappa_separate(self, gamma, thetaD, T, P=1, m=3, n=1):
        """
        nkpts: number of phonon k-points
        frequencies: list of eigenvalue-arrays as output by phonopy
        vgroup: group velocities
        T: temperature in K

        following parameters from Eq (70) in Tritt book, p.14
        P: proportionality factor of Umklapp scattering rate, defualt 1
        mass: mass in amu (average mass of unitcell)
        gamma: Gruneisen parameter, unitless
        thetaD: Debye temperature of relevance (acoustic modes) 283K for Mo3Sb7
        m = 3 by default
        n = 1 by default
        cellvol: unit cell volume in A^3
        """

        T = float(T)
        #self.phonon.set_mesh(mesh, is_eigenvectors=True)
        #self.mass = self.phonon.get_primitive().get_masses().sum()/self.phonon.get_primitive().get_number_of_atoms()
        self.cellvol = self.phonon.get_primitive().get_volume()
        self.qpoints, self.weigths, self.frequencies, self.eigvecs = self.phonon.get_mesh(
        )

        nkpts = self.frequencies.shape[0]
        numbranches = self.frequencies.shape[1]

        self.group_velocity = np.zeros((nkpts, numbranches, 3))
        for i in range(len(self.qpoints)):
            self.group_velocity[i, :, :] = self.phonon.get_group_velocity_at_q(
                self.qpoints[i])

        inv_nor_Um = np.zeros((nkpts, numbranches))
        inv_point_defect_mass_fc = np.zeros((nkpts, numbranches))
        inv_tau_total = np.zeros((nkpts, numbranches))

        kappa_Um = np.zeros((nkpts, numbranches))
        kappa_point_defect_mass_fc = np.zeros((nkpts, numbranches))
        kappa_total = np.zeros((nkpts, numbranches))
        self.kappaten = np.zeros((nkpts, numbranches, 3, 3))

        v_group = np.zeros((nkpts, numbranches))
        capacity = np.zeros((nkpts, numbranches))

        for i in range(nkpts):
            for j in range(numbranches):
                nu = self.frequencies[i][
                    j]  # frequency (in Thz) of current mode
                velocity = self.group_velocity[
                    i, j, :]  # cartesian vector of group velocity
                v_group = (velocity[0]**2 + velocity[1]**2 +
                           velocity[2]**2)**(0.5) * THztoA
                capacity[i, j] = mode_cv(
                    T, nu * THzToEv) * eV2Joule / (self.cellvol * Ang2meter**3)

                # tau inverse phonon-phonon, inverse lifetime
                inv_nor_Um[i, j] = P * hbar * gamma**2 / (
                    self.mass * amu) / v_group**2 * (T**n) / thetaD * (
                        2 * np.pi * THz * nu)**2 * np.exp(
                            (-1.0) * thetaD / m / T)

                # tau inverse point defect, inverse lifetime
                inv_point_defect_mass_fc[i, j] = (self.mass_fc_factor) * (
                    2 * np.pi * THz * nu)**4 / v_group**3

                # tau inverst, inverse lifetime
                inv_tau_total[
                    i, j] = inv_nor_Um[i, j] + inv_point_defect_mass_fc[i, j]

                kappa_total[
                    i,
                    j] = (1.0 / 3.0) * self.weigths[i] * v_group**2 * capacity[
                        i,
                        j] / inv_tau_total[i,
                                           j]  # 1/3 is for isotropic condition
                kappa_Um[
                    i,
                    j] = (1.0 / 3.0) * self.weigths[i] * v_group**2 * capacity[
                        i, j] / inv_nor_Um[i,
                                           j]  # 1/3 is for isotropic condition
                kappa_point_defect_mass_fc[
                    i,
                    j] = (1.0 / 3.0) * self.weigths[i] * v_group**2 * capacity[
                        i, j] / inv_point_defect_mass_fc[
                            i, j]  # 1/3 is for isotropic condition
                self.kappaten[i, j, :, :] = self.weigths[i] * np.outer(
                    velocity,
                    velocity) * THztoA**2 * capacity[i, j] / inv_tau_total[i,
                                                                           j]
        #print(np.sum(inv_nor_Um, axis =1))
        #print(np.sum(inv_point_defect_mass_fc, axis =1))
        #print(np.sum(inv_tau_total, axis =1))
        self.tau = np.concatenate(
            (inv_nor_Um, inv_point_defect_mass_fc, inv_tau_total), axis=1)
        self.kappa = [
            kappa_Um.sum() / self.weigths.sum(),
            kappa_point_defect_mass_fc.sum() / self.weigths.sum(),
            kappa_total.sum() / self.weigths.sum()
        ]
        return self.tau, self.kappa, self.kappaten
Esempio n. 8
0
from phonopy.interface.vasp import read_vasp
from phonopy.file_IO import parse_FORCE_SETS, parse_BORN
import matplotlib.pyplot as plt

unitcell = read_vasp("POSCAR")
phonon = Phonopy(unitcell,
                 [[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]])

force_sets = parse_FORCE_SETS()
phonon.set_displacement_dataset(force_sets)
phonon.produce_force_constants()
primitive = phonon.get_primitive()
nac_params = parse_BORN(primitive, filename="BORN")
phonon.set_nac_params(nac_params)
phonon.set_group_velocity()
phonon.set_mesh([31, 31, 31])
qpoints, weights, frequencies, _ = phonon.get_mesh()
group_velocity = phonon.get_group_velocity()
gv_norm = np.sqrt((group_velocity ** 2).sum(axis=2))
for i, (f, g) in enumerate(zip(frequencies.T, gv_norm.T)):
    plt.plot(f, g, 'o', label=('band%d' % (i + 1)))
plt.legend()
plt.xlabel("Frequency (THz)")
plt.ylabel("|group-velocity| (THz.A)")
plt.show()