Esempio n. 1
0
def aucu_phonons():
    N = 7
    atoms = bulk("Au", crystalstructure="fcc", a=4.08)
    calc = EMT()
    atoms.set_calculator(calc)

    ph = Phonons(atoms, calc, supercell=(N, N, N), delta=0.05)
    ph.run()
    ph.read(acoustic=True)
    ph.clean()
    omega_e_au, dos_e_au = ph.dos(kpts=(50, 50, 50), npts=1000, delta=5E-4)

    atoms = bulk("Cu", crystalstructure="fcc", a=3.62)
    atoms.set_calculator(calc)

    ph = Phonons(atoms, calc, supercell=(N, N, N), delta=0.05)
    ph.run()
    ph.read(acoustic=True)
    ph.clean()
    omega_e_cu, dos_e_cu = ph.dos(kpts=(13, 13, 13), npts=100, delta=5E-4)

    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    ax.plot(omega_e_au * 1000.0, dos_e_au)
    ax.plot(omega_e_cu * 1000.0, dos_e_cu)
    ax.set_xlabel("Energy (meV)")

    logw_au = np.sum(np.log(omega_e_au[1:]) * dos_e_au[1:])
    logw_cu = np.sum(np.log(omega_e_cu[1:]) * dos_e_cu[1:])
    print(logw_au, logw_cu, logw_au - logw_cu)
    plt.show()
Esempio n. 2
0
def phonon_run(runID, save_to_db=False, plot_bands=False):
    print("Running ID %d" % (runID))
    db = connect(db_name)
    atoms = db.get_atoms(id=runID)
    #view(atoms)
    #atoms = bulk("Al")
    #atoms = atoms*(2,1,1)
    #calc = EAM(potential="/home/davidkl/Documents/EAM/Al-LEA.eam.alloy")
    calc = EAM(potential="/home/davidkl/Documents/EAM/mg-al-set.eam.alloy")
    atoms.set_calculator(calc)
    #calc = gp.GPAW( mode=gp.PW(600), xc="PBE", kpts=(4,4,4), nbands="120%", symmetry="off" )
    #atoms.set_calculator(calc)
    ph = Phonons(atoms,
                 calc,
                 supercell=(3, 3, 3),
                 name=wrk + "/phonon_files/phonon%d" % (runID))
    ph.run()
    #return
    ph.read(acoustic=True)
    omega_e, dos_e = ph.dos(kpts=(30, 30, 30), npts=1000, delta=5E-4)
    if (plot_bands):
        points = ibz_points['fcc']
        G = points['Gamma']
        X = points['X']
        W = points['W']
        K = points['K']
        L = points['L']
        U = points['U']
        point_names = ['$\Gamma$', 'X', 'U', 'L', '$\Gamma$', 'K']
        path = [G, X, U, L, G, K]

        path_kc, q, Q = bandpath(path, atoms.cell, 100)
        omega_kn = 1000.0 * ph.band_structure(path_kc)

        figb = plt.figure()
        axb = figb.add_subplot(1, 1, 1)
        for n in range(len(omega_kn[0])):
            omega_n = omega_kn[:, n]
            axb.plot(q, omega_n)
        plt.show()

    if (save_to_db):
        # Store the results in the database
        db.update(runID, has_dos=True)

        manager = cpd.PhononDOS_DB(db_name)

        # Extract relevant information from the atoms database
        row = db.get(id=runID)
        name = row.name
        atID = row.id
        manager.save(name=name, atID=atID, omega_e=omega_e, dos_e=dos_e)
def test_crystal_thermo(asap3, testdir):
    atoms = bulk('Al', 'fcc', a=4.05)
    calc = asap3.EMT()
    atoms.calc = calc
    energy = atoms.get_potential_energy()

    # Phonon calculator
    N = 7
    ph = Phonons(atoms, calc, supercell=(N, N, N), delta=0.05)
    ph.run()

    ph.read(acoustic=True)
    phonon_energies, phonon_DOS = ph.dos(kpts=(4, 4, 4), npts=30, delta=5e-4)

    thermo = CrystalThermo(phonon_energies=phonon_energies,
                           phonon_DOS=phonon_DOS,
                           potentialenergy=energy,
                           formula_units=4)
    thermo.get_helmholtz_energy(temperature=298.15)
