def get_qha(eos, temperatures, fe_phonon, cv, entropy, t_max=1000):

    from phonopy import PhonopyQHA
    import numpy as np

    phonopy_qha = PhonopyQHA(eos.get_array('volumes'),
                             eos.get_array('energies'),
                             eos="vinet",
                             temperatures=np.array(temperatures),
                             free_energy=np.array(fe_phonon).T,
                             cv=np.array(cv),
                             entropy=np.array(entropy),
                             t_max=t_max,
                             verbose=False)

    # testing
    if __testing__:
        import matplotlib.pyplot as plt
        plt = phonopy_qha.plot_qha()
        plt.show()

    qha_results = {'qha_temperatures': phonopy_qha._qha._temperatures[:phonopy_qha._qha._max_t_index],
                   'helmholtz_volume': phonopy_qha.get_helmholtz_volume(),
                   'thermal_expansion': phonopy_qha.get_thermal_expansion(),
                   'volume_temperature':  phonopy_qha.get_volume_temperature(),
                   'heat_capacity_P_numerical': phonopy_qha.get_heat_capacity_P_numerical(),
                   'volume_expansion': phonopy_qha.get_volume_expansion(),
                   'gibbs_temperature': phonopy_qha.get_gibbs_temperature()}

    return qha_results
class QuasiparticlesQHA():
    def __init__(self, args, load_data=False, verbose=False, tmin=None):

        input_parameters = reading.read_parameters_from_input_file(args.input_file)

        if 'structure_file_name_outcar' in input_parameters:
            structure = reading.read_from_file_structure_outcar(input_parameters['structure_file_name_outcar'])
        else:
            structure = reading.read_from_file_structure_poscar(input_parameters['structure_file_name_poscar'])

        structure.get_data_from_dict(input_parameters)

        if 'supercell_phonon' in input_parameters:
            supercell_phonon = input_parameters['supercell_phonon']
        else:
            supercell_phonon = np.identity(3)

        structure.set_force_constants(get_force_constants_from_file(file_name=input_parameters['force_constants_file_name'],
                                                                    fc_supercell=supercell_phonon))

        if '_mesh_phonopy' in input_parameters:
            mesh = input_parameters['_mesh_phonopy']
        else:
            mesh = [20, 20, 20] # Default
            print ('mesh set to: {}'.format(mesh))

        if 'bands' in input_parameters is None:
            self._bands =  structure.get_path_using_seek_path()
        else:
            self._bands = input_parameters['_band_ranges']

        volumes, energies = read_v_e(args.ev, factor=1.0, volume_factor=1.0, pressure=args.pressure)

        self._fc_fit = ForceConstantsFitting(structure,
                                       files_temperature=args.ct_data,
                                       files_volume=args.cv_data,
                                       temperatures=args.temperatures,
                                       volumes=volumes,
                                       mesh=mesh,
                                       ref_temperature=args.ref_temperature,
                                       fitting_order=args.order,
                                       tmin=tmin,
                                       use_NAC=True)

        if not load_data:
            temperatures = self._fc_fit.get_temperature_range()

            free_energy = []
            entropy = []
            cv = []
            for v, e in zip(volumes, energies):
                print ('Volume: {} Ang.      Energy(U): {} eV'.format(v, e))
                tp_data = self._fc_fit.get_thermal_properties(volume=v)
                free_energy.append(tp_data[0])
                entropy.append(tp_data[1])
                cv.append(tp_data[2])

            free_energy = np.array(free_energy).T
            entropy = np.array(entropy).T
            cv = np.array(cv).T

            np.save('free_energy.npy', free_energy)
            np.save('temperatures.npy', temperatures)
            np.save('cv.npy', cv)
            np.save('entropy.npy', entropy)
        else:
            free_energy = np.load('free_energy.npy')
            temperatures = np.load('temperatures.npy')
            cv = np.load('cv.npy')
            entropy = np.load('entropy.npy')

        self.phonopy_qha = PhonopyQHA(volumes,
                                 energies,
                                 eos="vinet",  # options: 'vinet', 'murnaghan' or 'birch_murnaghan'
                                 temperatures=temperatures,
                                 free_energy=free_energy,
                                 cv=cv,
                                 entropy=entropy,
                                 t_max=self.fc_fit.get_temperature_range()[-1],
                                 verbose=False)

        # Write data files to disk
        self.phonopy_qha.write_bulk_modulus_temperature()
        self.phonopy_qha.write_gibbs_temperature()
        self.phonopy_qha.write_heat_capacity_P_numerical()
        self.phonopy_qha.write_gruneisen_temperature()
        self.phonopy_qha.write_thermal_expansion()
        self.phonopy_qha.write_helmholtz_volume()
        self.phonopy_qha.write_volume_expansion()
        self.phonopy_qha.write_volume_temperature()

        if verbose:
            self.phonopy_qha.plot_qha().show()

    # Designed for test only
    def volume_shift(self, volume_range=np.arange(-2.0, 2.0, 0.1)):
        import matplotlib.pyplot as plt
        fig, ax = plt.subplots(1, 1)

        volumes = self.phonopy_qha._qha._volumes
        energies = self.phonopy_qha._qha._electronic_energies

        free_energy = np.load('free_energy.npy')
        temperatures = np.load('temperatures.npy')
        cv = np.load('cv.npy')
        entropy = np.load('entropy.npy')

        for i in volume_range:
            volumesi = np.array(volumes) + i
            print volumesi

            phonopy_qha = PhonopyQHA(volumesi,
                                     energies,
                                     eos="vinet",  # options: 'vinet', 'murnaghan' or 'birch_murnaghan'
                                     temperatures=temperatures,
                                     free_energy=free_energy,
                                     cv=cv,
                                     entropy=entropy,
                                     t_max=self.fc_fit.get_temperature_range()[-1],
                                     verbose=False)

            cp = phonopy_qha.get_heat_capacity_P_numerical()
            import matplotlib.pyplot as plt
            import matplotlib.colors as colors

            cNorm = colors.Normalize(vmin=volume_range[0], vmax=volume_range[-1])
            scalarMap = plt.cm.ScalarMappable(norm=cNorm, cmap=plt.cm.get_cmap('plasma'))
            ax.plot(phonopy_qha._qha._temperatures[:-3], cp, label='{}'.format(i), color=scalarMap.to_rgba(i))

        import matplotlib as mpl

        ax2 = fig.add_axes([0.93, 0.1, 0.02, 0.8])

        mpl.colorbar.ColorbarBase(ax2, cmap=plt.cm.get_cmap('plasma'), norm=cNorm,
                                  spacing='proportional', ticks=volume_range,
                                  boundaries=None, format='%1i')
        plt.show()

    def plot_dos_gradient(self):

        import matplotlib.pyplot as plt
        import matplotlib.colors as colors
        import matplotlib.colorbar as colorbar

        volumes = self.phonopy_qha.get_volume_temperature()
        temperatures = self.fc_fit.get_temperature_range()

        fig, ax = plt.subplots(1,1)
        for t, v in zip(temperatures[::40], volumes[::20]):
            print ('temperature: {} K'.format(t))
            dos = self.fc_fit.get_dos(t, v)
            cNorm = colors.Normalize(vmin=temperatures[0], vmax=temperatures[-1])
            scalarMap = plt.cm.ScalarMappable(norm=cNorm, cmap=plt.cm.get_cmap('plasma'))
            ax.plot(dos[0], dos[1], color=scalarMap.to_rgba(t))

        plt.suptitle('Phonon density of states')
        plt.xlabel('Frequency [THz]')

        ax2 = fig.add_axes([0.93, 0.1, 0.02, 0.8])
        colorbar.ColorbarBase(ax2, cmap=plt.cm.get_cmap('plasma'), norm=cNorm,
                              spacing='proportional', ticks=temperatures[::40],
                              boundaries=None, format='%1i')

        plt.show()

    def plot_band_structure_gradient(self, tmin=300, tmax=1600, tstep=100):

        import matplotlib.pyplot as plt
        import matplotlib.colors as colors
        import matplotlib.colorbar as colorbar

        def replace_list(text_string):
            substitutions = {'GAMMA': u'$\Gamma$',
                             }

            for item in substitutions.iteritems():
                text_string = text_string.replace(item[0], item[1])
            return text_string


        volumes = self.phonopy_qha.get_volume_temperature()
        cNorm = colors.Normalize(vmin=tmin, vmax=tmax)

        fig, ax = plt.subplots(1,1)
        for t in np.arange(tmin, tmax, tstep):
            print ('temperature: {} K'.format(t))
            v = self.get_volume_at_temperature(t)
            scalarMap = plt.cm.ScalarMappable(norm=cNorm, cmap=plt.cm.get_cmap('plasma'))
            band_data = self.fc_fit.get_band_structure(t, v, band_ranges=self._bands['ranges'])

            for i, freq in enumerate(band_data[1]):
                ax.plot(band_data[1][i], band_data[2][i], color=scalarMap.to_rgba(t))

                # plt.axes().get_xaxis().set_visible(False)


        #plt.axes().get_xaxis().set_ticks([])
        plt.ylabel('Frequency [THz]')
        plt.xlabel('Wave vector')

        plt.xlim([0, band_data[1][-1][-1]])
        plt.axhline(y=0, color='k', ls='dashed')
        plt.suptitle('Phonon dispersion')

        if 'labels' in self._bands:
            plt.rcParams.update({'mathtext.default': 'regular'})
            labels = self._bands['labels']

            labels_e = []
            x_labels = []
            for i in range(len(band_data[1])):
                if labels[i][0] == labels[i - 1][1]:
                    labels_e.append(replace_list(labels[i][0]))
                else:
                    labels_e.append(
                        replace_list(labels[i - 1][1]) + '/' + replace_list(labels[i][0]))
                x_labels.append(band_data[1][i][0])
            x_labels.append(band_data[1][-1][-1])
            labels_e.append(replace_list(labels[-1][1]))
            labels_e[0] = replace_list(labels[0][0])
            plt.xticks(x_labels, labels_e, rotation='horizontal')

        ax2 = fig.add_axes([0.93, 0.1, 0.02, 0.8])
        colorbar.ColorbarBase(ax2, cmap=plt.cm.get_cmap('plasma'), norm=cNorm,
                              spacing='proportional', ticks=np.arange(tmin, tmax, tstep),
                              boundaries=None, format='%1i')

        plt.show()

    def get_volume_at_temperature(self, temperature):

        temperatures = self.get_qha_temperatures()
        volumes = self.phonopy_qha.get_volume_temperature()
        volume = np.interp(temperature, temperatures, volumes)

        return volume

    def plot_band_structure_constant_pressure(self, temperature=300, external_data=None):

        import matplotlib.pyplot as plt

        def replace_list(text_string):
            substitutions = {'GAMMA': u'$\Gamma$',
                             }

            for item in substitutions.iteritems():
                text_string = text_string.replace(item[0], item[1])
            return text_string

        volume = self.get_volume_at_temperature(temperature)
        fig, ax = plt.subplots(1,1)
        band_data = self.fc_fit.get_band_structure(temperature, volume, band_ranges=self._bands['ranges'])

        for i, freq in enumerate(band_data[1]):
            ax.plot(band_data[1][i], band_data[2][i], color='r')

        #plt.axes().get_xaxis().set_ticks([])
        plt.ylabel('Frequency [THz]')
        plt.xlabel('Wave vector')

        plt.xlim([0, band_data[1][-1][-1]])
        plt.axhline(y=0, color='k', ls='dashed')
        plt.suptitle('Phonon dispersion')

        if 'labels' in self._bands:
            plt.rcParams.update({'mathtext.default': 'regular'})
            labels = self._bands['labels']

            labels_e = []
            x_labels = []
            for i in range(len(band_data[1])):
                if labels[i][0] == labels[i - 1][1]:
                    labels_e.append(replace_list(labels[i][0]))
                else:
                    labels_e.append(
                        replace_list(labels[i - 1][1]) + '/' + replace_list(labels[i][0]))
                x_labels.append(band_data[1][i][0])
            x_labels.append(band_data[1][-1][-1])
            labels_e.append(replace_list(labels[-1][1]))
            labels_e[0] = replace_list(labels[0][0])
            plt.xticks(x_labels, labels_e, rotation='horizontal')

        ax.plot(external_data[:, 0], external_data[:, 1], 'o', color='b')
        plt.show()

    def get_qha_temperatures(self):
        max_t_index = self.phonopy_qha._qha._get_max_t_index(self.phonopy_qha._qha._temperatures)
        temperatures = self.phonopy_qha._qha._temperatures[:max_t_index]

        return temperatures

    def get_FC_constant_pressure(self):
        temperatures = self.get_qha_temperatures()
        volumes = self.phonopy_qha.get_volume_temperature()

        for t, v in zip(temperatures[::20], volumes[::20]):
            fc = self.fc_fit.get_total_force_constants(temperature=t, volume=v)
            write_FORCE_CONSTANTS(fc.get_array(), filename='FC_{}'.format(t))

    def get_total_shift_constant_pressure(self, qpoint=(0, 0, 0)):

        qindex = self.fc_fit.qpoint_to_index(qpoint)

        volumes = self.phonopy_qha.get_volume_temperature()
        temperatures = self.get_qha_temperatures()
        h_frequencies, ev = self.fc_fit.get_harmonic_frequencies_and_eigenvectors()

        chk_shift_matrix = []
        for v, t in zip(volumes, temperatures):
            total_shifts = self.fc_fit.get_total_shifts(volume=v, temperature=t)

            chk_shift_matrix.append(total_shifts)
        chk_shift_matrix = np.array(chk_shift_matrix).T

        return chk_shift_matrix[:, qindex]

    def plot_total_shift_constant_pressure(self, qpoint=(0, 0, 0), branch=None):

        import matplotlib.pyplot as plt

        temperatures = self.get_qha_temperatures()
        chk_shift_matrix = self.get_total_shift_constant_pressure(qpoint=qpoint)

        plt.suptitle('Total frequency shift at wave vector={} (relative to {} K)'.format(qpoint, self.fc_fit.ref_temperature))
        plt.xlabel('Temperature [K]')
        plt.ylabel('Frequency shift [THz]')
        if branch is None:
            plt.plot(temperatures, chk_shift_matrix.T, '-')
        else:
            plt.title('Branch {}'.format(branch))
            plt.plot(temperatures, chk_shift_matrix[branch].T, '-')
        plt.show()

    @property
    def fc_fit(self):
        return self._fc_fit
