Beispiel #1
0
    def _create_supercell(self, unitcell, symprec):
        mat = self._supercell_matrix
        frame = self._get_surrounding_frame(mat)
        sur_cell, u2sur_map = self._get_simple_supercell(frame, unitcell)
    
        # Trim the simple supercell by the supercell matrix
        trim_frame = np.array([mat[0] / float(frame[0]),
                               mat[1] / float(frame[1]),
                               mat[2] / float(frame[2])])
        supercell, sur2s_map = trim_cell(trim_frame,
                                         sur_cell,
                                         symprec)

        multi = supercell.get_number_of_atoms() / unitcell.get_number_of_atoms()
        
        if multi != determinant(self._supercell_matrix):
            print "Supercell creation failed."
            Atoms.__init__(self)
        else:            
            Atoms.__init__(self,
                           numbers=supercell.get_atomic_numbers(),
                           masses=supercell.get_masses(),
                           magmoms=supercell.get_magnetic_moments(),
                           scaled_positions=supercell.get_scaled_positions(),
                           cell=supercell.get_cell(),
                           pbc=True)
            self._u2s_map = np.arange(unitcell.get_number_of_atoms()) * multi
            self._u2u_map = dict([(j, i) for i, j in enumerate(self._u2s_map)])
            self._s2u_map = np.array(u2sur_map)[sur2s_map] * multi
Beispiel #2
0
    def _create_supercell(self, unitcell, symprec):
        mat = self._supercell_matrix
        frame = self._get_surrounding_frame(mat)
        sur_cell, u2sur_map = self._get_simple_supercell(frame, unitcell)

        # Trim the simple supercell by the supercell matrix
        trim_frame = np.array([
            mat[0] / float(frame[0]), mat[1] / float(frame[1]),
            mat[2] / float(frame[2])
        ])
        supercell, sur2s_map = trim_cell(trim_frame, sur_cell, symprec)

        multi = supercell.get_number_of_atoms() / unitcell.get_number_of_atoms(
        )

        if multi != determinant(self._supercell_matrix):
            print "Supercell creation failed."
            Atoms.__init__(self)
        else:
            Atoms.__init__(self,
                           numbers=supercell.get_atomic_numbers(),
                           masses=supercell.get_masses(),
                           magmoms=supercell.get_magnetic_moments(),
                           scaled_positions=supercell.get_scaled_positions(),
                           cell=supercell.get_cell(),
                           pbc=True)
            self._u2s_map = np.arange(unitcell.get_number_of_atoms()) * multi
            self._u2u_map = dict([(j, i) for i, j in enumerate(self._u2s_map)])
            self._s2u_map = np.array(u2sur_map)[sur2s_map] * multi
Beispiel #3
0
class TestCell(unittest.TestCase):

    def setUp(self):
        symbols = ['Si'] * 2 + ['O'] * 4
        lattice = [[4.65, 0, 0],
                   [0, 4.75, 0],
                   [0, 0, 3.25]]
        points = [[0.0, 0.0, 0.0],
                  [0.5, 0.5, 0.5],
                  [0.3, 0.3, 0.0],
                  [0.7, 0.7, 0.0],
                  [0.2, 0.8, 0.5],
                  [0.8, 0.2, 0.5]]
        
        self._cell = Atoms(cell=lattice,
                           scaled_positions=points,
                           symbols=symbols)
    
    def tearDown(self):
        pass
    
    def test_atoms(self):
        print(self._cell.get_cell())
        for s, p in zip(self._cell.get_chemical_symbols(),
                        self._cell.get_scaled_positions()):
            print("%s %s" % (s, p))

    def test_phonopy_atoms(self):
        print(PhonopyAtoms(atoms=self._cell))
Beispiel #4
0
def read_pwscf(filename):
    pwscf_in = PwscfIn(open(filename).readlines())
    tags = pwscf_in.get_tags()
    lattice = tags['cell_parameters']
    positions = [pos[1] for pos in tags['atomic_positions']]
    species = [pos[0] for pos in tags['atomic_positions']]
    mass_map = {}
    pp_map = {}
    for vals in tags['atomic_species']:
        mass_map[vals[0]] = vals[1]
        pp_map[vals[0]] = vals[2]
    masses = [mass_map[x] for x in species]
    pp_all_filenames = [pp_map[x] for x in species]

    unique_species = []
    for x in species:
        if x not in unique_species:
            unique_species.append(x)
    
    numbers = []
    is_unusual = False
    for x in species:
        if x in symbol_map:
            numbers.append(symbol_map[x])
        else:
            numbers.append(-unique_species.index(x))
            is_unusual = True

    if is_unusual:
        positive_numbers = []
        for n in numbers:
            if n > 0:
                if n not in positive_numbers:
                    positive_numbers.append(n)
    
        available_numbers = range(1, 119)
        for pn in positive_numbers:
            available_numbers.remove(pn)
        
        for i, n in enumerate(numbers):
            if n < 1:
                numbers[i] = available_numbers[-n]

        cell = Atoms(numbers=numbers,
                     masses=masses,
                     cell=lattice,
                     scaled_positions=positions)
    else:
        cell = Atoms(numbers=numbers,
                     cell=lattice,
                     scaled_positions=positions)

    unique_symbols = []
    pp_filenames = {}
    for i, symbol in enumerate(cell.get_chemical_symbols()):
        if symbol not in unique_symbols:
            unique_symbols.append(symbol)
            pp_filenames[symbol] = pp_all_filenames[i]

    return cell, pp_filenames
Beispiel #5
0
def read_pwscf(filename):
    pwscf_in = PwscfIn(open(filename).readlines())
    tags = pwscf_in.get_tags()
    lattice = tags['cell_parameters']
    positions = [pos[1] for pos in tags['atomic_positions']]
    species = [pos[0] for pos in tags['atomic_positions']]
    mass_map = {}
    pp_map = {}
    for vals in tags['atomic_species']:
        mass_map[vals[0]] = vals[1]
        pp_map[vals[0]] = vals[2]
    masses = [mass_map[x] for x in species]
    pp_all_filenames = [pp_map[x] for x in species]

    unique_species = []
    for x in species:
        if x not in unique_species:
            unique_species.append(x)
    
    numbers = []
    is_unusual = False
    for x in species:
        if x in symbol_map:
            numbers.append(symbol_map[x])
        else:
            numbers.append(-unique_species.index(x))
            is_unusual = True

    if is_unusual:
        positive_numbers = []
        for n in numbers:
            if n > 0:
                if n not in positive_numbers:
                    positive_numbers.append(n)
    
        available_numbers = range(1, 119)
        for pn in positive_numbers:
            available_numbers.remove(pn)
        
        for i, n in enumerate(numbers):
            if n < 1:
                numbers[i] = available_numbers[-n]

        cell = Atoms(numbers=numbers,
                     masses=masses,
                     cell=lattice,
                     scaled_positions=positions)
    else:
        cell = Atoms(numbers=numbers,
                     cell=lattice,
                     scaled_positions=positions)

    unique_symbols = []
    pp_filenames = {}
    for i, symbol in enumerate(cell.get_chemical_symbols()):
        if symbol not in unique_symbols:
            unique_symbols.append(symbol)
            pp_filenames[symbol] = pp_all_filenames[i]

    return cell, pp_filenames
Beispiel #6
0
    def setUp(self):
        self._cells = []
        symbols = ['Si'] * 2 + ['O'] * 4
        lattice = [[4.65, 0, 0],
                   [0, 4.75, 0],
                   [0, 0, 3.25]]
        points = [[0.0, 0.0, 0.0],
                  [0.5, 0.5, 0.5],
                  [0.3, 0.3, 0.0],
                  [0.7, 0.7, 0.0],
                  [0.2, 0.8, 0.5],
                  [0.8, 0.2, 0.5]]

        self._cells.append(Atoms(cell=lattice,
                                 scaled_positions=points,
                                 symbols=symbols))

        symbols = ['Si'] * 2
        lattice = [[0, 2.73, 2.73],
                   [2.73, 0, 2.73],
                   [2.73, 2.73, 0]]
        points = [[0.75, 0.75, 0.75],
                  [0.5, 0.5, 0.5]]

        self._cells.append(Atoms(cell=lattice,
                                 scaled_positions=points,
                                 symbols=symbols))

        self._smats = []
        self._smats.append(np.diag([1, 2, 3]))
        self._smats.append([[-1, 1, 1],
                            [1, -1, 1],
                            [1, 1, -1]])

        self._fnames = ("SiO2-123.yaml", "Si-conv.yaml")