def test_thermochemistry():
    """Tests of the major methods (HarmonicThermo, IdealGasThermo,
    CrystalThermo) from the thermochemistry module."""

    # Ideal gas thermo.
    atoms = Atoms('N2', positions=[(0, 0, 0), (0, 0, 1.1)], calculator=EMT())
    QuasiNewton(atoms).run(fmax=0.01)
    energy = atoms.get_potential_energy()
    vib = Vibrations(atoms, name='idealgasthermo-vib')
    vib.run()
    vib_energies = vib.get_energies()

    thermo = IdealGasThermo(vib_energies=vib_energies,
                            geometry='linear',
                            atoms=atoms,
                            symmetrynumber=2,
                            spin=0,
                            potentialenergy=energy)
    thermo.get_gibbs_energy(temperature=298.15, pressure=2 * 101325.)

    # Harmonic thermo.

    atoms = fcc100('Cu', (2, 2, 2), vacuum=10.)
    atoms.set_calculator(EMT())
    add_adsorbate(atoms, 'Pt', 1.5, 'hollow')
    atoms.set_constraint(
        FixAtoms(indices=[atom.index for atom in atoms
                          if atom.symbol == 'Cu']))
    QuasiNewton(atoms).run(fmax=0.01)
    vib = Vibrations(
        atoms,
        name='harmonicthermo-vib',
        indices=[atom.index for atom in atoms if atom.symbol != 'Cu'])
    vib.run()
    vib.summary()
    vib_energies = vib.get_energies()

    thermo = HarmonicThermo(vib_energies=vib_energies,
                            potentialenergy=atoms.get_potential_energy())
    thermo.get_helmholtz_energy(temperature=298.15)

    # Crystal thermo.
    atoms = bulk('Al', 'fcc', a=4.05)
    calc = EMT()
    atoms.set_calculator(calc)
    energy = atoms.get_potential_energy()

    # Phonon calculator
    N = 7
    ph = Phonons(atoms, calc, supercell=(N, N, N), delta=0.05)
    ph.run()

    ph.read(acoustic=True)
    phonon_energies, phonon_DOS = ph.dos(kpts=(4, 4, 4), npts=30, delta=5e-4)

    thermo = CrystalThermo(phonon_energies=phonon_energies,
                           phonon_DOS=phonon_DOS,
                           potentialenergy=energy,
                           formula_units=4)
    thermo.get_helmholtz_energy(temperature=298.15)

    # Hindered translator / rotor.
    # (Taken directly from the example given in the documentation.)

    vibs = np.array([
        3049.060670, 3040.796863, 3001.661338, 2997.961647, 2866.153162,
        2750.855460, 1436.792655, 1431.413595, 1415.952186, 1395.726300,
        1358.412432, 1335.922737, 1167.009954, 1142.126116, 1013.918680,
        803.400098, 783.026031, 310.448278, 136.112935, 112.939853, 103.926392,
        77.262869, 60.278004, 25.825447
    ])
    vib_energies = vibs / 8065.54429  # Convert to eV from cm^-1.
    trans_barrier_energy = 0.049313  # eV
    rot_barrier_energy = 0.017675  # eV
    sitedensity = 1.5e15  # cm^-2
    rotationalminima = 6
    symmetrynumber = 1
    mass = 30.07  # amu
    inertia = 73.149  # amu Ang^-2

    thermo = HinderedThermo(vib_energies=vib_energies,
                            trans_barrier_energy=trans_barrier_energy,
                            rot_barrier_energy=rot_barrier_energy,
                            sitedensity=sitedensity,
                            rotationalminima=rotationalminima,
                            symmetrynumber=symmetrynumber,
                            mass=mass,
                            inertia=inertia)

    helmholtz = thermo.get_helmholtz_energy(temperature=298.15)
    target = 1.593  # Taken from documentation example.
    assert (helmholtz - target) < 0.001
Esempio n. 5
0
from ase.calculators.emt import EMT
from ase.optimize import QuasiNewton
from ase.phonons import Phonons
from ase.thermochemistry import CrystalThermo

# Set up gold bulk and attach EMT calculator
a = 4.078
atoms = crystal('Au', (0., 0., 0.),
                spacegroup=225,
                cellpar=[a, a, a, 90, 90, 90],
                pbc=(1, 1, 1))
calc = EMT()
atoms.set_calculator(calc)
qn = QuasiNewton(atoms)
qn.run(fmax=0.05)
electronicenergy = atoms.get_potential_energy()

# Phonon analysis
N = 5
ph = Phonons(atoms, calc, supercell=(N, N, N), delta=0.05)
ph.run()
ph.read(acoustic=True)
phonon_energies, phonon_DOS = ph.dos(kpts=(40, 40, 40), npts=3000, delta=5e-4)

# Calculate the Helmholtz free energy
thermo = CrystalThermo(phonon_energies=phonon_energies,
                       phonon_DOS=phonon_DOS,
                       electronicenergy=electronicenergy,
                       formula_units=4)