class QuasiparticlesQHA():
    def __init__(self, args, load_data=False, verbose=False, tmin=None):

        input_parameters = reading.read_parameters_from_input_file(
            args.input_file)

        if 'structure_file_name_outcar' in input_parameters:
            structure = reading.read_from_file_structure_outcar(
                input_parameters['structure_file_name_outcar'])
        else:
            structure = reading.read_from_file_structure_poscar(
                input_parameters['structure_file_name_poscar'])

        structure.get_data_from_dict(input_parameters)

        if 'supercell_phonon' in input_parameters:
            supercell_phonon = input_parameters['supercell_phonon']
        else:
            supercell_phonon = np.identity(3)

        structure.set_force_constants(
            get_force_constants_from_file(
                file_name=input_parameters['force_constants_file_name'],
                fc_supercell=supercell_phonon))

        if '_mesh_phonopy' in input_parameters:
            mesh = input_parameters['_mesh_phonopy']
        else:
            mesh = [20, 20, 20]  # Default
            print('mesh set to: {}'.format(mesh))

        if 'bands' in input_parameters is None:
            self._bands = structure.get_path_using_seek_path()
        else:
            self._bands = input_parameters['_band_ranges']

        volumes, energies = read_v_e(args.ev,
                                     factor=1.0,
                                     volume_factor=1.0,
                                     pressure=args.pressure)

        self._fc_fit = ForceConstantsFitting(
            structure,
            files_temperature=args.ct_data,
            files_volume=args.cv_data,
            temperatures=args.temperatures,
            volumes=volumes,
            mesh=mesh,
            ref_temperature=args.ref_temperature,
            fitting_order=args.order,
            tmin=tmin,
            use_NAC=True)

        if not load_data:
            temperatures = self._fc_fit.get_temperature_range()

            free_energy = []
            entropy = []
            cv = []
            for v, e in zip(volumes, energies):
                print('Volume: {} Ang.      Energy(U): {} eV'.format(v, e))
                tp_data = self._fc_fit.get_thermal_properties(volume=v)
                free_energy.append(tp_data[0])
                entropy.append(tp_data[1])
                cv.append(tp_data[2])

            free_energy = np.array(free_energy).T
            entropy = np.array(entropy).T
            cv = np.array(cv).T

            np.save('free_energy.npy', free_energy)
            np.save('temperatures.npy', temperatures)
            np.save('cv.npy', cv)
            np.save('entropy.npy', entropy)
        else:
            free_energy = np.load('free_energy.npy')
            temperatures = np.load('temperatures.npy')
            cv = np.load('cv.npy')
            entropy = np.load('entropy.npy')

        self.phonopy_qha = PhonopyQHA(
            volumes,
            energies,
            eos="vinet",  # options: 'vinet', 'murnaghan' or 'birch_murnaghan'
            temperatures=temperatures,
            free_energy=free_energy,
            cv=cv,
            entropy=entropy,
            t_max=self.fc_fit.get_temperature_range()[-1],
            verbose=False)

        # Write data files to disk
        self.phonopy_qha.write_bulk_modulus_temperature()
        self.phonopy_qha.write_gibbs_temperature()
        self.phonopy_qha.write_heat_capacity_P_numerical()
        self.phonopy_qha.write_gruneisen_temperature()
        self.phonopy_qha.write_thermal_expansion()
        self.phonopy_qha.write_helmholtz_volume()
        self.phonopy_qha.write_volume_expansion()
        self.phonopy_qha.write_volume_temperature()

        if verbose:
            self.phonopy_qha.plot_qha().show()

    # Designed for test only
    def volume_shift(self, volume_range=np.arange(-2.0, 2.0, 0.1)):
        import matplotlib.pyplot as plt
        fig, ax = plt.subplots(1, 1)

        volumes = self.phonopy_qha._qha._volumes
        energies = self.phonopy_qha._qha._electronic_energies

        free_energy = np.load('free_energy.npy')
        temperatures = np.load('temperatures.npy')
        cv = np.load('cv.npy')
        entropy = np.load('entropy.npy')

        for i in volume_range:
            volumesi = np.array(volumes) + i
            print volumesi

            phonopy_qha = PhonopyQHA(
                volumesi,
                energies,
                eos=
                "vinet",  # options: 'vinet', 'murnaghan' or 'birch_murnaghan'
                temperatures=temperatures,
                free_energy=free_energy,
                cv=cv,
                entropy=entropy,
                t_max=self.fc_fit.get_temperature_range()[-1],
                verbose=False)

            cp = phonopy_qha.get_heat_capacity_P_numerical()
            import matplotlib.pyplot as plt
            import matplotlib.colors as colors

            cNorm = colors.Normalize(vmin=volume_range[0],
                                     vmax=volume_range[-1])
            scalarMap = plt.cm.ScalarMappable(norm=cNorm,
                                              cmap=plt.cm.get_cmap('plasma'))
            ax.plot(phonopy_qha._qha._temperatures[:-3],
                    cp,
                    label='{}'.format(i),
                    color=scalarMap.to_rgba(i))

        import matplotlib as mpl

        ax2 = fig.add_axes([0.93, 0.1, 0.02, 0.8])

        mpl.colorbar.ColorbarBase(ax2,
                                  cmap=plt.cm.get_cmap('plasma'),
                                  norm=cNorm,
                                  spacing='proportional',
                                  ticks=volume_range,
                                  boundaries=None,
                                  format='%1i')
        plt.show()

    def plot_dos_gradient(self):

        import matplotlib.pyplot as plt
        import matplotlib.colors as colors
        import matplotlib.colorbar as colorbar

        volumes = self.phonopy_qha.get_volume_temperature()
        temperatures = self.fc_fit.get_temperature_range()

        fig, ax = plt.subplots(1, 1)
        for t, v in zip(temperatures[::40], volumes[::20]):
            print('temperature: {} K'.format(t))
            dos = self.fc_fit.get_dos(t, v)
            cNorm = colors.Normalize(vmin=temperatures[0],
                                     vmax=temperatures[-1])
            scalarMap = plt.cm.ScalarMappable(norm=cNorm,
                                              cmap=plt.cm.get_cmap('plasma'))
            ax.plot(dos[0], dos[1], color=scalarMap.to_rgba(t))

        plt.suptitle('Phonon density of states')
        plt.xlabel('Frequency [THz]')

        ax2 = fig.add_axes([0.93, 0.1, 0.02, 0.8])
        colorbar.ColorbarBase(ax2,
                              cmap=plt.cm.get_cmap('plasma'),
                              norm=cNorm,
                              spacing='proportional',
                              ticks=temperatures[::40],
                              boundaries=None,
                              format='%1i')

        plt.show()

    def plot_band_structure_gradient(self, tmin=300, tmax=1600, tstep=100):

        import matplotlib.pyplot as plt
        import matplotlib.colors as colors
        import matplotlib.colorbar as colorbar

        def replace_list(text_string):
            substitutions = {
                'GAMMA': u'$\Gamma$',
            }

            for item in substitutions.iteritems():
                text_string = text_string.replace(item[0], item[1])
            return text_string

        volumes = self.phonopy_qha.get_volume_temperature()
        cNorm = colors.Normalize(vmin=tmin, vmax=tmax)

        fig, ax = plt.subplots(1, 1)
        for t in np.arange(tmin, tmax, tstep):
            print('temperature: {} K'.format(t))
            v = self.get_volume_at_temperature(t)
            scalarMap = plt.cm.ScalarMappable(norm=cNorm,
                                              cmap=plt.cm.get_cmap('plasma'))
            band_data = self.fc_fit.get_band_structure(
                t, v, band_ranges=self._bands['ranges'])

            for i, freq in enumerate(band_data[1]):
                ax.plot(band_data[1][i],
                        band_data[2][i],
                        color=scalarMap.to_rgba(t))

                # plt.axes().get_xaxis().set_visible(False)

        #plt.axes().get_xaxis().set_ticks([])
        plt.ylabel('Frequency [THz]')
        plt.xlabel('Wave vector')

        plt.xlim([0, band_data[1][-1][-1]])
        plt.axhline(y=0, color='k', ls='dashed')
        plt.suptitle('Phonon dispersion')

        if 'labels' in self._bands:
            plt.rcParams.update({'mathtext.default': 'regular'})
            labels = self._bands['labels']

            labels_e = []
            x_labels = []
            for i in range(len(band_data[1])):
                if labels[i][0] == labels[i - 1][1]:
                    labels_e.append(replace_list(labels[i][0]))
                else:
                    labels_e.append(
                        replace_list(labels[i - 1][1]) + '/' +
                        replace_list(labels[i][0]))
                x_labels.append(band_data[1][i][0])
            x_labels.append(band_data[1][-1][-1])
            labels_e.append(replace_list(labels[-1][1]))
            labels_e[0] = replace_list(labels[0][0])
            plt.xticks(x_labels, labels_e, rotation='horizontal')

        ax2 = fig.add_axes([0.93, 0.1, 0.02, 0.8])
        colorbar.ColorbarBase(ax2,
                              cmap=plt.cm.get_cmap('plasma'),
                              norm=cNorm,
                              spacing='proportional',
                              ticks=np.arange(tmin, tmax, tstep),
                              boundaries=None,
                              format='%1i')

        plt.show()

    def get_volume_at_temperature(self, temperature):

        temperatures = self.get_qha_temperatures()
        volumes = self.phonopy_qha.get_volume_temperature()
        volume = np.interp(temperature, temperatures, volumes)

        return volume

    def plot_band_structure_constant_pressure(self,
                                              temperature=300,
                                              external_data=None):

        import matplotlib.pyplot as plt

        def replace_list(text_string):
            substitutions = {
                'GAMMA': u'$\Gamma$',
            }

            for item in substitutions.iteritems():
                text_string = text_string.replace(item[0], item[1])
            return text_string

        volume = self.get_volume_at_temperature(temperature)
        fig, ax = plt.subplots(1, 1)
        band_data = self.fc_fit.get_band_structure(
            temperature, volume, band_ranges=self._bands['ranges'])

        for i, freq in enumerate(band_data[1]):
            ax.plot(band_data[1][i], band_data[2][i], color='r')

        #plt.axes().get_xaxis().set_ticks([])
        plt.ylabel('Frequency [THz]')
        plt.xlabel('Wave vector')

        plt.xlim([0, band_data[1][-1][-1]])
        plt.axhline(y=0, color='k', ls='dashed')
        plt.suptitle('Phonon dispersion')

        if 'labels' in self._bands:
            plt.rcParams.update({'mathtext.default': 'regular'})
            labels = self._bands['labels']

            labels_e = []
            x_labels = []
            for i in range(len(band_data[1])):
                if labels[i][0] == labels[i - 1][1]:
                    labels_e.append(replace_list(labels[i][0]))
                else:
                    labels_e.append(
                        replace_list(labels[i - 1][1]) + '/' +
                        replace_list(labels[i][0]))
                x_labels.append(band_data[1][i][0])
            x_labels.append(band_data[1][-1][-1])
            labels_e.append(replace_list(labels[-1][1]))
            labels_e[0] = replace_list(labels[0][0])
            plt.xticks(x_labels, labels_e, rotation='horizontal')

        ax.plot(external_data[:, 0], external_data[:, 1], 'o', color='b')
        plt.show()

    def get_qha_temperatures(self):
        max_t_index = self.phonopy_qha._qha._get_max_t_index(
            self.phonopy_qha._qha._temperatures)
        temperatures = self.phonopy_qha._qha._temperatures[:max_t_index]

        return temperatures

    def get_FC_constant_pressure(self):
        temperatures = self.get_qha_temperatures()
        volumes = self.phonopy_qha.get_volume_temperature()

        for t, v in zip(temperatures[::20], volumes[::20]):
            fc = self.fc_fit.get_total_force_constants(temperature=t, volume=v)
            write_FORCE_CONSTANTS(fc.get_array(), filename='FC_{}'.format(t))

    def get_total_shift_constant_pressure(self, qpoint=(0, 0, 0)):

        qindex = self.fc_fit.qpoint_to_index(qpoint)

        volumes = self.phonopy_qha.get_volume_temperature()
        temperatures = self.get_qha_temperatures()
        h_frequencies, ev = self.fc_fit.get_harmonic_frequencies_and_eigenvectors(
        )

        chk_shift_matrix = []
        for v, t in zip(volumes, temperatures):
            total_shifts = self.fc_fit.get_total_shifts(volume=v,
                                                        temperature=t)

            chk_shift_matrix.append(total_shifts)
        chk_shift_matrix = np.array(chk_shift_matrix).T

        return chk_shift_matrix[:, qindex]

    def plot_total_shift_constant_pressure(self,
                                           qpoint=(0, 0, 0),
                                           branch=None):

        import matplotlib.pyplot as plt

        temperatures = self.get_qha_temperatures()
        chk_shift_matrix = self.get_total_shift_constant_pressure(
            qpoint=qpoint)

        plt.suptitle(
            'Total frequency shift at wave vector={} (relative to {} K)'.
            format(qpoint, self.fc_fit.ref_temperature))
        plt.xlabel('Temperature [K]')
        plt.ylabel('Frequency shift [THz]')
        if branch is None:
            plt.plot(temperatures, chk_shift_matrix.T, '-')
        else:
            plt.title('Branch {}'.format(branch))
            plt.plot(temperatures, chk_shift_matrix[branch].T, '-')
        plt.show()

    @property
    def fc_fit(self):
        return self._fc_fit