def get_data_from_dir(directory, i_volume):

    data_sets = file_IO.parse_FORCE_SETS(
        filename=directory + '/phonon-{0:02d}/FORCE_SETS'.format(i_volume))

    yaml_file = open(
        directory + '/phonon-{0:02d}/phonon.yaml'.format(i_volume), 'r')
    data = yaml.load_all(yaml_file).next()

    unit_cell = PhonopyAtoms(
        symbols=[item['symbol'] for item in data['points']],
        scaled_positions=[item['coordinates'] for item in data['points']],
        cell=data['lattice'])

    phonon = Phonopy(unit_cell, data['supercell_matrix'])

    phonon.set_displacement_dataset(data_sets)
    phonon.produce_force_constants()

    force_constants = phonon.get_force_constants()

    supercell = phonon.get_supercell()

    volume = unit_cell.get_volume()
    energy = data['electric_total_energy']

    return supercell, volume, energy, force_constants, data['supercell_matrix']
Beispiel #8
0
class TestCell(unittest.TestCase):

    def setUp(self):
        symbols = ['Si'] * 2 + ['O'] * 4
        lattice = [[4.65, 0, 0],
                   [0, 4.75, 0],
                   [0, 0, 3.25]]
        points = [[0.0, 0.0, 0.0],
                  [0.5, 0.5, 0.5],
                  [0.3, 0.3, 0.0],
                  [0.7, 0.7, 0.0],
                  [0.2, 0.8, 0.5],
                  [0.8, 0.2, 0.5]]
        
        self._cell = Atoms(cell=lattice,
                           scaled_positions=points,
                           symbols=symbols)
    
    def tearDown(self):
        pass
    
    def test_atoms(self):
        print(self._cell.get_cell())
        for s, p in zip(self._cell.get_chemical_symbols(),
                        self._cell.get_scaled_positions()):
            print s, p

    def test_phonopy_atoms(self):
        print(PhonopyAtoms(atoms=self._cell))
Beispiel #9
0
 def __init__( self, supercell, supercell_to_unitcell_map ):
     Atoms.__init__( self,
                     numbers = supercell.get_atomic_numbers(),
                     masses = supercell.get_masses(),
                     scaled_positions = supercell.get_scaled_positions(),
                     cell = supercell.get_cell(),
                     pbc = True )
     self.s2u_map = supercell_to_unitcell_map
Beispiel #10
0
 def __init__(self, supercell, supercell_to_unitcell_map):
     Atoms.__init__(self,
                    numbers = supercell.get_atomic_numbers(),
                    masses = supercell.get_masses(),
                    magmoms = supercell.get_magnetic_moments(),
                    scaled_positions = supercell.get_scaled_positions(),
                    cell = supercell.get_cell(),
                    pbc = True)
     self.s2u_map = supercell_to_unitcell_map
Beispiel #11
0
    def setUp(self):
        symbols = ['Si'] * 2 + ['O'] * 4
        lattice = [[4.65, 0, 0], [0, 4.75, 0], [0, 0, 3.25]]
        points = [[0.0, 0.0, 0.0], [0.5, 0.5, 0.5], [0.3, 0.3, 0.0],
                  [0.7, 0.7, 0.0], [0.2, 0.8, 0.5], [0.8, 0.2, 0.5]]

        self._cell = Atoms(cell=lattice,
                           scaled_positions=points,
                           symbols=symbols)
Beispiel #12
0
def get_phonopy(structure):
    from phonopy import Phonopy
    from phonopy.structure.atoms import Atoms as PhonopyAtoms

    phon_atoms = PhonopyAtoms(symbols=[str(s.specie) for s in structure],
                              scaled_positions=structure.frac_coords)
    phon_atoms.set_cell(structure.lattice.matrix)
    # supercell size
    scell = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
    return Phonopy(phon_atoms, scell)
Beispiel #13
0
def get_phonopy(structure):
    from phonopy import Phonopy
    from phonopy.structure.atoms import Atoms as PhonopyAtoms

    phon_atoms = PhonopyAtoms(symbols=[str(s.specie) for s in structure],
                              scaled_positions=structure.frac_coords)
    phon_atoms.set_cell(structure.lattice.matrix)
    # supercell size
    scell = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
    return Phonopy(phon_atoms, scell)
Beispiel #14
0
    def _primitive_cell(self, supercell):
        trimed_cell, p2s_map = trim_cell(self.frame, supercell, self.symprec)
        Atoms.__init__(self,
                       numbers=trimed_cell.get_atomic_numbers(),
                       masses=trimed_cell.get_masses(),
                       magmoms=trimed_cell.get_magnetic_moments(),
                       scaled_positions=trimed_cell.get_scaled_positions(),
                       cell=trimed_cell.get_cell(),
                       pbc=True)

        self.p2s_map = p2s_map
Beispiel #15
0
    def _primitive_cell(self, supercell):
        trimed_cell, p2s_map = trim_cell(self._primitive_matrix, supercell,
                                         self._symprec)
        Atoms.__init__(self,
                       numbers=trimed_cell.get_atomic_numbers(),
                       masses=trimed_cell.get_masses(),
                       magmoms=trimed_cell.get_magnetic_moments(),
                       scaled_positions=trimed_cell.get_scaled_positions(),
                       cell=trimed_cell.get_cell(),
                       pbc=True)

        self._p2s_map = np.array(p2s_map, dtype='intc')
Beispiel #16
0
    def __primitive_cell(self, supercell):
        trimed_cell, p2s_map = trim_cell( self.frame,
                                          supercell,
                                          self.symprec )
        Atoms.__init__( self,
                        numbers = trimed_cell.get_atomic_numbers(),
                        masses = trimed_cell.get_masses(),
                        scaled_positions = trimed_cell.get_scaled_positions(),
                        cell = trimed_cell.get_cell(),
                        pbc = True )

        self.p2s_map = p2s_map
Beispiel #17
0
    def _primitive_cell(self, supercell):
        trimed_cell, p2s_map = trim_cell(self._primitive_matrix,
                                         supercell,
                                         self._symprec)
        Atoms.__init__(self,
                       numbers=trimed_cell.get_atomic_numbers(),
                       masses=trimed_cell.get_masses(),
                       magmoms=trimed_cell.get_magnetic_moments(),
                       scaled_positions=trimed_cell.get_scaled_positions(),
                       cell=trimed_cell.get_cell(),
                       pbc=True)

        self._p2s_map = np.array(p2s_map, dtype='intc')
Beispiel #18
0
def get_phonopy(structure):
    try:
        from phonopy import Phonopy
        from phonopy.structure.atoms import Atoms as PhonopyAtoms
    except ImportError:
        print("Install phonopy. Exiting.")
        sys.exit()

    phon_atoms = PhonopyAtoms(symbols=[str(s.specie) for s in structure],
                              scaled_positions=structure.frac_coords)
    phon_atoms.set_cell(structure.lattice.matrix)
    # supercell size
    scell = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
    return Phonopy(phon_atoms, scell)
Beispiel #19
0
def get_phonopy(structure):
    try:
        from phonopy import Phonopy
        from phonopy.structure.atoms import Atoms as PhonopyAtoms
    except ImportError:
        print("Install phonopy. Exiting.")
        sys.exit()

    phon_atoms = PhonopyAtoms(symbols=[str(s.specie) for s in structure],
                              scaled_positions=structure.frac_coords)
    phon_atoms.set_cell(structure.lattice.matrix)
    # supercell size
    scell = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
    return Phonopy(phon_atoms, scell)