F = thermo.get_helmholtz_energy(temperature=298.15)
Esempio n. 6
0
class ThermalProperties(object):
    """Class with methods to calculate thermal properties of a structure within the QHA

    Attributes
    ----------
    name : str
        Base name for the files used for the phonon calculations.
    structure : ATAT2EMT
        ATAT structure file describing the primitive cell.
    atoms : ase.Atoms
        Atoms object with the primitive cell.
    calc : ase.Calculator
        Callable returning a Calculator to use for all energy and force calculations.
    n_atoms : int
        Number of atoms in the primitive cell.
    temperature : Iterable of float
        Temperatures at which to calculate temperature dependent properties.
    strains : Iterable of float
        Strains to apply to the atoms for volume dependent properties.
    strained_thermo : list of ThermalProperties
        List with classes for the thermal properties of strained versions of the atoms object.
    sjeos : SJEOS
        Class to fit the equation of state at constant temperature.
    base_dir : str
        Base directory for the calculations. (WARNING: not fully implemented)
    verbosity : int >= 0
        Verbosity level.
    do_plotting : bool
        Determines if the plottings are activated.
    supercell_size : tuple of 3 int
        Size of the supercell to do the phonon calculations.
    thermo : ase.CrystalThermo
        Class to delegate the calculation of some thermodynamic properties.
    phonons : ase.Phonons
        Class to perform phonon calculations using the supercell approach.
    phonon_kpts_mp : (N, 3) np.ndarray
        Monkhorst-Pack k-point grid.
    phonon_energy_mp : (N,) np.ndarray
        Energies of the corresponding MP k-points.
    phonon_energy : np.ndarray
        Energies to calculate the Phonon density of states.
    phonon_dos : np.ndarray
        Phonon density of states at given energies.

    Parameters
    ----------
    atoms :
    calc :
    supercell_size :
    atat_structure :
    plot :
    verbosity :
    name :

    """
    def __init__(self,
                 atoms=None,
                 calc=None,
                 supercell_size=5,
                 atat_structure=None,
                 plot=False,
                 verbosity=0,
                 name='thermo'):
        # relaxed structure
        self.name = name
        self.structure = None
        self.atoms = None
        self.calc = None
        self.n_atoms = 0
        self.temperature = None
        self.strains = None
        self.strained_thermo = []
        if atoms is not None and atat_structure is not None:
            print('ERROR: only atoms OR atat_structure can be specified')
            return
        if atoms is not None:
            self.atoms = atoms
            self.n_atoms = len(self.atoms)
            if self.atoms.calc is None:
                assert calc is not None
                self.atoms.set_calculator(calc())
                self.calc = calc
            else:
                self.calc = atoms.calc
        elif atat_structure is not None:
            assert calc is not None
            self.calc = calc
            self.structure = ATAT2EMT(atat_structure,
                                      calc(),
                                      to_niggli=True,
                                      verbosity=verbosity)
            self.structure.atoms.wrap()
            self.atoms = self.structure.atoms
            self.n_atoms = len(self.atoms)
        # isgn = spglib.get_symmetry_dataset(self.atoms, symprec=1e-3)['number']
        # self.symmetry = el.crystal_system(isgn)
        self.sjeos = SJEOS()

        self.base_dir = os.getcwd()
        self.verbosity = verbosity
        self.do_plotting = plot

        if isinstance(supercell_size, int):
            self.supercell_size = (supercell_size, supercell_size,
                                   supercell_size)
        else:
            assert len(supercell_size) == 3
            self.supercell_size = supercell_size

        self.get_phonons()

        self.thermo = CrystalThermo(
            phonon_energies=self.phonon_energy,
            phonon_DOS=self.phonon_dos,
            potentialenergy=self.atoms.get_potential_energy(),
            formula_units=self.n_atoms)

    def set_temperature(self, temperature, save_at='.'):
        """Set the temperature grid.

        Parameters
        ----------
        temperature : iterable of float
            Iterable containing the temperatures at which to calculate the properties.
        save_at : string
            Path (relative or absolute) in which to store the value.

        """
        if save_at is not None:
            if not os.path.exists(save_at):
                os.makedirs(save_at)
            save_name = os.path.join(save_at, 'T.dat')
            np.savetxt(save_name, temperature)
        self.temperature = temperature

    def get_phonons(self, kpts=(50, 50, 50), npts=5000):
        """Calculate the phonon spectrum and DOS.

        Parameters
        ----------
        kpts : tuple
            Number of points in each directions of the k-space grid.
        npts : int
            Number of energy points to calculate the DOS at.

        """
        self.phonons = Phonons(self.atoms,
                               self.calc(),
                               supercell=self.supercell_size,
                               delta=0.05,
                               name=self.name)
        self.phonons.run()
        # Read forces and assemble the dynamical matrix
        self.phonons.read(acoustic=True)
        self.phonon_kpts_mp = monkhorst_pack(kpts)
        self.phonon_energy_mp = self.phonons.band_structure(
            self.phonon_kpts_mp)
        self.phonon_energy, self.phonon_dos = \
            self.phonons.dos(kpts=kpts, npts=npts, delta=5e-4)

    def get_volume_phonons(self, nvolumes=5, max_strain=0.02):
        """Calculate the volume dependent phonons.

        Parameters
        ----------
        nvolumes : int > 0
            Number of volumes to calculate the phonon spectrum.
        max_strain : float > 0
            Maximum (isotropic) strain used to deform equilibrium volume.

        """
        strains = np.linspace(-max_strain, max_strain, nvolumes)
        load = False
        if self.strains is None:
            self.strains = strains
        else:
            if not (strains == self.strains).all():
                self.strains = strains
                self.strained_thermo = []
            else:
                load = True
        strain_matrices = [np.eye(3) * (1 + s) for s in self.strains]
        atoms = self.atoms
        cell = atoms.cell
        for i, s in enumerate(strain_matrices):
            satoms = atoms.copy()
            satoms.set_cell(np.dot(cell, s.T), scale_atoms=True)
            if load:
                pass
            else:
                satoms.set_calculator(None)
                sthermo = ThermalProperties(satoms,
                                            self.calc,
                                            name='thermo_{:.2f}'.format(
                                                self.strains[i]))
                self.strained_thermo.append(sthermo)

    def get_volume_energy(self, temperature=None, nvolumes=5, max_strain=0.02):
        """Return the volume dependent (Helmholtz) energy.

        Parameters
        ----------
        temperature : float > 0
            Temeprature at which the volume-energy curve is calculated.
        nvolumes : int > 0
            Number of volumes to calculate the energy at.
        max_strain : float > 0
            Maximum (isotropic) strain used to deform equilibrium volume.
        save_at : string
            Path (relative or absolute) in which to store the value.

        Returns
        -------
        volume : list of double
            Volumes at which the entropy was calculated.
        energy : list of double
            Helmholtz energy for each of the volumes.

        """
        if temperature is None and self.temperature is None:
            print(
                'ERROR. You nee to specify a temperature for the calculations.'
            )
            return
        elif temperature is None:
            temperature = self.temperature

        if isinstance(temperature, collections.Iterable):
            volume_energy = [
                self.get_volume_energy(T, nvolumes, max_strain)
                for T in temperature
            ]
            return volume_energy

        self.get_volume_phonons(nvolumes, max_strain)

        energy = []
        volume = []
        for sthermo in self.strained_thermo:
            energy.append(
                sthermo.get_helmholtz_energy(temperature, save_at=None))
            volume.append(sthermo.atoms.get_volume())

        return volume, energy

    def get_volume_entropy(self,
                           temperature=None,
                           nvolumes=5,
                           max_strain=0.02):
        """Return the volume dependent entropy.

        Parameters
        ----------
        temperature : float > 0
            Temeprature at which the volume-entropy curve is calculated.
        nvolumes : int > 0
            Number of volumes to calculate the entropy at.
        max_strain : float > 0
            Maximum (isotropic) strain used to deform equilibrium volume.
        save_at : string
            Path (relative or absolute) in which to store the value.

        Returns
        -------
        volume : list of double
            Volumes at which the entropy was calculated.
        entropy : list of double
            Entropy for each of the volumes.

        """
        if temperature is None and self.temperature is None:
            print(
                'ERROR. You nee to specify a temperature for the calculations.'
            )
            return
        elif temperature is None:
            temperature = self.temperature

        if isinstance(temperature, collections.Iterable):
            volume_entropy = [
                self.get_volume_entropy(T, nvolumes, max_strain)
                for T in temperature
            ]
            return volume_entropy

        self.get_volume_phonons(nvolumes, max_strain)

        entropy = []
        volume = []
        for sthermo in self.strained_thermo:
            entropy.append(sthermo.get_entropy(temperature, save_at=None))
            volume.append(sthermo.atoms.get_volume())

        return volume, entropy

    def get_entropy(self, temperature=None, save_at='.'):
        """Return entropy per atom in eV / atom.

        Parameters
        ----------
        temperature : float > 0
            Temeprature at which the Helmholtz energy is calculated.
        save_at : string
            Path (relative or absolute) in which to store the value.

        Returns
        -------
        entropy : float
            Entropy in eV / atom

        Notes
        -----
        To convert to SI units, divide by units.J.
        At the moment only vibrational entropy is included. Electronic entropy can
        be included if the calculator provides the electronic DOS.

        """
        if temperature is None and self.temperature is None:
            print(
                'ERROR. You nee to specify a temperature for the calculations.'
            )
            return
        elif temperature is None:
            temperature = self.temperature

        if save_at is not None:
            if not os.path.exists(save_at):
                os.makedirs(save_at)
            save_name = os.path.join(save_at, 'S.dat')

        if isinstance(temperature, collections.Iterable):
            vib_entropy = [
                self.get_entropy(T, save_at=None) for T in temperature
            ]
            if save_at is not None:
                np.savetxt(save_name, vib_entropy)
            return np.array(vib_entropy)
        if temperature == 0.:
            if save_at is not None:
                np.savetxt(save_name, np.asarray([0.]))
            return 0.

        vib_entropy = self.thermo.get_entropy(temperature, self.verbosity)
        if save_at is not None:
            np.savetxt(save_name, vib_entropy)
        return vib_entropy

    def get_helmholtz_energy(self, temperature=None, save_at='.'):
        """Return Helmholtz energy per atom in eV / atom.

        Parameters
        ----------
        temperature : float > 0
            Temeprature at which the Helmholtz energy is calculated.
        save_at : string
            Path (relative or absolute) in which to store the value.

        Returns
        -------
        helmholtz_energy : float
            Helmholtz energy in eV / atom

        Notes
        -----
        To convert to SI units, divide by units.J.

        """
        if temperature is None and self.temperature is None:
            print(
                'ERROR. You nee to specify a temperature for the calculations.'
            )
            return
        elif temperature is None:
            temperature = self.temperature

        if save_at is not None:
            if not os.path.exists(save_at):
                os.makedirs(save_at)
            save_name = os.path.join(save_at, 'F.dat')

        if isinstance(temperature, collections.Iterable):
            helmholtz_energy = [
                self.get_helmholtz_energy(T, save_at=None) for T in temperature
            ]
            if save_at is not None:
                np.savetxt(save_name, helmholtz_energy)
            return np.array(helmholtz_energy)
        if temperature == 0.:
            helmholtz_energy = self.get_zero_point_energy(
            ) + self.thermo.potentialenergy
            if save_at is not None:
                np.savetxt(save_name, helmholtz_energy)
            return helmholtz_energy

        helmholtz_energy = self.thermo.get_helmholtz_energy(
            temperature, self.verbosity)
        if save_at is not None:
            np.savetxt(save_name, helmholtz_energy)
        return helmholtz_energy

    def get_internal_energy(self, temperature=None, save_at='.'):
        """Return internal energy per atom in eV / atom.

        Parameters
        ----------
        temperature : float > 0
            Temeprature at which the internal energy is calculated.
        save_at : string
            Path (relative or absolute) in which to store the value.

        Returns
        -------
        internal_energy : float
            Internal energy in eV / atom

        Notes
        -----
        To convert to SI units, divide by units.J.

        """
        if temperature is None and self.temperature is None:
            print(
                'ERROR. You nee to specify a temperature for the calculations.'
            )
            return
        elif temperature is None:
            temperature = self.temperature

        if save_at is not None:
            if not os.path.exists(save_at):
                os.makedirs(save_at)
            save_name = os.path.join(save_at, 'U.dat')

        if isinstance(temperature, collections.Iterable):
            internal_energy = [
                self.get_internal_energy(T, save_at=None) for T in temperature
            ]
            if save_at is not None:
                np.savetxt(save_name, internal_energy)
            return np.array(internal_energy)
        if temperature == 0.:
            internal_energy = self.get_zero_point_energy(
            ) + self.thermo.potentialenergy
            if save_at is not None:
                np.savetxt(save_name, internal_energy)
            return internal_energy

        internal_energy = self.thermo.get_internal_energy(
            temperature, self.verbosity)

        if save_at is not None:
            np.savetxt(save_name, internal_energy)

        return internal_energy

    def get_zero_point_energy(self):
        """Return the Zero Point Energy in eV / atom.

        Returns
        -------
        zpe: float
            Zero point energy in eV / atom.

        """
        zpe_list = self.phonon_energy / 2.
        zpe = np.trapz(zpe_list * self.phonon_dos,
                       self.phonon_energy) / self.n_atoms
        return zpe

    def get_specific_heat(self, temperature=None, save_at='.'):
        """Return heat capacity per atom in eV / atom K.
        
        Parameters
        ----------
        temperature : float > 0
            Temeprature at which the specific heat is calculated.
        save_at : string
            Path (relative or absolute) in which to store the value.

        Returns
        -------
        C_V : float
            Specific heat in eV / atom K
            
        Notes
        -----
        To convert to SI units, multiply by (units.mol / units.J).

        """
        if temperature is None and self.temperature is None:
            print(
                'ERROR. You nee to specify a temperature for the calculations.'
            )
            return
        elif temperature is None:
            temperature = self.temperature

        if save_at is not None:
            if not os.path.exists(save_at):
                os.makedirs(save_at)
            save_name = os.path.join(save_at, 'Cv.dat')

        if isinstance(temperature, collections.Iterable):
            C_V = [
                self.get_specific_heat(T, save_at=None) for T in temperature
            ]
            if save_at is not None:
                np.savetxt(save_name, C_V)
            return np.array(C_V)

        if temperature == 0.:
            if save_at is not None:
                np.savetxt(save_name, np.asarray([0.]))
            return 0.

        if self.phonon_energy[0] == 0.:
            self.phonon_energy = np.delete(self.phonon_energy, 0)
            self.phonon_dos = np.delete(self.phonon_dos, 0)
        i2kT = 1. / (2. * units.kB * temperature)
        arg = self.phonon_energy * i2kT
        C_v = units.kB * arg**2 / np.sinh(arg)**2
        C_V = np.trapz(C_v * self.phonon_dos,
                       self.phonon_energy) / self.n_atoms
        if save_at is not None:
            np.savetxt(save_name, np.asarray([C_V]))
        return C_V

    def get_thermal_expansion(self,
                              temperature=None,
                              exp_norm_temp=None,
                              nvolumes=5,
                              max_strain=0.02,
                              ntemperatures=5,
                              delta_t=1.,
                              save_at='.'):
        """Return the isotropic volumetric thermal expansion in K^-1.
        
        Parameters
        ----------
        temperature : float > 0
            Temeprature at which the expansion coefficient is calculated.
        exp_norm_temp : float > 0
            Temperature for the normalization of the thermal expansion (usually to compare with experiment).
        nvolumes : int > 0
            Number of volumes to fit the equation of state to extract equilibrium volumes.
        max_strain : float > 0
            Maximum strain used to fit the equation of state to extract equilibrium volumes.
        ntemperatures : int > 0
            Number of temperatures to approximate the temperature derivative of the volume.
        delta_t : float >0
            Temperature step to approximate the temperature derivative of the volume.
        save_at : string
            Path (relative or absolute) in which to store the value.

        Returns
        -------
            : double
            Isotropic volumetric thermal expansion in K^-1

        """
        if temperature is None and self.temperature is None:
            print(
                'ERROR. You nee to specify a temperature for the calculations.'
            )
            return
        elif temperature is None:
            temperature = self.temperature

        if save_at is not None:
            if not os.path.exists(save_at):
                os.makedirs(save_at)
            save_name = os.path.join(save_at, 'thermal_expansion.dat')

        if isinstance(temperature, collections.Iterable):
            alpha_v = [
                self.get_thermal_expansion(T,
                                           exp_norm_temp,
                                           nvolumes,
                                           max_strain,
                                           ntemperatures,
                                           delta_t,
                                           save_at=None) for T in temperature
            ]
            if save_at is not None:
                np.savetxt(save_name, alpha_v)
            return np.array(alpha_v)

        max_delta_t = (ntemperatures - 1) * delta_t
        if temperature - max_delta_t / 2. > 0.:
            temperatures = np.linspace(temperature - max_delta_t / 2.,
                                       temperature + max_delta_t / 2.,
                                       ntemperatures)
            t0 = (ntemperatures - 1) / 2
            mode = 'c'
        else:
            ntemperatures = (ntemperatures + 2) / 2
            temperatures = np.linspace(temperature,
                                       temperature + max_delta_t / 2.,
                                       ntemperatures)
            t0 = 0
            mode = 'f'
        print(temperatures, ntemperatures)
        # 1.- Get V-F points
        Vs = []
        Fs = []
        for T in temperatures:
            V, F = self.get_volume_energy(T, nvolumes, max_strain)
            Vs.append(V)
            Fs.append(F)
        # 2.- Fit EOS to V-F points for each T
        self.sjeos.clean()
        for i in range(ntemperatures):
            V = np.asarray(Vs[i])
            F = np.asarray(Fs[i])
            self.sjeos.fit(V, F)
        # 3.- Numerical derivative dV/dT
        V0s = self.sjeos.get_equilibrium_volume(mean=True)
        fd = FD(temperatures)
        dV_dT = fd.derivative(1, t0, V0s, acc_order=2, mode=mode)
        if self.do_plotting:
            plt.plot(temperatures, V0s)
        # 4a.- Normalize by volume at temperature (same as derivative)
        if exp_norm_temp is None:
            return dV_dT / V0s[(ntemperatures - 1) / 2]
        # 4b.- Normalize by volume at some give reference temperature (different from derivative)
        V, F = self.get_volume_energy(exp_norm_temp, nvolumes, max_strain)
        self.sjeos.clean()
        self.sjeos.fit(np.asarray(V), np.asarray(F))
        V_norm = self.sjeos.get_equilibrium_volume(mean=True)
        alpha_v = dV_dT / V_norm
        if save_at is not None:
            np.savetxt(save_name, alpha_v)
        return alpha_v

    def get_gruneisen(self,
                      temperature=None,
                      nvolumes=5,
                      max_strain=0.02,
                      save_at='.'):
        r"""Return the Gr\"uneisen parameter.

        Parameters
        ----------
        temperature : float > 0
            Temeprature at which the expansion coefficient is calculated.
        nvolumes : int > 0
            Number of volumes to fit the equation of state to extract equilibrium volumes.
        max_strain : float > 0
            Maximum strain used to fit the equation of state to extract equilibrium volumes.
        save_at : string
            Path (relative or absolute) in which to store the value.

        Returns
        -------
        gruneisen : double
            Gr\"uneisen parameter.

        Notes
        -----
        The Gr\"uneisen parameter is calculated as

        .. math ::
            \gamma=\frac{C_v}{V}\left.\frac{\partial S}{\partial V}\right|_T

        """
        if temperature is None and self.temperature is None:
            print(
                'ERROR. You nee to specify a temperature for the calculations.'
            )
            return
        elif temperature is None:
            temperature = self.temperature

        if save_at is not None:
            if not os.path.exists(save_at):
                os.makedirs(save_at)
            save_name = os.path.join(save_at, 'gruneisen.dat')

        if isinstance(temperature, collections.Iterable):
            gruneisen = [
                self.get_gruneisen(T, nvolumes, max_strain, save_at=None)
                for T in temperature
            ]
            if save_at is not None:
                np.savetxt(save_name, gruneisen)
            return gruneisen

        self.get_volume_phonons(nvolumes, max_strain)
        C_V = self.get_specific_heat(temperature)

        V, F = self.get_volume_energy(temperature, nvolumes, max_strain)
        self.sjeos.clean()
        self.sjeos.fit(np.asarray(V), np.asarray(F))
        V_0 = self.sjeos.get_equilibrium_volume(mean=True)[0]

        V, S = self.get_volume_entropy(temperature, nvolumes, max_strain)
        fd = FD(V)
        dS_dV = fd.derivative(1, nvolumes / 2, S, acc_order=2, mode='c')
        gruneisen = dS_dV * V_0 / C_V
        """
        phonon_energy_mp = []
        volumes = []
        hw_V = [[] for i in range(len(self.phonon_energy_mp.ravel()))]
        for sthermo in self.strained_thermo:
            volumes.append(sthermo.atoms.get_volume())
            phonon_energy_mp.append(sthermo.phonon_energy_mp.ravel())
            for j, hw in enumerate(phonon_energy_mp[-1]):
                hw_V[j].append(hw)

        fd = FD(volumes)
        gruneisen_i = np.empty_like(phonon_energy_mp[0])
        for i, hw in enumerate(hw_V):
            dhw_dV = fd.derivative(1, nvolumes/2, hw, acc_order=2, mode='c')
            # print(dhw_dV, hw[nvolumes/2], dhw_dV * volumes[nvolumes/2] / hw[nvolumes/2])
            gruneisen_i[i]\
                = - dhw_dV * volumes[nvolumes/2] / hw[nvolumes/2]

        self.hw_V = hw_V
        self.volumes = volumes

        i2kT = 1. / (2. * units.kB * temperature)
        arg = phonon_energy_mp[nvolumes/2] * i2kT
        C_v = units.kB * arg ** 2 / np.sinh(arg) ** 2

        # print(C_V, C_v, gruneisen_i, volumes)
        # gruneisen = np.trapz(C_v * gruneisen_i * self.phonon_dos, self.phonon_energy) / C_V
        gruneisen = np.sum(C_v * gruneisen_i) / np.sum(C_v)

        print(gruneisen, gruneisen_S)
        plt.scatter(temperature, gruneisen, color='r')
        plt.scatter(temperature, gruneisen_S, color='g')
        """
        if save_at is not None:
            np.savetxt(save_name, gruneisen)

        return gruneisen
