Example #1
0
def check_symmetry(input_cell,
                   primitive_axis=None,
                   symprec=1e-5,
                   distance_to_A=1.0,
                   phonopy_version=None):
    if primitive_axis is None:
        cell = get_primitive(input_cell, np.eye(3), symprec=symprec)
    else:
        cell = get_primitive(input_cell, primitive_axis, symprec=symprec)
    lattice = cell.get_cell() * distance_to_A
    cell.set_cell(lattice)

    symmetry = Symmetry(cell, symprec)
    print(_get_symmetry_yaml(cell, symmetry, phonopy_version))

    if input_cell.get_magnetic_moments() is None:
        primitive = find_primitive(cell, symprec)
        if primitive is not None:
            print("# Primitive cell was found. It is written into PPOSCAR.")
            write_vasp('PPOSCAR', primitive)

            # Overwrite symmetry and cell
            symmetry = Symmetry(primitive, symprec)
            cell = primitive

        (bravais_lattice,
         bravais_pos,
         bravais_numbers) = spg.refine_cell(cell, symprec)
        bravais = Atoms(numbers=bravais_numbers,
                        scaled_positions=bravais_pos,
                        cell=bravais_lattice,
                        pbc=True)
        print("# Bravais lattice is written into BPOSCAR.")
        write_vasp('BPOSCAR', bravais)
Example #2
0
def check_symmetry(input_cell,
                   primitive_axis=np.eye(3, dtype=float),
                   symprec=1e-5,
                   phonopy_version=None):

    cell = Primitive(input_cell, primitive_axis, symprec)

    symmetry = Symmetry(cell, symprec)
    print get_symmetry_yaml(cell, symmetry, phonopy_version),

    if input_cell.get_magnetic_moments() == None:
        primitive = find_primitive(cell, symprec)
        if not primitive == None:
            print "# Primitive cell was found. It is written into PPOSCAR."
            write_vasp('PPOSCAR', primitive)

            # Overwrite symmetry and cell
            symmetry = Symmetry(primitive, symprec)
            cell = primitive

        bravais_lattice, bravais_pos, bravais_numbers = \
            spg.refine_cell(cell, symprec)
        bravais = Atoms(numbers=bravais_numbers,
                        scaled_positions=bravais_pos,
                        cell=bravais_lattice,
                        pbc=True)
        print "# Bravais lattice is written into BPOSCAR."
        write_vasp('BPOSCAR', bravais)
Example #3
0
def write_crystal_structure(filename,
                            cell,
                            interface_mode=None,
                            optional_structure_info=None):
    """Utility method to write out a crystal structure

    filename : str, optional
        File name to be used to write out the crystal structure.
    cell : PhonopyAtoms
        Crystal structure
    interface_mode : str, optional
        Calculator interface such as 'vasp', 'qe', ... Default is None,
        that is equivalent to 'vasp'.
    optional_structure_info : tuple, optional
        Information returned by the method ``read_crystal_structure``.
        See the docstring. Default is None.

    """

    if interface_mode is None or interface_mode == 'vasp':
        import phonopy.interface.vasp as vasp
        vasp.write_vasp(filename, cell)
    elif interface_mode == 'abinit':
        import phonopy.interface.abinit as abinit
        abinit.write_abinit(filename, cell)
    elif interface_mode == 'qe':
        import phonopy.interface.qe as qe
        pp_filenames = optional_structure_info[1]
        qe.write_pwscf(filename, cell, pp_filenames)
    elif interface_mode == 'wien2k':
        import phonopy.interface.wien2k as wien2k
        _, npts, r0s, rmts = optional_structure_info
        wien2k.write_wein2k(filename, cell, npts, r0s, rmts)
    elif interface_mode == 'elk':
        import phonopy.interface.elk as elk
        sp_filenames = optional_structure_info[1]
        elk.write_elk(filename, cell, sp_filenames)
    elif interface_mode == 'siesta':
        import phonopy.interface.siesta as siesta
        atypes = optional_structure_info[1]
        siesta.write_siesta(filename, cell, atypes)
    elif interface_mode == 'cp2k':
        import phonopy.interface.cp2k as cp2k
        _, tree = optional_structure_info
        cp2k.write_cp2k_by_filename(filename, cell, tree)
    elif interface_mode == 'crystal':
        import phonopy.interface.crystal as crystal
        conv_numbers = optional_structure_info[1]
        crystal.write_crystal(filename, cell, conv_numbers)
    elif interface_mode == 'dftbp':
        import phonopy.interface.dftbp as dftbp
        dftbp.write_dftbp(filename, cell)
    elif interface_mode == 'turbomole':
        import phonopy.interface.turbomole as turbomole
        turbomole.write_turbomole(filename, cell)
    elif interface_mode == 'aims':
        import phonopy.interface.aims as aims
        aims.write_aims(filename, cell)
    else:
        raise RuntimeError("No calculator interface was found.")