Beispiel #20
0
def read_aims(filename):
    """Read FHI-aims geometry files in phonopy context."""
    lines = open(filename, "r").readlines()

    cell = []
    is_frac = []
    positions = []
    symbols = []
    magmoms = []
    for line in lines:
        fields = line.split()
        if not len(fields):
            continue
        if fields[0] == "lattice_vector":
            vec = lmap(float, fields[1:4])
            cell.append(vec)
        elif fields[0][0:4] == "atom":
            if fields[0] == "atom":
                frac = False
            elif fields[0] == "atom_frac":
                frac = True
            pos = lmap(float, fields[1:4])
            sym = fields[4]
            is_frac.append(frac)
            positions.append(pos)
            symbols.append(sym)
            magmoms.append(None)
        # implicitly assuming that initial_moments line adhere to FHI-aims geometry.in
        # specification, i.e. two subsequent initial_moments lines do not occur
        # if they do, the value specified in the last line is taken here - without
        # any warning
        elif fields[0] == "initial_moment":
            magmoms[-1] = float(fields[1])

    for (n, frac) in enumerate(is_frac):
        if frac:
            pos = [
                sum([positions[n][ll] * cell[ll][i] for ll in range(3)])
                for i in range(3)
            ]
            positions[n] = pos
    if None in magmoms:
        atoms = Atoms(cell=cell, symbols=symbols, positions=positions)
    else:
        atoms = Atoms(cell=cell,
                      symbols=symbols,
                      positions=positions,
                      magmoms=magmoms)

    return atoms
Beispiel #21
0
    def _build_supercells_with_displacements(self):
        supercells = []
        magmoms = self._supercell.get_magnetic_moments()
        masses = self._supercell.get_masses()
        numbers = self._supercell.get_atomic_numbers()
        lattice = self._supercell.get_cell()

        for disp1 in self._displacement_dataset['first_atoms']:
            disp_cart1 = disp1['displacement']
            positions = self._supercell.get_positions()
            positions[disp1['number']] += disp_cart1
            supercells.append(
                Atoms(numbers=numbers,
                      masses=masses,
                      magmoms=magmoms,
                      positions=positions,
                      cell=lattice,
                      pbc=True))

        for disp1 in self._displacement_dataset['first_atoms']:
            for disp2 in disp1['second_atoms']:
                positions = self._supercell.get_positions()
                positions[disp1['number']] += disp_cart1
                positions[disp2['number']] += disp2['displacement']
                supercells.append(
                    Atoms(numbers=numbers,
                          masses=masses,
                          magmoms=magmoms,
                          positions=positions,
                          cell=lattice,
                          pbc=True))

        for disp1 in self._displacement_dataset['first_atoms']:
            for disp2 in disp1['second_atoms']:
                for disp3 in disp2['third_atoms']:
                    positions = self._supercell.get_positions()
                    positions[disp1['number']] += disp_cart1
                    positions[disp2['number']] += disp2['displacement']
                    positions[disp3['number']] += disp3['displacement']
                    supercells.append(
                        Atoms(numbers=numbers,
                              masses=masses,
                              magmoms=magmoms,
                              positions=positions,
                              cell=lattice,
                              pbc=True))

        self._supercells_with_displacements = supercells
Beispiel #22
0
def ReadBORN(structure, filePath="BORN"):
    """
    Read a Phonopy BORN file, and expand the charges for the supplied structure, and return a list of Born effective-charge tensors for each atom in the structure.

    Arguments:
        structure -- a tuple of (lattice_vectors, atomic_symbols, atom_positions) specifying the structure to be used to expand the Born charges to the full set of atoms.

    Keyword arguments:
        filePath -- path to the Phonopy BORN-format file to read (default: BORN).

    Return value:
        A list of 3x3 Born effective-charge tensors for each atom in the supplied structure.

    Notes:
        The atom positions supplied with structure are assumed to be in fractional coordinates.
    """

    # Convert the supplied structure to a Phonopy Atoms object.

    latticeVectors, atomicSymbols, atomPositions = structure

    cell = Atoms(symbols=atomicSymbols,
                 cell=latticeVectors,
                 scaled_positions=atomPositions)

    # Read the BORN file.

    bornData = parse_BORN(cell, filename=filePath)

    # Return the Born effective-charge tensors from the dictionary returned by parse_BORN.

    return [becTensor for becTensor in bornData['born']]
Beispiel #23
0
def get_simple_supercell(multi, unitcell):
    # Scaled positions within the frame, i.e., create a supercell that
    # is made simply to multiply the input cell.
    positions = unitcell.get_scaled_positions()
    numbers = unitcell.get_atomic_numbers()
    masses = unitcell.get_masses()
    magmoms = unitcell.get_magnetic_moments()
    lattice = unitcell.get_cell()
    
    positions_multi = []
    numbers_multi = []
    masses_multi = []
    if magmoms == None:
        magmoms_multi = None
    else:
        magmoms_multi = []
    for l, pos in enumerate(positions):
        for i in range(multi[2]):
            for j in range(multi[1]):
                for k in range(multi[0]):
                    positions_multi.append([(pos[0] + k) / multi[0],
                                            (pos[1] + j) / multi[1],
                                            (pos[2] + i) / multi[2]])
                    numbers_multi.append(numbers[l])
                    masses_multi.append(masses[l])
                    if not magmoms == None:
                        magmoms_multi.append(magmoms[l])

    return Atoms(numbers = numbers_multi,
                 masses = masses_multi,
                 magmoms = magmoms_multi,
                 scaled_positions = positions_multi,
                 cell = np.dot(np.diag(multi), lattice),
                 pbc=True)
Beispiel #24
0
def read_crystal(filename):
    f_crystal = open(filename)
    crystal_in = CrystalIn(f_crystal.readlines())
    f_crystal.close()
    tags = crystal_in.get_tags()

    cell = Atoms(cell=tags['lattice_vectors'],
                 symbols=tags['atomic_species'],
                 scaled_positions=tags['coordinates'])

    magmoms = tags['magnetic_moments']
    if magmoms is not None:
        # Print out symmetry information for magnetic cases
        # Original code from structure/symmetry.py
        symmetry = Symmetry(cell, symprec=1e-5)
        print(
            "CRYSTAL-interface: Magnetic structure, number of operations without spin: %d"
            % len(symmetry.get_symmetry_operations()['rotations']))
        print("CRYSTAL-interface: Spacegroup without spin: %s" %
              symmetry.get_international_table())

        cell.set_magnetic_moments(magmoms)
        symmetry = Symmetry(cell, symprec=1e-5)
        print(
            "CRYSTAL-interface: Magnetic structure, number of operations with spin: %d"
            % len(symmetry.get_symmetry_operations()['rotations']))
        print("")

    return cell, tags['conv_numbers']
Beispiel #25
0
def read_siesta(filename):
    siesta_in = SiestaIn(open(filename).read())
    numbers = siesta_in._tags["atomicnumbers"]
    lattice = siesta_in._tags["latticevectors"]
    positions = siesta_in._tags["atomiccoordinates"]
    atypes = siesta_in._tags["chemicalspecieslabel"]
    cell = Atoms(numbers=numbers, cell=lattice, scaled_positions=positions)

    coordformat = siesta_in._tags["atomiccoordinatesformat"]
    if coordformat == "fractional" or coordformat == "scaledbylatticevectors":
        cell.set_scaled_positions(positions)
    elif coordformat == "scaledcartesian":
        if siesta_in._tags['latticeconstant'] == 'ang':
            cell.set_positions(np.array(positions) / Bohr)
        else:
            cell.set_positions(np.array(positions))
    elif coordformat == "notscaledcartesianang" or coordformat == "ang":
        cell.set_positions(np.array(positions) / Bohr)
    elif coordformat == "notscaledcartesianbohr" or coordformat == "bohr":
        cell.set_positions(np.array(positions))
    else:
        print("The format %s for the AtomicCoordinatesFormat is not "
              "implemented." % coordformat)
        sys.exit(1)

    return cell, atypes