Esempio n. 7
0
# High-symmetry points in the Brillouin zone
points = ibz_points['bcc']
G = points['Gamma']
H = points['H']
N = points['N']
P = points['P']

point_names = ['$\Gamma$', 'H', 'P', '$\Gamma$', 'N']
path = [G, H, P, G, N]

# Band structure in meV
path_kc, q, Q = bandpath(path, atoms.cell, 100)
omega_kn = 1000 * ph.band_structure(path_kc)

# Calculate phonon DOS
omega_e, dos_e = ph.dos(kpts=(50, 50, 50), npts=5000, delta=5e-4)
omega_e *= 1000
save_atoms(atoms, q, Q, omega_kn, point_names, dos_e, omega_e)
# Plot the band structure and DOS
# import matplotlib.pyplot as plt
# plt.figure(1, (8, 6))
# plt.axes([.1, .07, .67, .85])
# for n in range(len(omega_kn[0])):
#     omega_n = omega_kn[:, n]
#     plt.plot(q, omega_n, 'k-', lw=2)
#
# plt.xticks(Q, point_names, fontsize=18)
# plt.yticks(fontsize=18)
# plt.xlim(q[0], q[-1])
# plt.ylabel("Frequency ($\mathrm{meV}$)", fontsize=22)
# plt.grid('on')
Esempio n. 8
0
File: gold.py Progetto: PHOTOX/fuase
from ase.optimize import QuasiNewton
from ase.phonons import Phonons
from ase.thermochemistry import CrystalThermo