def convert_phonopy_atoms_to_structure(phonopy_atoms_structure):
    """
	Converts phonopy's representation of a structure to an instance of Structure.
	"""

    temporary_write_path = Path.get_temporary_path()

    Path.validate_does_not_exist(temporary_write_path)
    Path.validate_writeable(temporary_write_path)

    write_vasp(temporary_write_path, phonopy_atoms_structure)

    species_list = convert_phonopy_symbols_to_unique_species_list(
        phonopy_atoms_structure.symbols)

    structure_poscar_file = File(temporary_write_path)
    structure_poscar_file.insert(
        5, " ".join(species_list))  #phonopy uses bad poscar format
    structure_poscar_file.write_to_path()

    final_structure = Structure(temporary_write_path)

    Path.remove(temporary_write_path)

    Structure.validate(final_structure)

    return final_structure
Example #5
0
def check_symmetry(input_cell,
                   primitive_axis=None,
                   symprec=1e-5,
                   distance_to_A=1.0,
                   phonopy_version=None):
    if primitive_axis is None:
        cell = get_primitive(input_cell, np.eye(3), symprec=symprec)
    else:
        cell = get_primitive(input_cell, primitive_axis, symprec=symprec)
    lattice = cell.get_cell() * distance_to_A
    cell.set_cell(lattice)

    symmetry = Symmetry(cell, symprec)
    print(_get_symmetry_yaml(cell, symmetry, phonopy_version))

    if input_cell.get_magnetic_moments() is None:
        primitive = find_primitive(cell, symprec)
        if primitive is not None:
            print("# Primitive cell was found. It is written into PPOSCAR.")
            write_vasp('PPOSCAR', primitive)

            # Overwrite symmetry and cell
            symmetry = Symmetry(primitive, symprec)
            cell = primitive

        (bravais_lattice, bravais_pos,
         bravais_numbers) = spg.refine_cell(cell, symprec)
        bravais = Atoms(numbers=bravais_numbers,
                        scaled_positions=bravais_pos,
                        cell=bravais_lattice,
                        pbc=True)
        print("# Bravais lattice is written into BPOSCAR.")
        write_vasp('BPOSCAR', bravais)
Example #6
0
def check_symmetry(input_cell,
                   primitive_axis=None,
                   symprec=1e-5,
                   phonopy_version=None):
    if primitive_axis is None:
        cell = get_primitive(input_cell, np.eye(3), symprec=symprec)
    else:
        cell = get_primitive(input_cell, primitive_axis, symprec=symprec)
    symmetry = Symmetry(cell, symprec)
    print get_symmetry_yaml(cell, symmetry, phonopy_version),

    if input_cell.get_magnetic_moments() == None:
        primitive = find_primitive(cell, symprec)
        if not primitive==None:
            print "# Primitive cell was found. It is written into PPOSCAR."
            write_vasp('PPOSCAR', primitive)
            
            # Overwrite symmetry and cell
            symmetry = Symmetry(primitive, symprec)
            cell = primitive
    
        bravais_lattice, bravais_pos, bravais_numbers = \
            spg.refine_cell(cell, symprec)
        bravais = Atoms(numbers=bravais_numbers,
                        scaled_positions=bravais_pos,
                        cell=bravais_lattice,
                        pbc=True)
        print "# Bravais lattice is written into BPOSCAR."
        write_vasp('BPOSCAR', bravais)
Example #7
0
 def write_POSCAR( self, band_index, amplitude=1, num_div=20,
                   filename="APOSCAR" ):
     self.__set_displacements( band_index - 1 )
     for i in range( num_div ):
         positions = np.dot( self.positions, self.lattice ) \
             + ( self.displacements * np.exp( 2j * np.pi / num_div * i ) ).imag * amplitude
         atoms = Atoms( cell=self.lattice,
                        positions=positions,
                        masses=self.masses,
                        symbols=self.symbols,
                        pbc=True )
         write_vasp( ( filename+"-%03d" ) % i, atoms, direct=True )