Beispiel #26
0
    def _get_supercell(self):
        """Attention

        This method will be removed after
        new get_delta method is well checked.
        """
        dim = self._dimension
        scaled_positions = []
        masses = []
        magmoms_prim = self._primitive.get_magnetic_moments()
        if magmoms_prim is None:
            magmoms = None
        else:
            magmoms = []
        symbols = []
        for a, b, c in list(np.ndindex(tuple(dim))):
            for i in range(self._primitive.get_number_of_atoms()):
                p = self._primitive.get_scaled_positions()[i]
                scaled_positions.append(p + np.array([a, b, c]))
                masses.append(self._primitive.get_masses()[i])
                symbols.append(self._primitive.get_chemical_symbols()[i])
                if magmoms_prim is not None:
                    magmoms.append(magmoms_prim[i])

        lattice = np.dot(np.diag(dim), self._primitive.get_cell())
        positions = np.dot(scaled_positions, self._primitive.get_cell())

        from phonopy.structure.atoms import Atoms
        return Atoms(cell=lattice,
                     positions=positions,
                     masses=masses,
                     magmoms=magmoms,
                     symbols=symbols,
                     pbc=True)
Beispiel #27
0
def get_born_vasprunxml(filename="vasprun.xml",
                        primitive_matrix=None,
                        supercell_matrix=None,
                        is_symmetry=True,
                        symmetrize_tensors=False,
                        symprec=1e-5):
    import io
    borns = []
    epsilon = []
    with io.open(filename, "rb") as f:
        vasprun = VasprunxmlExpat(f)
        if vasprun.parse():
            epsilon = vasprun.get_epsilon()
            borns = vasprun.get_born()
            lattice = vasprun.get_lattice()[-1]
            points = vasprun.get_points()[-1]
            symbols = vasprun.get_symbols()
            ucell = Atoms(symbols=symbols,
                          scaled_positions=points,
                          cell=lattice)
        else:
            return None

    return elaborate_borns_and_epsilon(ucell,
                                       borns,
                                       epsilon,
                                       primitive_matrix=primitive_matrix,
                                       supercell_matrix=supercell_matrix,
                                       is_symmetry=is_symmetry,
                                       symmetrize_tensors=symmetrize_tensors,
                                       symprec=symprec)
Beispiel #28
0
def read_castep(filename):
    f_castep = open(filename)
    castep_in = CastepIn(f_castep.readlines())
    f_castep.close()
    tags = castep_in.get_tags()
    # 1st stage is to create Atoms object ignoring Spin polarization. General case.
    cell = Atoms(cell=tags['lattice_vectors'],
                 symbols=tags['atomic_species'],
                 scaled_positions=tags['coordinates'])
    # Analyse spin states and add data to Atoms instance "cell" if ones exist
    magmoms = tags['magnetic_moments']
    if magmoms is not None:
        # Print out symmetry information for magnetic cases
        # Original code from structure/symmetry.py
        symmetry = Symmetry(cell, symprec=1e-5)
        print(
            "CASTEP-interface: Magnetic structure, number of operations without spin: %d"
            % len(symmetry.get_symmetry_operations()['rotations']))
        print("CASTEP-interface: Spacegroup without spin: %s" %
              symmetry.get_international_table())

        cell.set_magnetic_moments(magmoms)
        symmetry = Symmetry(cell, symprec=1e-5)
        print(
            "CASTEP-interface: Magnetic structure, number of operations with spin: %d"
            % len(symmetry.get_symmetry_operations()['rotations']))
        print("")

    return cell
Beispiel #29
0
def read_fleur(filename):
    fleur_in = FleurIn(open(filename).readlines())
    tags = fleur_in.get_variables()
    avec = [tags['avec'][i] for i in range(3)]
    speci = tags['atoms']['speci']
    symbols = [
        list(symbol_map.keys())[list(symbol_map.values()).index(
            math.floor(float(x)))] for x in speci
    ]
    numbers = [math.floor(float(x)) for x in speci]

    for i, n in enumerate(numbers):
        if n == 0:
            for j in range(1, 119):
                if not (j in numbers):
                    numbers[i] = j
                    break
    pos_all = []
    num_all = []
    for num, pos in zip(numbers, tags['atoms']['positions']):
        pos_all += pos
    num_all = [symbol_map[s] for s in symbols]

    return Atoms(numbers=num_all, cell=avec,
                 scaled_positions=pos_all), speci, fleur_in._restlines
Beispiel #30
0
    def _get_cell(self, lattice, points, symbols, masses=None):
        if lattice:
            _lattice = lattice
        else:
            _lattice = None
        if points:
            _points = points
        else:
            _points = None
        if symbols:
            _symbols = symbols
        else:
            _symbols = None
        if masses:
            _masses = masses
        else:
            _masses = None

        if _lattice and _points and _symbols:
            return Atoms(symbols=_symbols,
                         cell=_lattice,
                         masses=_masses,
                         scaled_positions=_points)
        else:
            return None
Beispiel #31
0
def get_commensurate_points(supercell_matrix): # wrt primitive cell
    rec_primitive = Atoms(numbers=[1],
                          scaled_positions=[[0, 0, 0]],
                          cell=np.diag([1, 1, 1]),
                          pbc=True)
    rec_supercell = get_supercell(rec_primitive, supercell_matrix.T)
    return rec_supercell.get_scaled_positions()
Beispiel #32
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)
Beispiel #33
0
def parse_disp_yaml_with_supercell(filename='disp.yaml'):
    try:
        import yaml
    except ImportError:
        print "You need to install python-yaml."
        exit(1)

    try:
        from yaml import CLoader as Loader
        from yaml import CDumper as Dumper
    except ImportError:
        from yaml import Loader, Dumper

    data = yaml.load(open(filename).read(), Loader=Loader)
    lattice = data['lattice']
    displacements = []
    for x in data['displacements']:
        displacements.append([x['atom'] - 1, x['displacement']])
    positions = [x['position'] for x in data['atoms']]
    symbols = [x['symbol'] for x in data['atoms']]
    cell = Atoms(cell=lattice,
                 scaled_positions=positions,
                 symbols=symbols,
                 pbc=True)

    return displacements, cell
Beispiel #34
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)
def gencastep(fn, modenum, basis, natom, typatsym, symprec, atpos):
    from phonopy import Phonopy
    import phonopy.structure.spglib as spg
    from phonopy.structure.atoms import PhonopyAtoms as Atoms
    from phonopy.structure.symmetry import Symmetry, find_primitive, get_pointgroup

    fh = open(fn, 'w')
    unitcell = Atoms(symbols=typatsym, cell=basis, positions=atpos)
    pbasis = np.eye(3)
    for i in range(len(basis)):
        pbasis[i] = basis[i] / np.linalg.norm(basis[i])
    symmetry = Symmetry(unitcell, symprec)
    rotations = symmetry.get_symmetry_operations()['rotations']
    translations = symmetry.get_symmetry_operations()['translations']
    print('Space group International symbol: %s' %
          symmetry.get_international_table())

    fh.write('%BLOCK LATTICE_CART\n')
    for bl in basis:
        fh.write('%s\n' % ''.join(' %12.8f' % b for b in bl))
    fh.write('%ENDBLOCK LATTICE_CART\n\n')
    fh.write('%BLOCK POSITIONS_ABS\n')
    for i in range(len(typatsym)):
        fh.write("  %3s   " % typatsym[i])
        fh.write('%s\n' % ''.join(' %12.8f' % p for p in atpos[i].tolist()))
    fh.write('%ENDBLOCK POSITIONS_ABS\n\n')

    fh.write('SYMMETRY_TOL : %f ang\n' % symprec)
    fh.write('SYMMETRY_GENERATE \n')
    fh.write('#KPOINT_MP_GRID : 4 4 4\n#KPOINT_MP_OFFSET : 0.5 0.5 0.5\n')