Exemple #4
0
    verbose=False)

# Get data
qha_temperatures = phonopy_qha._qha._temperatures[:phonopy_qha._qha.
                                                  _max_t_index]
helmholtz_volume = phonopy_qha.get_helmholtz_volume()
thermal_expansion = phonopy_qha.get_thermal_expansion()
volume_temperature = phonopy_qha.get_volume_temperature()
heat_capacity_P_numerical = phonopy_qha.get_heat_capacity_P_numerical()
volume_expansion = phonopy_qha.get_volume_expansion()
gibbs_temperature = phonopy_qha.get_gibbs_temperature()

#phonopy_qha.plot_bulk_modulus()
#plt.show()

phonopy_qha.plot_qha()
plt.show()
phonopy_qha.plot_gruneisen_temperature()
plt.show()
phonopy_qha.plot_gibbs_temperature()
plt.show()
phonopy_qha.plot_heat_capacity_P_numerical()
plt.show()

phonopy_qha.write_gibbs_temperature()
phonopy_qha.write_heat_capacity_P_numerical()

qha_output = ArrayData()
qha_output.set_array('temperature', np.array(qha_temperatures))
qha_output.set_array('helmholtz_volume', np.array(helmholtz_volume))
qha_output.set_array('thermal_expansion', np.array(thermal_expansion))