Example #8
0
 def write_POSCAR(self,
                  band_index,
                  amplitude=1,
                  num_div=20,
                  filename="APOSCAR"):
     self._set_displacements(band_index - 1)
     for i in range(num_div):
         positions = np.dot(self._positions, self._lattice) \
             + (self._displacements * np.exp(2j * np.pi / num_div * i)).imag * amplitude
         atoms = Atoms(cell=self._lattice,
                       positions=positions,
                       masses=self._masses,
                       symbols=self._symbols,
                       pbc=True)
         write_vasp((filename + "-%03d") % i, atoms, direct=True)
Example #9
0
 def next(self):
     print "The %dth iteration in finding the equilibrium position"%(self._step + 1)
     self.set_disp_and_forces()
     self.distribute_fc2()
     self.show_residual_forces_fc2()
     print_irred_fc2(self._fc._pairs_reduced, self._fc._ifc2_ele, self.irred_fc2)
     self._step += 1
     if self._converge2:
         print "Equilibrium position found. "
         raise StopIteration
     elif self._step == self._count:
         print "Iteration terminated due to the counting limit"
         raise StopIteration
     else:
         self.predict_new_positions()
         cell = deepcopy(self.supercell)
         cell.set_positions(self._pos_equi)
         write_vasp("POSCAR_FC2", cell, direct=False)
Example #10
0
    def write_POSCAR(self, band_index, amplitude=1, num_div=20, filename="APOSCAR"):
        """Write snapshots to files in VASP POSCAR format."""
        self._set_displacements(band_index - 1)
        for i in range(num_div):
            positions = (
                np.dot(self._positions, self._lattice)
                + (self._displacements * np.exp(2j * np.pi / num_div * i)).imag
                * amplitude
            )
            atoms = PhonopyAtoms(
                cell=self._lattice,
                positions=positions,
                masses=self._masses,
                symbols=self._symbols,
                pbc=True,
            )
            write_vasp((filename + "-%03d") % i, atoms, direct=True)

        return filename
Example #11
0
 def next(self):
     print "The %dth iteration in finding the equilibrium position" % (
         self._step + 1)
     self.set_disp_and_forces()
     self.distribute_fc2()
     self.show_residual_forces_fc2()
     print_irred_fc2(self._fc._pairs_reduced, self._fc._ifc2_ele,
                     self.irred_fc2)
     self._step += 1
     if self._converge2:
         print "Equilibrium position found. "
         raise StopIteration
     elif self._step == self._count:
         print "Iteration terminated due to the counting limit"
         raise StopIteration
     else:
         self.predict_new_positions()
         cell = deepcopy(self.supercell)
         cell.set_positions(self._pos_equi)
         write_vasp("POSCAR_FC2", cell, direct=False)
Example #12
0
def write_Supercells_VASP(Supercells, directory='./', prefix='POSCAR'):
    #print(directory)
    if directory != './':
        if os.path.exists(directory):
            shutil.rmtree(directory)
        os.mkdir(directory)

    if type(Supercells) != list:
        Supercells = [Supercells]

    NSnaps = len(Supercells)
    str_NSnaps = str(NSnaps)
    for isnap, supercell in enumerate(Supercells):
        str_isnap = str(isnap + 1)
        index_len = np.max([3, len(str_NSnaps)])
        Nzero = index_len - len(str_isnap)
        index = ''
        for iz in range(Nzero):
            index += '0'
        index += str_isnap
        phonVasp.write_vasp(prefix + '-' + index, supercell)
        if directory != './':
            shutil.move(prefix + '-' + index, directory)
Example #13
0
 def write(self, filename="MPOSCAR"):
     deltas = []
     for i, delta_positions in enumerate(self._delta_modulations):
         cell = self._get_cell_with_modulation(delta_positions)
         write_vasp((filename+"-%03d") % (i+1), cell, direct=True)
         deltas.append(delta_positions)
 
     sum_of_deltas = np.sum(deltas, axis=0)
     cell = self._get_cell_with_modulation(sum_of_deltas)
     write_vasp(filename, cell, direct=True)
     no_modulations = np.zeros(sum_of_deltas.shape, dtype=complex)
     cell = self._get_cell_with_modulation(no_modulations)
     write_vasp(filename+"-orig", cell, direct=True)
Example #14
0
    def write(self, filename="MPOSCAR"):
        deltas = []
        for i, u in enumerate(self._u):
            cell = self._get_cell_with_modulation(u)
            write_vasp((filename + "-%03d") % (i + 1), cell, direct=True)
            deltas.append(u)

        sum_of_deltas = np.sum(deltas, axis=0)
        cell = self._get_cell_with_modulation(sum_of_deltas)
        write_vasp(filename, cell, direct=True)
        no_modulations = np.zeros(sum_of_deltas.shape, dtype=complex)
        cell = self._get_cell_with_modulation(no_modulations)
        write_vasp(filename + "-orig", cell, direct=True)