Beispiel #36
0
def read_elk(filename):
    """Read crystal structure."""
    elk_in = ElkIn(open(filename).readlines())
    tags = elk_in.get_variables()
    avec = [tags["scale"][i] * np.array(tags["avec"][i]) for i in range(3)]
    spfnames = tags["atoms"]["spfnames"]
    symbols = [x.split(".")[0] for x in spfnames]
    numbers = []
    for s in symbols:
        if s in symbols:
            numbers.append(symbol_map[s])
        else:
            numbers.append(0)

    for i, n in enumerate(numbers):
        if n == 0:
            for j in range(1, 119):
                if not (j in numbers):
                    numbers[i] = j
                    break
    pos_all = []
    num_all = []
    for num, pos in zip(numbers, tags["atoms"]["positions"]):
        pos_all += pos
        num_all += [num] * len(pos)

    return Atoms(numbers=num_all, cell=avec,
                 scaled_positions=pos_all), spfnames
Beispiel #37
0
    def _build_supercells_with_displacements(self):
        supercells = []
        magmoms = self._supercell.get_magnetic_moments()
        masses = self._supercell.get_masses()
        numbers = self._supercell.get_atomic_numbers()
        lattice = self._supercell.get_cell()

        supercells = self._build_phonon_supercells_with_displacements(
            self._supercell,
            self._displacement_dataset)

        for disp1 in self._displacement_dataset['first_atoms']:
            disp_cart1 = disp1['displacement']
            for disp2 in disp1['second_atoms']:
                if 'included' in disp2:
                    included = disp2['included']
                else:
                    included = True
                if included:
                    positions = self._supercell.get_positions()
                    positions[disp1['number']] += disp_cart1
                    positions[disp2['number']] += disp2['displacement']
                    supercells.append(Atoms(numbers=numbers,
                                            masses=masses,
                                            magmoms=magmoms,
                                            positions=positions,
                                            cell=lattice,
                                            pbc=True))
                else:
                    supercells.append(None)

        self._supercells_with_displacements = supercells
Beispiel #38
0
    def _get_supercell(self):
        dim = self._dimension
        scaled_positions = []
        masses = []
        magmoms_prim = self._cell.get_magnetic_moments()
        if magmoms_prim == None:
            magmoms = None
        else:
            magmoms = []
        symbols = []
        for a in range(dim[0]):
            for b in range(dim[1]):
                for c in range(dim[2]):
                    for i in range(self._cell.get_number_of_atoms()):
                        p = self._cell.get_scaled_positions()[i]
                        scaled_positions.append(p + np.array([a,b,c]))
                        masses.append(self._cell.get_masses()[i])
                        symbols.append(self._cell.get_chemical_symbols()[i])
                        if not magmoms_prim == None:
                            magmoms.append(magmoms_prim[i])

        lattice = np.dot(np.diag(dim), self._cell.get_cell())
        positions = np.dot(scaled_positions, self._cell.get_cell())

        return Atoms(cell=lattice,
                     positions=positions,
                     masses=masses,
                     magmoms=magmoms,
                     symbols=symbols,
                     pbc=True)
Beispiel #39
0
 def setUp(self):
     symbols = ['Si'] * 2 + ['O'] * 4
     lattice = [[4.65, 0, 0],
                [0, 4.75, 0],
                [0, 0, 3.25]]
     points = [[0.0, 0.0, 0.0],
               [0.5, 0.5, 0.5],
               [0.3, 0.3, 0.0],
               [0.7, 0.7, 0.0],
               [0.2, 0.8, 0.5],
               [0.8, 0.2, 0.5]]
     
     self._cell = Atoms(cell=lattice,
                        scaled_positions=points,
                        symbols=symbols)
Beispiel #40
0
def read_siesta(filename):
    siesta_in = SiestaIn(open(filename).read())
    numbers = siesta_in._tags["atomicnumbers"]
    lattice = siesta_in._tags["latticevectors"]
    positions = siesta_in._tags["atomiccoordinates"]
    atypes = siesta_in._tags["chemicalspecieslabel"]
    cell = Atoms(numbers=numbers,
                 cell=lattice)

    coordformat = siesta_in._tags["atomiccoordinatesformat"]
    if coordformat == "fractional" or coordformat == "scaledbylatticevectors":
        cell.set_scaled_positions(positions)
    elif coordformat == "scaledcartesian":
        if siesta_in._tags['latticeconstant'] == 'ang':
            cell.set_positions(np.array(positions) / Bohr)#convert from angstroem to Bohr 
        else:
            cell.set_positions(np.array(positions))
    elif coordformat == "notscaledcartesianang" or coordformat == "ang":
        cell.set_positions(np.array(positions) / Bohr) #convert from angstroem to Bohr 
    elif coordformat == "notscaledcartesianbohr" or coordformat == "bohr":
        cell.set_positions(np.array(positions))
    else:
        print "The format %s for the AtomicCoordinatesFormat is not implemented"%coordformat
        exit() 
    
    return cell, atypes