# Set up gold bulk and attach EMT calculator
a = 4.078
atoms = crystal('Au', (0.,0.,0.),
                spacegroup = 225,
                cellpar = [a, a, a, 90, 90, 90],
                pbc = (1, 1, 1))
calc = EMT()
atoms.set_calculator(calc)
qn = QuasiNewton(atoms)
qn.run(fmax = 0.05)
electronicenergy = atoms.get_potential_energy()

# Phonon analysis
N = 5
ph = Phonons(atoms, calc, supercell=(N, N, N), delta=0.05)
ph.run()
ph.read(acoustic=True)
phonon_energies, phonon_DOS = ph.dos(kpts=(40, 40, 40), npts=3000,
                                     delta=5e-4)

# Calculate the Helmholtz free energy
thermo = CrystalThermo(phonon_energies=phonon_energies,
                       phonon_DOS = phonon_DOS,
                       electronicenergy = electronicenergy,
                       formula_units = 4)
F = thermo.get_helmholtz_energy(temperature=298.15)
Esempio n. 9
0
vib = Vibrations(atoms,
                 name='harmonicthermo-vib',
                 indices=[atom.index for atom in atoms if atom.symbol != 'Cu'])
vib.run()
vib.summary()
vib_energies = vib.get_energies()

thermo = HarmonicThermo(vib_energies=vib_energies,
                        potentialenergy=atoms.get_potential_energy())