Example #15
0
def write_modulations( dynamical_matrix,
                       primitive,
                       setting,
                       filename="MPOSCAR" ):
    """
    write_modulations:
      ``setting`` is given as sets of band index and amplitude.
      For example:
      setting['q'] = [ 0, 0, 0 ]
      setting['dimension'] = [ 1, 1, 1 ]
      setting['modulations'] = [ [ 1, 2 ], [2, 2.5 ] ]
    """
    
    dimension = setting['dimension']
    argument = setting['argument']
    q = setting['q']
    dm = dynamical_matrix
    dm.set_dynamical_matrix( q )
    eig, eigvec = np.linalg.eigh( dm.get_dynamical_matrix() )
    modulations = []

    for i, ( band_index, amplitude ) in enumerate( setting['modulations'] ):
        modulation = get_modulation( band_index - 1,
                                     eigvec,
                                     primitive,
                                     q,
                                     dimension ) * amplitude 
        cell = get_cell_with_modulation( modulation, primitive, dimension, argument )
        write_vasp( ( filename+"-%03d" ) % (i+1), cell, direct=True )
        
        modulations.append( modulation )

    sum_of_modulations = np.sum( modulations, axis=0 )
    cell = get_cell_with_modulation( sum_of_modulations, primitive, dimension, argument )
    write_vasp( filename, cell, direct=True )

    no_modulations = np.zeros( sum_of_modulations.shape, dtype=complex )
    cell = get_cell_with_modulation( no_modulations, primitive, dimension, argument )
    write_vasp( filename+"-orig", cell, direct=True )
Example #16
0
def create_phono3py_supercells(unitcell,
                               supercell_matrix,
                               phonon_supercell_matrix,
                               output_filename,
                               symprec,
                               settings,
                               log_level):
    if settings.get_displacement_distance() is None:
        displacement_distance = 0.03
    else:
        displacement_distance = settings.get_displacement_distance()
    cutoff_pair_distance = settings.get_cutoff_pair_distance()
    phono3py = Phono3py(
        unitcell,
        supercell_matrix,
        phonon_supercell_matrix=phonon_supercell_matrix,
        symprec=symprec)
    supercell = phono3py.get_supercell()
    phono3py.generate_displacements(
        distance=displacement_distance,
        cutoff_pair_distance=cutoff_pair_distance,
        is_plusminus=settings.get_is_plusminus_displacement(),
        is_diagonal=settings.get_is_diagonal_displacement())
    dds = phono3py.get_displacement_dataset()
    
    if log_level:
        print('')
        print("Displacement distance: %s" % displacement_distance)

    if output_filename is None:
        filename = 'disp_fc3.yaml'
    else:
        filename = 'disp_fc3.' + output_filename + '.yaml'
        
    num_disps, num_disp_files = write_disp_fc3_yaml(dds,
                                                    supercell,
                                                    filename=filename)
    for i, dcell in enumerate(phono3py.get_supercells_with_displacements()):
        if dcell is not None:
            write_vasp('POSCAR-%05d' % (i + 1), dcell, direct=True)

    if log_level:
        print("Number of displacements: %d" % num_disps)
        if cutoff_pair_distance is not None:
            print("Cutoff distance for displacements: %s" %
                  cutoff_pair_distance)
            print("Number of displacement supercell files created: %d" %
                  num_disp_files)
            
    if phonon_supercell_matrix is not None:
        phonon_dds = phono3py.get_phonon_displacement_dataset()
        phonon_supercell = phono3py.get_phonon_supercell()
        if output_filename is None:
            filename = 'disp_fc2.yaml'
        else:
            filename = 'disp_fc2.' + output_filename + '.yaml'
            
        num_disps = write_disp_fc2_yaml(phonon_dds,
                                        phonon_supercell,
                                        filename=filename)
        for i, dcell in enumerate(
                phono3py.get_phonon_supercells_with_displacements()):
            write_vasp('POSCAR_FC2-%05d' % (i + 1), dcell, direct=True)

        if log_level:
            print("Number of displacements for special fc2: %d" % num_disps)