Beispiel #41
0
 def __init__(self, numbatom=125, supercell=5):
     
     #species = 'WRe_0.25_conv'
     species = 'WRe_0.00'
     #species = 'Re'
     ###read force constants from vasprun.xml###
     vasprun = etree.iterparse('vasprun.xml', tag='varray')
     #fc = vasp.get_force_constants_vasprun_xml(vasprun,1) #pass xml input and species atomic weight.
     ###########################################
     
     ########### read positionsl ###############
     primitive = vasp.get_atoms_from_poscar(open('POSCAR-p'),'W')
     superc =  vasp.get_atoms_from_poscar(open('POSCAR'),'W')
     ###########################################
     numbatom =  superc.get_number_of_atoms()
     #print primitive.get_cell()
     #print primitive.get_scaled_positions()
     #print superc.get_scaled_positions()
     
     print numbatom, species, os.getcwd()
     if species=='W':
     #Tungsten
         fc = vasp.get_force_constants_vasprun_xml(vasprun,1,0,64)
         s = 4.
         a = superc.get_cell()[0][0]*2.
         print a
         bulk = PhonopyAtoms(symbols=['W'] * 1,
                             scaled_positions= primitive.get_scaled_positions())
         bulk.set_cell(np.diag((a, a, a)))
         phonon = Phonopy(bulk,
                          [[s,0.,0.],[0.,s,0.],[0.,0.,s]],
                          primitive_matrix=[[-0.5, 0.5, 0.5],[0.5, -0.5, 0.5],[0.5, 0.5, -0.5]],
                          distance=0.01, factor=15.633302)
         print fc
         phonon.set_force_constants(fc[0])
         phonon.set_dynamical_matrix()
         #print phonon.get_dynamical_matrix_at_q([0,0,0])
         mesh = [100, 100, 100]
         phonon.set_mesh(mesh)
         qpoints, weights, frequencies, eigvecs = phonon.get_mesh()
         print frequencies
         phonon.set_total_DOS()
         
         phonon.set_thermal_properties(t_step=10,
                                       t_max=3700,
                                       t_min=0)
         
     elif species=='W_conv_2x2x2':
     #Tungsten
         fc = vasp.get_force_constants_vasprun_xml(vasprun,1,2)
         s = 2.
         a = superc.get_cell()[0][0]*2.
         print a
         bulk = PhonopyAtoms(symbols=['W','W'] * 1,
                             scaled_positions= primitive.get_scaled_positions())
         bulk.set_cell(np.diag((a, a, a)))
         phonon = Phonopy(bulk,
                          [[s,0.,0.],[0.,s,0.],[0.,0.,s]],
                          primitive_matrix=[[-0.5, 0.5, 0.5],[0.5, -0.5, 0.5],[0.5, 0.5, -0.5]],
                          distance=0.01, factor=15.633302)
         print fc
         phonon.set_force_constants(fc[0])
         phonon.set_dynamical_matrix()
         #print phonon.get_dynamical_matrix_at_q([0,0,0])
         mesh = [100, 100, 100]
         phonon.set_mesh(mesh)
         qpoints, weights, frequencies, eigvecs = phonon.get_mesh()
         print frequencies
         phonon.set_total_DOS()
         
         phonon.set_thermal_properties(t_step=10,
                                       t_max=3700,
                                       t_min=0)
     
     elif species=='W_conv':
     #Tungsten
         fc = vasp.get_force_constants_vasprun_xml(vasprun,1,2)
         s = 4.
         a = superc.get_cell()[0][0]*2.
         print a
         bulk = PhonopyAtoms(symbols=['W','W'] * 1,
                             scaled_positions= primitive.get_scaled_positions())
         bulk.set_cell(np.diag((a, a, a)))
         phonon = Phonopy(bulk,
                          [[s,0.,0.],[0.,s,0.],[0.,0.,s]],
                          primitive_matrix=[[-0.5, 0.5, 0.5],[0.5, -0.5, 0.5],[0.5, 0.5, -0.5]],
                          distance=0.01, factor=15.633302)
         print fc
         phonon.set_force_constants(fc[0])
         phonon.set_dynamical_matrix()
         #print phonon.get_dynamical_matrix_at_q([0,0,0])
         mesh = [100, 100, 100]
         phonon.set_mesh(mesh)
         qpoints, weights, frequencies, eigvecs = phonon.get_mesh()
         print frequencies
         phonon.set_total_DOS()
         
         phonon.set_thermal_properties(t_step=10,
                                       t_max=3700,
                                       t_min=0)
     
     elif species=='WRe_0.25_conv':
     #Tungsten
         fc = vasp.get_force_constants_vasprun_xml(vasprun,8,2,64)
         s = 4.
         a = superc.get_cell()[0][0]*2.
         print a, primitive.get_scaled_positions()
         bulk = PhonopyAtoms(symbols=['W','W'] * 1,
                             scaled_positions= primitive.get_scaled_positions())
         bulk.set_cell(np.diag((a, a, a)))
         phonon = Phonopy(bulk,
                          [[s,0.,0.],[0.,s,0.],[0.,0.,s]],
                          primitive_matrix=[[-0.5, 0.5, 0.5],[0.5, -0.5, 0.5],[0.5, 0.5, -0.5]],
                          distance=0.01, factor=15.633302)
         print fc
         phonon.set_force_constants(fc[0])
         phonon.set_dynamical_matrix()
         #print phonon.get_dynamical_matrix_at_q([0,0,0])
         mesh = [100, 100, 100]
         phonon.set_mesh(mesh)
         qpoints, weights, frequencies, eigvecs = phonon.get_mesh()
         #print frequencies
         phonon.set_total_DOS()
         
         phonon.set_thermal_properties(t_step=10,
                                       t_max=3700,
                                       t_min=0)
     
     elif species == 'WRe_B2': 
         fc = vasp.get_force_constants_vasprun_xml(vasprun,1,1)
         s = 5.
         a = superc.get_cell()[0][0]*2.
         print a
         bulk = PhonopyAtoms(symbols=['W','Re'] * 1,
                             scaled_positions= primitive.get_scaled_positions())
         bulk.set_cell(np.diag((a, a, a)))
         phonon = Phonopy(bulk,
                          [[s,0.,0.],[0.,s,0.],[0.,0.,s]],
                          primitive_matrix=[[-0.5, 0.5, 0.5],[0.5, -0.5, 0.5],[0.5, 0.5, -0.5]],
                          distance=0.01, factor=15.633302)
         print fc
         phonon.set_force_constants(fc[0])
         phonon.set_dynamical_matrix()
         #print phonon.get_dynamical_matrix_at_q([0,0,0])
         mesh = [100, 100, 100]
         phonon.set_mesh(mesh)
         qpoints, weights, frequencies, eigvecs = phonon.get_mesh()
         print frequencies
         phonon.set_total_DOS()
         
         phonon.set_thermal_properties(t_step=10,
                                       t_max=3700,
                                       t_min=0)
     elif species == 'WRe_0.00': 
         fc = vasp.get_force_constants_vasprun_xml(vasprun,1,0,numbatom)
         s = supercell
         a = superc.get_cell()[0][0]*2.
         print a
         bulk = PhonopyAtoms(symbols=['W'] * 1,
                             scaled_positions= primitive.get_scaled_positions())
         bulk.set_cell(np.diag((a, a, a)))
         phonon = Phonopy(bulk,
                          [[s,0.,0.],[0.,s,0.],[0.,0.,s]],
                          primitive_matrix=[[-0.5, 0.5, 0.5],[0.5, -0.5, 0.5],[0.5, 0.5, -0.5]],
                          distance=0.01, factor=15.633302)
         print fc
         phonon.set_force_constants(fc[0])
         phonon.set_dynamical_matrix()
         #print phonon.get_dynamical_matrix_at_q([0,0,0])
         mesh = [200, 200, 200]
         phonon.set_mesh(mesh)
         qpoints, weights, frequencies, eigvecs = phonon.get_mesh()
         print frequencies
         phonon.set_total_DOS()
         
         phonon.set_thermal_properties(t_step=10,
                                       t_max=3700,
                                       t_min=0)
     elif species == 'WRe_0.03': 
         fc = vasp.get_force_constants_vasprun_xml(vasprun,2,0)
         s = 2.
         a = superc.get_cell()[0][0]*2.
         print a
         bulk = PhonopyAtoms(symbols=['W'] * 1,
                             scaled_positions= primitive.get_scaled_positions())
         bulk.set_cell(np.diag((a, a, a)))
         phonon = Phonopy(bulk,
                          [[s,0.,0.],[0.,s,0.],[0.,0.,s]],
                          primitive_matrix=[[-0.5, 0.5, 0.5],[0.5, -0.5, 0.5],[0.5, 0.5, -0.5]],
                          distance=0.01, factor=15.633302)
         print fc
         phonon.set_force_constants(fc[0])
         phonon.set_dynamical_matrix()
         #print phonon.get_dynamical_matrix_at_q([0,0,0])
         mesh = [100, 100, 100]
         phonon.set_mesh(mesh)
         qpoints, weights, frequencies, eigvecs = phonon.get_mesh()
         print frequencies
         phonon.set_total_DOS()
         
         phonon.set_thermal_properties(t_step=10,
                                       t_max=3700,
                                       t_min=0)
     elif species == 'WRe_0.06': 
         fc = vasp.get_force_constants_vasprun_xml(vasprun,3,0)
         s = 2.
         a = superc.get_cell()[0][0]*2.
         print a
         bulk = PhonopyAtoms(symbols=['W'] * 1,
                             scaled_positions= primitive.get_scaled_positions())
         bulk.set_cell(np.diag((a, a, a)))
         phonon = Phonopy(bulk,
                          [[s,0.,0.],[0.,s,0.],[0.,0.,s]],
                          primitive_matrix=[[-0.5, 0.5, 0.5],[0.5, -0.5, 0.5],[0.5, 0.5, -0.5]],
                          distance=0.01, factor=15.633302)
         print fc
         phonon.set_force_constants(fc[0])
         phonon.set_dynamical_matrix()
         #print phonon.get_dynamical_matrix_at_q([0,0,0])
         mesh = [100, 100, 100]
         phonon.set_mesh(mesh)
         qpoints, weights, frequencies, eigvecs = phonon.get_mesh()
         print frequencies
         phonon.set_total_DOS()
         
         phonon.set_thermal_properties(t_step=10,
                                       t_max=3700,
                                       t_min=0)
     
     elif species == 'WRe_0.09': 
         fc = vasp.get_force_constants_vasprun_xml(vasprun,4,0)
         s = 2.
         a = superc.get_cell()[0][0]*2.
         print a
         bulk = PhonopyAtoms(symbols=['W'] * 1,
                             scaled_positions= primitive.get_scaled_positions())
         bulk.set_cell(np.diag((a, a, a)))
         phonon = Phonopy(bulk,
                          [[s,0.,0.],[0.,s,0.],[0.,0.,s]],
                          primitive_matrix=[[-0.5, 0.5, 0.5],[0.5, -0.5, 0.5],[0.5, 0.5, -0.5]],
                          distance=0.01, factor=15.633302)
         print fc
         phonon.set_force_constants(fc[0])
         phonon.set_dynamical_matrix()
         #print phonon.get_dynamical_matrix_at_q([0,0,0])
         mesh = [100, 100, 100]
         phonon.set_mesh(mesh)
         qpoints, weights, frequencies, eigvecs = phonon.get_mesh()
         print frequencies
         phonon.set_total_DOS()
         
         phonon.set_thermal_properties(t_step=10,
                                       t_max=3700,
                                       t_min=0)
     elif species == 'WRe_0.12': 
         fc = vasp.get_force_constants_vasprun_xml(vasprun,5,0)
         s = 2.
         a = superc.get_cell()[0][0]*2.
         print a
         bulk = PhonopyAtoms(symbols=['W'] * 1,
                             scaled_positions= primitive.get_scaled_positions())
         bulk.set_cell(np.diag((a, a, a)))
         phonon = Phonopy(bulk,
                          [[s,0.,0.],[0.,s,0.],[0.,0.,s]],
                          primitive_matrix=[[-0.5, 0.5, 0.5],[0.5, -0.5, 0.5],[0.5, 0.5, -0.5]],
                          distance=0.01, factor=15.633302)
         print fc
         phonon.set_force_constants(fc[0])
         phonon.set_dynamical_matrix()
         #print phonon.get_dynamical_matrix_at_q([0,0,0])
         mesh = [100, 100, 100]
         phonon.set_mesh(mesh)
         qpoints, weights, frequencies, eigvecs = phonon.get_mesh()
         print frequencies
         phonon.set_total_DOS()
         
         phonon.set_thermal_properties(t_step=10,
                                       t_max=3700,
                                       t_min=0)
     
     elif species == 'WRe_0.18': 
         fc = vasp.get_force_constants_vasprun_xml(vasprun,6,0)
         s = 2.
         a = superc.get_cell()[0][0]*2.
         print a
         bulk = PhonopyAtoms(symbols=['W'] * 1,
                             scaled_positions= primitive.get_scaled_positions())
         bulk.set_cell(np.diag((a, a, a)))
         phonon = Phonopy(bulk,
                          [[s,0.,0.],[0.,s,0.],[0.,0.,s]],
                          primitive_matrix=[[-0.5, 0.5, 0.5],[0.5, -0.5, 0.5],[0.5, 0.5, -0.5]],
                          distance=0.01, factor=15.633302)
         print fc
         phonon.set_force_constants(fc[0])
         phonon.set_dynamical_matrix()
         #print phonon.get_dynamical_matrix_at_q([0,0,0])
         mesh = [100, 100, 100]
         phonon.set_mesh(mesh)
         qpoints, weights, frequencies, eigvecs = phonon.get_mesh()
         print frequencies
         phonon.set_total_DOS()
         
         phonon.set_thermal_properties(t_step=10,
                                       t_max=3700,
                                       t_min=0)
     elif species == 'WRe_0.25': 
         fc = vasp.get_force_constants_vasprun_xml(vasprun,7,0)
         s = 2.
         a = primitive.get_cell()[0][0]*2.
         print a, primitive.get_scaled_positions()
         bulk = PhonopyAtoms(symbols=['W'] * 1,
                             scaled_positions= primitive.get_scaled_positions())
         bulk.set_cell(np.diag((a, a, a)))
         phonon = Phonopy(bulk,
                          [[s,0.,0.],[0.,s,0.],[0.,0.,s]],
                          primitive_matrix=[[-0.5, 0.5, 0.5],[0.5, -0.5, 0.5],[0.5, 0.5, -0.5]],
                          distance=0.01, factor=15.633302)
         print fc
         phonon.set_force_constants(fc[0])
         phonon.set_dynamical_matrix()
         #print phonon.get_dynamical_matrix_at_q([0,0,0])
         mesh = [100, 100, 100]
         phonon.set_mesh(mesh)
         qpoints, weights, frequencies, eigvecs = phonon.get_mesh()
         print frequencies
         phonon.set_total_DOS()
         #phonon.set_partial_DOS()
         phonon.set_thermal_properties(t_step=10,
                                       t_max=3700,
                                       t_min=0)    
     
     elif species == 'WRe_0.50': 
         fc = vasp.get_force_constants_vasprun_xml(vasprun,8,0)
         s = 2.
         a = superc.get_cell()[0][0]*2.
         print a
         bulk = PhonopyAtoms(symbols=['W'] * 1,
                             scaled_positions= primitive.get_scaled_positions())
         bulk.set_cell(np.diag((a, a, a)))
         phonon = Phonopy(bulk,
                          [[s,0.,0.],[0.,s,0.],[0.,0.,s]],
                          primitive_matrix=[[-0.5, 0.5, 0.5],[0.5, -0.5, 0.5],[0.5, 0.5, -0.5]],
                          distance=0.01, factor=15.633302)
         #print fc
         phonon.set_force_constants(fc[0])
         phonon.set_dynamical_matrix()
         #print phonon.get_dynamical_matrix_at_q([0,0,0])
         mesh = [100, 100, 100]
         phonon.set_mesh(mesh)
         qpoints, weights, frequencies, eigvecs = phonon.get_mesh()
         #print frequencies
         phonon.set_total_DOS()
         #phonon.set_partial_DOS()
         phonon.set_thermal_properties(t_step=10,
                                       t_max=3700,
                                       t_min=0)    
         
         
     elif species == 'Au': 
         fc = vasp.get_force_constants_vasprun_xml(vasprun,1,0)
         #Gold
         s = 5.
         a = superc.get_cell()[0][0]
         bulk = PhonopyAtoms(symbols=['Au'] * 1,
                             scaled_positions= primitive.get_scaled_positions())
         bulk.set_cell(np.diag((a, a, a)))
         phonon = Phonopy(bulk,
                          [[s,0.,0.],[0.,s,0.],[0.,0.,s]],
                          primitive_matrix=[[0.5, 0.5, 0.0],[0.0, 0.5, 0.5],[0.5, 0.0, 0.5]],
                          distance=0.01, factor=15.633302)
         
         phonon.set_force_constants(fc[0])
         phonon.set_dynamical_matrix()
         #print phonon.get_dynamical_matrix_at_q([0,0,0])
         mesh = [100, 100, 100]
         phonon.set_mesh(mesh)
         qpoints, weights, frequencies, eigvecs = phonon.get_mesh()
         print frequencies
         phonon.set_total_DOS()
         phonon.set_partial_DOS()
         phonon.set_thermal_properties(t_step=10,
                                       t_max=1300,
                                       t_min=0)
     
     elif species == 'Mo': 
         fc = vasp.get_force_constants_vasprun_xml(vasprun,10,0)
         s = 5.
         a = superc.get_cell()[0][0]*2.
         print a
         bulk = PhonopyAtoms(symbols=['Mo'] * 1,
                             scaled_positions= primitive.get_scaled_positions())
         bulk.set_cell(np.diag((a, a, a)))
         phonon = Phonopy(bulk,
                          [[s,0.,0.],[0.,s,0.],[0.,0.,s]],
                          primitive_matrix=[[-0.5, 0.5, 0.5],[0.5, -0.5, 0.5],[0.5, 0.5, -0.5]],
                          distance=0.01, factor=15.633302)
         print fc
         phonon.set_force_constants(fc[0])
         phonon.set_dynamical_matrix()
         #print phonon.get_dynamical_matrix_at_q([0,0,0])
         mesh = [100, 100, 100]
         phonon.set_mesh(mesh)
         qpoints, weights, frequencies, eigvecs = phonon.get_mesh()
         print frequencies
         phonon.set_total_DOS()
         
         phonon.set_thermal_properties(t_step=10,
                                       t_max=2500,
                                       t_min=0)
     
     
     elif species == 'Re': 
         fc = vasp.get_force_constants_vasprun_xml(vasprun,9,0)
         s = 5.
         a = superc.get_cell()[0][0]*2.
         print a
         bulk = PhonopyAtoms(symbols=['Re'] * 1,
                             scaled_positions= primitive.get_scaled_positions())
         bulk.set_cell(np.diag((a, a, a)))
         phonon = Phonopy(bulk,
                          [[s,0.,0.],[0.,s,0.],[0.,0.,s]],
                          primitive_matrix=[[-0.5, 0.5, 0.5],[0.5, -0.5, 0.5],[0.5, 0.5, -0.5]],
                          distance=0.01, factor=15.633302)
         print fc
         phonon.set_force_constants(fc[0])
         phonon.set_dynamical_matrix()
         #print phonon.get_dynamical_matrix_at_q([0,0,0])
         mesh = [100, 100, 100]
         phonon.set_mesh(mesh)
         qpoints, weights, frequencies, eigvecs = phonon.get_mesh()
         print frequencies
         phonon.set_total_DOS()
         
         phonon.set_thermal_properties(t_step=10,
                                       t_max=2500,
                                       t_min=0)
     
     
     f = open('F_TV','w')
     for t, free_energy, entropy, cv in np.array(phonon.get_thermal_properties()).T:
         #print t, cv
         #print ("%12.3f " + "%15.7f" * 3) % ( t, free_energy, entropy, cv )
         f.write(("%12.3f " + "%15.7f" + "\n") % ( t, free_energy))
     f.close()
     
     fc = open('thermal_properties','w')
     for t, free_energy, entropy, cv in np.array(phonon.get_thermal_properties()).T:
         fc.write(("%12.3f " + "%15.7f" *3 + "\n") % ( t, free_energy, entropy, cv ))
     fc.close()
     
     #phonon.plot_thermal_properties().show()
     
     #phonon.plot_total_DOS().show()
     phonon.write_total_DOS()
     #phonon.write_partial_DOS()
     phonon.write_yaml_thermal_properties()
     
     bands = []
     
     #### PRIMITIVE
     
     q_start  = np.array([0.0, 0.0, 0.0])
     #q_start  = np.array([0.5, 0.5, 0.0])
     q_end    = np.array([-0.5, 0.5, 0.5])
     #q_end    = np.array([0., 0., 0.])
     band = []
     for i in range(101):
         band.append(q_start + (q_end - q_start) / 100 * i)
     bands.append(band)
     
     band = []
     
     
     q_start  = np.array([-0.5, 0.5, 0.5])
     #q_start  = np.array([0., 0., 0.])
     q_end    = np.array([0.25, 0.25, 0.25])
     #q_end    = np.array([1., 0., 0.])
     
     for i in range(101):
         #band.append([-0.5+3*1/400*i, 0.5-1/400*i, 0.5-1/400*i])
         band.append(q_start + (q_end - q_start) / 100 * i)
     bands.append(band)
     #print band
     q_start  = np.array([0.25, 0.25, 0.25])
     q_end    = np.array([0., 0., 0.])
     band = []
     for i in range(101):
         band.append(q_start + (q_end - q_start) / 100 * i)
     bands.append(band)
     
     q_start  = np.array([0., 0., 0.])
     q_end    = np.array([0.0, 0., 0.5])
     band = []
     for i in range(101):
         band.append(q_start + (q_end - q_start) / 100 * i)
     bands.append(band)
     
     #q_start  = np.array([0.0, 0.0, 0.0])
     #q_end    = np.array([0.5, 0.5, 0.5])
     #band = []
     #for i in range(101):
     #    band.append(q_start + (q_end - q_start) / 100 * i)
     #bands.append(band)
     
     """
     ###### CONVENTIONAL CELL ######
     q_start  = np.array([0.0, 0.0, 0.0])
     q_end    = np.array([-0.5, 0.5, 0.5])
     band = []
     for i in range(101):
         band.append(q_start + (q_end - q_start) / 100 * i)
     bands.append(band)
     
     
     q_start  = np.array([-0.5, 0.5, 0.5])
     q_end    = np.array([1./4., 1./4., 1./4.])
     band = []
     for i in range(101):
         band.append(q_start + (q_end - q_start) / 100 * i)
     bands.append(band)
     q_start  = np.array([1./4., 1./4., 1./4.])
     q_end    = np.array([0.0, 0.0, 0.0])
     band = []
     for i in range(101):
         band.append(q_start + (q_end - q_start) / 100 * i)
     bands.append(band)
     q_start  = np.array([0.0, 0.0, 0.0])
     q_end    = np.array([0.5, 0.0, 0.0])
     band = []
     for i in range(101):
         band.append(q_start + (q_end - q_start) / 100 * i)
     bands.append(band)
     """
     phonon.set_band_structure(bands)
     #phonon.plot_band_structure().show()
     
     q_points, distances, frequencies, eigvecs = phonon.get_band_structure()
     disp = {'q':q_points, 'distances':distances, 'frequencies':frequencies, 'eigvecs':eigvecs}
     f = open('ph_dispersion.pkl','w')
     pickle.dump(disp, f)
     f.close()