thermo.get_helmholtz_energy(temperature=298.15)

# Crystal thermo.
atoms = bulk('Al', 'fcc', a=4.05)
calc = EMT()
atoms.set_calculator(calc)
energy = atoms.get_potential_energy()

# Phonon calculator
N = 7
ph = Phonons(atoms, calc, supercell=(N, N, N), delta=0.05)
ph.run()

ph.read(acoustic=True)
phonon_energies, phonon_DOS = ph.dos(kpts=(4, 4, 4), npts=30, delta=5e-4)

thermo = CrystalThermo(phonon_energies=phonon_energies,
                       phonon_DOS=phonon_DOS,
                       potentialenergy=energy,
                       formula_units=4)
thermo.get_helmholtz_energy(temperature=298.15)
Esempio n. 10
0
# High-symmetry points in the Brillouin zone
points = ibz_points['fcc']
G = points['Gamma']
X = points['X']
W = points['W']
K = points['K']
L = points['L']
U = points['U']

point_names = ['$\Gamma$', 'X', 'U', 'L', '$\Gamma$', 'K']
path = [G, X, U, L, G, K]
path_kc, q, Q = get_bandpath(path, atoms.cell, 100)
omega_kn = 1000 * ph.band_structure(path_kc)

# DOS
omega_e, dos_e = ph.dos(kpts=(50, 50, 50), npts=5000, delta=1e-4)
omega_e *= 1000