Example #17
0
def write_crystal_structure(
    filename, cell, interface_mode=None, optional_structure_info=None
):
    """Write crystal structure to file in each calculator format.

    filename : str, optional
        File name to be used to write out the crystal structure.
    cell : PhonopyAtoms
        Crystal structure
    interface_mode : str, optional
        Calculator interface such as 'vasp', 'qe', ... Default is None,
        that is equivalent to 'vasp'.
    optional_structure_info : tuple, optional
        Information returned by the method ``read_crystal_structure``.
        See the docstring. Default is None.

    """
    if interface_mode is None or interface_mode == "vasp":
        import phonopy.interface.vasp as vasp

        vasp.write_vasp(filename, cell)
    elif interface_mode == "abinit":
        import phonopy.interface.abinit as abinit

        abinit.write_abinit(filename, cell)
    elif interface_mode == "qe":
        import phonopy.interface.qe as qe

        pp_filenames = optional_structure_info[1]
        qe.write_pwscf(filename, cell, pp_filenames)
    elif interface_mode == "wien2k":
        import phonopy.interface.wien2k as wien2k

        _, npts, r0s, rmts = optional_structure_info
        wien2k.write_wein2k(filename, cell, npts, r0s, rmts)
    elif interface_mode == "elk":
        import phonopy.interface.elk as elk

        sp_filenames = optional_structure_info[1]
        elk.write_elk(filename, cell, sp_filenames)
    elif interface_mode == "siesta":
        import phonopy.interface.siesta as siesta

        atypes = optional_structure_info[1]
        siesta.write_siesta(filename, cell, atypes)
    elif interface_mode == "cp2k":
        import phonopy.interface.cp2k as cp2k

        _, tree = optional_structure_info
        cp2k.write_cp2k_by_filename(filename, cell, tree)
    elif interface_mode == "crystal":
        import phonopy.interface.crystal as crystal

        conv_numbers = optional_structure_info[1]
        crystal.write_crystal(filename, cell, conv_numbers)
    elif interface_mode == "dftbp":
        import phonopy.interface.dftbp as dftbp

        dftbp.write_dftbp(filename, cell)
    elif interface_mode == "turbomole":
        import phonopy.interface.turbomole as turbomole

        turbomole.write_turbomole(filename, cell)
    elif interface_mode == "aims":
        import phonopy.interface.aims as aims

        aims.write_aims(filename, cell)
    elif interface_mode == "castep":
        import phonopy.interface.castep as castep

        castep.write_castep(filename, cell)
    elif interface_mode == "fleur":
        import phonopy.interface.fleur as fleur

        speci, restlines = optional_structure_info
        fleur.write_fleur(filename, cell, speci, 1, restlines)
    else:
        raise RuntimeError("No calculator interface was found.")
Example #18
0
                      help="Convert VASP to WIEN2k")
    (options, args) = parser.parse_args()

    from phonopy.units import Bohr

    if options.v2w:
        cell = read_vasp(args[0])
        lattice = cell.get_cell() / Bohr
        cell.set_cell(lattice)
        npts, r0s, rmts = parse_core_param(open(args[1]))
        text = get_wien2k_struct(cell, npts, r0s, rmts)
        print text

    elif options.w2v:
        cell, npts, r0s, rmts = parse_wien2k_struct(args[0])
        positions = cell.get_scaled_positions()
        lattice = cell.get_cell() * Bohr
        cell.set_cell(lattice)
        cell.set_scaled_positions(positions)
        clean_scaled_positions(cell)
        write_vasp("POSCAR.wien2k", cell, direct=True)
        w = open("wien2k_core.dat", 'w')

        w.write("# symbol       npt       r0             rmt\n")
        for symbol, npt, r0, rmt in \
                zip( cell.get_chemical_symbols(), npts, r0s, rmts ):
            w.write("%-10s     %5d     %10.8f     %10.5f\n" %
                    (symbol, npt, r0, rmt))
    else:
        print "You need to set -r or -w option."