Beispiel #42
0
def distribute_forces( supercell, disp, forces, filename, symprec ):
    natom = supercell.get_number_of_atoms()
    lattice = supercell.get_cell()
    symbols = supercell.get_chemical_symbols()
    positions = supercell.get_positions()
    positions[disp[0]] += disp[1]
    cell = Atoms( cell=lattice,
                  positions=positions,
                  symbols=symbols,
                  pbc=True )
    symmetry = Symmetry( cell, symprec )
    independent_atoms = symmetry.get_independent_atoms()

    # Rotation matrices in Cartesian
    rotations = []
    for r in symmetry.get_symmetry_operations()['rotations']:
        rotations.append( similarity_transformation( lattice.T, r ) )

    map_operations = symmetry.get_map_operations()
    map_atoms = symmetry.get_map_atoms()

    atoms_in_dot_scf = get_independent_atoms_in_dot_scf( filename )

    if not len( forces ) == len( atoms_in_dot_scf ):
        print "%s does not contain necessary information." % filename
        print "Plese check if there are \"FGL\" lines with"
        print "\"total forces\" are required." 
        return False
    
    if len( atoms_in_dot_scf ) == natom:
        print "It is assumed that there is no symmetrically-equivalent atoms in "
        print "\'%s\' at wien2k calculation." % filename
        print ""
        force_set = forces
    elif not len( forces ) == len( independent_atoms ):
        print "Non-equivalent atoms of %s could not be recognized by phonopy." % filename
        return False
    else:
        # 1. Transform wien2k forces to those on independent atoms
        indep_atoms_to_wien2k = []
        forces_remap = []
        for i, pos_wien2k in enumerate( atoms_in_dot_scf ):
            for j, pos in enumerate( cell.get_scaled_positions() ):
                diff = pos_wien2k - pos
                diff -= np.rint(diff)
                if ( abs( diff ) < 0.00001 ).all():
                    forces_remap.append(
                        np.dot( forces[ i ], rotations[ map_operations[ j ] ].T ) )
                    indep_atoms_to_wien2k.append( map_atoms[ j ] )
                    break
                
        if not len( forces_remap ) == len( forces ):
            print "Atomic position mapping between Wien2k and phonopy failed."
            print "If you think this is caused by a bug of phonopy"
            print "please report it in the phonopy mainling list."
            return False
 
        # 2. Distribute forces from independent to dependent atoms.
        force_set = []
        for i in range( natom ):
            force_set.append( np.dot(
                    forces_remap[ indep_atoms_to_wien2k.index( map_atoms[i] ) ],
                    rotations[ map_operations[i] ] ) )

    return force_set
Beispiel #43
0
import phonopy.interface.vasp as vasp
import numpy as np
import lxml.etree as etree
from phonopy import Phonopy
from phonopy.structure.atoms import Atoms as PhonopyAtoms


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

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

print superc.get_scaled_positions()

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

phonon.set_force_constants(fc)

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


phonon.set_total_DOS()
phonon.plot_total_DOS().show()