# Plot phonon dispersion
import matplotlib
#matplotlib.use('Agg')
import pylab as plt

plt.figure(1, (8, 6))
plt.axes([.1, .07, .67, .85])
for n in range(len(omega_kn[0])):
    omega_n = omega_kn[:, n]
    plt.plot(q, omega_n, 'k-', lw=2)

plt.xticks(Q, point_names, fontsize=18)
plt.yticks(fontsize=18)
Esempio n. 11
0
                 indices=[atom.index for atom in atoms
                          if atom.symbol != 'Cu'])
vib.run()
vib.summary()
vib_energies = vib.get_energies()

thermo = HarmonicThermo(vib_energies=vib_energies,
                        potentialenergy=atoms.get_potential_energy())
thermo.get_helmholtz_energy(temperature=298.15)

# Crystal thermo.
atoms = bulk('Al', 'fcc', a=4.05)
calc = EMT()
atoms.set_calculator(calc)
energy = atoms.get_potential_energy()

# Phonon calculator
N = 7
ph = Phonons(atoms, calc, supercell=(N, N, N), delta=0.05)
ph.run()

ph.read(acoustic=True)
phonon_energies, phonon_DOS = ph.dos(kpts=(4, 4, 4), npts=30,
                                     delta=5e-4)

thermo = CrystalThermo(phonon_energies=phonon_energies,
                       phonon_DOS=phonon_DOS,
                       potentialenergy=energy,
                       formula_units=4)
thermo.get_helmholtz_energy(temperature=298.15)