Example #19
0
def create_phono3py_supercells(unitcell, supercell_matrix,
                               phonon_supercell_matrix, output_filename,
                               symprec, settings, log_level):
    if settings.get_displacement_distance() is None:
        displacement_distance = 0.03
    else:
        displacement_distance = settings.get_displacement_distance()
    cutoff_pair_distance = settings.get_cutoff_pair_distance()
    phono3py = Phono3py(unitcell,
                        supercell_matrix,
                        phonon_supercell_matrix=phonon_supercell_matrix,
                        symprec=symprec)
    supercell = phono3py.get_supercell()
    phono3py.generate_displacements(
        distance=displacement_distance,
        cutoff_pair_distance=cutoff_pair_distance,
        is_plusminus=settings.get_is_plusminus_displacement(),
        is_diagonal=settings.get_is_diagonal_displacement())
    dds = phono3py.get_displacement_dataset()

    if log_level:
        print('')
        print("Displacement distance: %s" % displacement_distance)

    if output_filename is None:
        filename = 'disp_fc3.yaml'
    else:
        filename = 'disp_fc3.' + output_filename + '.yaml'

    num_disps, num_disp_files = write_disp_fc3_yaml(dds,
                                                    supercell,
                                                    filename=filename)
    for i, dcell in enumerate(phono3py.get_supercells_with_displacements()):
        if dcell is not None:
            write_vasp('POSCAR-%05d' % (i + 1), dcell, direct=True)

    if log_level:
        print("Number of displacements: %d" % num_disps)
        if cutoff_pair_distance is not None:
            print("Cutoff distance for displacements: %s" %
                  cutoff_pair_distance)
            print("Number of displacement supercell files created: %d" %
                  num_disp_files)

    if phonon_supercell_matrix is not None:
        phonon_dds = phono3py.get_phonon_displacement_dataset()
        phonon_supercell = phono3py.get_phonon_supercell()
        if output_filename is None:
            filename = 'disp_fc2.yaml'
        else:
            filename = 'disp_fc2.' + output_filename + '.yaml'

        num_disps = write_disp_fc2_yaml(phonon_dds,
                                        phonon_supercell,
                                        filename=filename)
        for i, dcell in enumerate(
                phono3py.get_phonon_supercells_with_displacements()):
            write_vasp('POSCAR_FC2-%05d' % (i + 1), dcell, direct=True)

        if log_level:
            print("Number of displacements for special fc2: %d" % num_disps)
Example #20
0
                      action="store_true",
                      help="Convert VASP to WIEN2k")
    (options, args) = parser.parse_args()

    from phonopy.units import Bohr

    if options.v2w:
        cell = read_vasp(args[0])
        lattice = cell.get_cell() / Bohr
        cell.set_cell( lattice )
        npts, r0s, rmts = parse_core_param(open(args[1]))
        text = get_wien2k_struct(cell, npts, r0s, rmts)
        print text

    elif options.w2v:
        cell, npts, r0s, rmts = parse_wien2k_struct(args[0])
        positions = cell.get_scaled_positions()
        lattice = cell.get_cell() * Bohr
        cell.set_cell( lattice )
        cell.set_scaled_positions( positions )
        clean_scaled_positions( cell )
        write_vasp("POSCAR.wien2k", cell, direct=True)
        w = open("wien2k_core.dat", 'w')
        
        w.write("# symbol       npt       r0             rmt\n")
        for symbol, npt, r0, rmt in \
                zip( cell.get_chemical_symbols(), npts, r0s, rmts ):
            w.write("%-10s     %5d     %10.8f     %10.5f\n" % (symbol, npt, r0, rmt))
    else:
        print "You need to set -r or -w option."
Example #21
0
        print("from disp-0001 to disp-%04d are already exist" % exist_disp_num)
    disp_start = "{0:04d}".format(exist_disp_num + 1)
    disp_stop = "{0:04d}".format(exist_disp_num + args.num)
    print("making displacement from disp-{0} to disp-{1}".format(
        disp_start, disp_stop))
    ### by mizo end

    for i, u_red in enumerate(np.dot(u, np.linalg.inv(lat))):
        cell = phonon.supercell.copy()
        pos = cell.get_scaled_positions()
        pos += u_red
        cell.set_scaled_positions(pos)
        # write_vasp("POSCAR-rd.%04d" % (i + 1), cell)

        ### by mizo start
        write_vasp("POSCAR-rd.%04d" % (exist_disp_num + i + 1), cell)
        ### by mizo end

if args.make_force:
    import io
    from phonopy.interface.vasp import VasprunxmlExpat
    forces = []
    points = []
    lattice = None

    vasprun_files = args.vaspruns.split()
    for filename in vasprun_files:
        print("reading %s" % filename)
        with io.open(filename, "rb") as fp:
            vasprun = VasprunxmlExpat(fp)
            vasprun.parse()
Example #22
0
    import quippy

    fmax = 1e-6
    pot = quippy.potential.Potential(param_filename=gp_xml_file)

    ucell = Intf_vasp.read_vasp('POSCAR')
    ucell_ase = api_ph.phonopyAtoms_to_aseAtoms(ucell)
    ucell_ase.set_calculator(
        pot)  # ase can accept quippy potential object as calculators
    #ucell_ase.set_constraint(FixAtoms(mask=[True for atom in ucell_ase]))
    #ucf = UnitCellFilter(ucell_ase)
    relax = BFGS(ucell_ase)

    relax.run(fmax=fmax)
    Unit_cell = api_ph.aseAtoms_to_phonopyAtoms(ucell_ase)
    Intf_vasp.write_vasp('POSCAR_relx', Unit_cell)

else:
    Unit_cell = Intf_vasp.read_vasp(
        "POSCAR")  # read prim cell from the POSCAR file

# generate displacements

prim_mat = np.eye(3)  #[[0, 0.5, 0.5],[0.5, 0, 0.5],[0.5, 0.5, 0]]
phonon_scell = Phonopy(
    Unit_cell, np.diag(Ncells),
    primitive_matrix=prim_mat)  # generate an phononpy object for LD calc.
phonon_scell.generate_displacements(distance=0.03)  # vasp
Scells_phonopy = phonon_scell.get_supercells_with_displacements(
)  # This returns a list of Phononpy atoms object
Example #23
0
 def write(self, filename):
     # the file io from ASE does not label the atoms for display in VESTA
     # so use the phonopy version
     write_vasp(filename, self.atoms)
Example #24
0
def calc_fcs(
    phono3py,
    calc,
    unitcell_f='Unknown',
    cp_files=None,
    sym_fc=True,
    fc_calc=None,
    r_cut=None,
):
    """
    fc_calc: None or 'alm'
    r_cut: None or float. Use hiPhive if provided.
    """

    # Check if structure is lower triangular cell
    for c in ((0, 1), (0, 2), (1, 2)):
        if phono3py.primitive.get_cell()[c[0], c[1]] != 0. and calc == 'lmp':
            raise ValueError('Please provide lower triangular cell.')

    #
    phono3py.generate_displacements()
    fc2_snd = phono3py.get_phonon_supercells_with_displacements()
    fc3_snd = phono3py.get_supercells_with_displacements()

    fc2_job_name = '{}-x{}{}{}_d0.010_sym{}-fc2'.format(
        calc,
        *np.diag(phono3py.get_phonon_supercell_matrix()),
        phono3py._is_symmetry,
    )
    fc3_job_name = '{}-x{}{}{}_d0.030_sym{}-fc3'.format(
        calc,
        *np.diag(phono3py.get_supercell_matrix()),
        phono3py._is_symmetry,
    )
    fc2_npy_name = '{}-forces.npy'.format(fc2_job_name)
    fc3_npy_name = '{}-forces.npy'.format(fc3_job_name)

    calc_dir = 'calcs'
    fc2_path = '{}/{}'.format(calc_dir, fc2_job_name)
    fc3_path = '{}/{}'.format(calc_dir, fc3_job_name)

    #
    from phonopy.interface.vasp import write_vasp
    call('mkdir -p {}/poscars'.format(fc2_path), shell=True)
    write_vasp('{}/poscars/SPOSCAR'.format(fc2_path),
               phono3py.get_phonon_supercell())
    for i in range(len(fc2_snd)):
        write_vasp('{}/poscars/POSCAR-{:03d}'.format(fc2_path, i + 1),
                   fc2_snd[i])
    #
    call('mkdir -p {}/poscars'.format(fc3_path), shell=True)
    write_vasp('{}/poscars/SPOSCAR'.format(fc3_path), phono3py.get_supercell())
    for i in range(len(fc3_snd)):
        write_vasp('{}/poscars/POSCAR-{:05d}'.format(fc3_path, i + 1),
                   fc3_snd[i])

    try:
        fc2_forces = np.load(fc2_npy_name)
    except:
        calc_fc2 = True
        print('\n*** NOTE) Failed to load {} file. ***\n'.format(fc2_npy_name))
    else:
        calc_fc2 = False
        print('\n=== NOTE) Loaded: {} ===\n'.format(fc2_npy_name))

    if calc_fc2:
        print('=== NOTE) Starting fc2 calculations! ===\n')
        fc2_forces = []
        for i in range(len(fc2_snd)):
            folder = 'disp-{:03d}'.format(i + 1)
            wdir = '{}/{}'.format(fc2_path, folder)
            budir = '{}/bu-{}'.format(fc2_path, folder)
            call('rm -rf {}'.format(budir), shell=True)
            call('mv {} {}'.format(wdir, budir), shell=True)
            call('mkdir -p {}'.format(wdir), shell=True)
            write_vasp('{}/POSCAR'.format(wdir), fc2_snd[i])
            fc2_forces.append(_calc_forces(wdir, calc, cp_files))
            print(' == Progress: {}/{}'.format(i + 1, len(fc2_snd)))
        np.save(fc2_npy_name, fc2_forces)

    try:
        fc3_forces = np.load(fc3_npy_name)
    except:
        calc_fc3 = True
        print('\n*** NOTE) Failed to load {} file. ***\n'.format(fc3_npy_name))
    else:
        calc_fc3 = False
        print('\n=== NOTE) Loaded: {} ===\n'.format(fc3_npy_name))

    if calc_fc3:
        print('=== NOTE) Starting fc3 calculations! ===\n')
        fc3_forces = []
        for i in range(len(fc3_snd)):
            folder = 'disp-{:05d}'.format(i + 1)
            wdir = '{}/{}'.format(fc3_path, folder)
            budir = '{}/bu-{}'.format(fc3_path, folder)
            call('rm -rf {}'.format(budir), shell=True)
            call('mv {} {}'.format(wdir, budir), shell=True)
            call('mkdir -p {}'.format(wdir), shell=True)
            write_vasp('{}/POSCAR'.format(wdir), fc3_snd[i])
            fc3_forces.append(_calc_forces(wdir, calc, cp_files))
            print(' == Progress: {}/{}'.format(i + 1, len(fc3_snd)))
        np.save(fc3_npy_name, fc3_forces)

    #
    phono3py.phonon_forces = np.array(fc2_forces)
    phono3py.forces = np.array(fc3_forces)

    #
    phono3py.produce_fc3(
        symmetrize_fc3r=sym_fc,
        fc_calculator=fc_calc,
    )
    phono3py.produce_fc2(
        symmetrize_fc2=sym_fc,
        fc_calculator=fc_calc,
    )
    if r_cut:
        #
        from ase.io import read
        from ase.calculators.singlepoint import SinglePointDFTCalculator
        fc2_disp_ds = phono3py.get_phonon_displacement_dataset()['first_atoms']
        fc2_sposcar = read('{}/poscars/SPOSCAR'.format(fc2_path))
        fc2_supers = []
        for i in range(len(fc2_disp_ds)):
            displacements = np.zeros(fc2_sposcar.get_positions().shape,
                                     dtype=float)
            displacements[fc2_disp_ds[i]
                          ['number']] += fc2_disp_ds[i]['displacement']
            fc2_supers.append(fc2_sposcar.copy())
            fc2_supers[-1].new_array(
                'displacements',
                displacements,
            )
            fc2_supers[-1]._calc = SinglePointDFTCalculator(fc2_supers[-1])
            fc2_supers[-1]._calc.results['forces'] = fc2_disp_ds[i]['forces']
        # rotational sum rule
        from hiphive import ForceConstants, ClusterSpace, StructureContainer
        cs = ClusterSpace(fc2_sposcar, [r_cut])
        sc = StructureContainer(cs)
        for s in fc2_supers:
            sc.add_structure(s)
        from hiphive.fitting import Optimizer
        opt = Optimizer(sc.get_fit_data(), train_size=1.0)
        opt.train()
        print(opt)
        parameters = opt.parameters
        from hiphive import ForceConstantPotential, enforce_rotational_sum_rules
        parameters_rot = enforce_rotational_sum_rules(cs, parameters,
                                                      ['Huang', 'Born-Huang'])
        fcp_rot = ForceConstantPotential(cs, parameters_rot)
        fcs = fcp_rot.get_force_constants(fc2_sposcar).get_fc_array(order=2)
        phono3py.set_fc2(fcs)

        # # Not implemented yet in hiPhive
        # fc3_disp_ds = phono3py.get_displacement_dataset()['first_atoms']
        # fc3_sposcar = read('{}/poscars/SPOSCAR'.format(fc3_path))
        # fc3_supers = []
        # for i in range(len(fc3_disp_ds)):
        # displacements_1st = np.zeros(fc3_sposcar.get_positions().shape, dtype=float)
        # displacements_1st[fc3_disp_ds[i]['number']] += fc3_disp_ds[i]['displacement']
        # for j in range(len(fc3_disp_ds[i]['second_atoms'])):
        # displacements_2nd = np.zeros(fc3_sposcar.get_positions().shape, dtype=float)
        # displacements_2nd[fc3_disp_ds[i]['second_atoms'][j]['number']] += fc3_disp_ds[i]['second_atoms'][j]['displacement']
        # displacements = displacements_1st + displacements_2nd
        # fc3_supers.append(fc3_sposcar.copy())
        # fc3_supers[-1].new_array(
        # 'displacements',
        # displacements,
        # )
        # fc3_supers[-1]._calc = SinglePointDFTCalculator(fc3_supers[-1])
        # fc3_supers[-1]._calc.results['forces'] = fc3_disp_ds[i]['second_atoms'][j]['forces']

    return phono3py