예제 #1
0
 def setUp(self):
     self.gnd_real = pmg.Structure.from_file(TEST_FILES / 'POSCAR.C0.gz')
     self.exd_real = pmg.Structure.from_file(TEST_FILES / 'POSCAR.C-.gz')
     self.gnd_test = pmg.Structure(pmg.Lattice.cubic(1.), ['H'],
                                   [[0., 0., 0.]])
     self.exd_test = pmg.Structure(pmg.Lattice.cubic(1.), ['H'],
                                   [[0.5, 0.5, 0.5]])
     self.sct_test = pmg.Structure(pmg.Lattice.cubic(1.), ['H'],
                                   [[0.25, 0.25, 0.25]])
     self.vrs = [TEST_FILES / 'vasprun.xml.0.gz'] + \
         glob.glob(str(TEST_FILES / 'lower' / '*' / 'vasprun.xml.gz'))
예제 #2
0
def MAST2Structure(lattice=None,
                   coordinates=None,
                   atom_list=None,
                   coord_type='fractional'):
    """Helper function for converting input options into a pymatgen Structure object"""
    if (coord_type.lower() == 'fractional'):
        return pmg.Structure(lattice, atom_list, coordinates)
    elif (coord_type.lower() == 'cartesian'):
        return pmg.Structure(lattice,
                             atom_list,
                             coordinates,
                             coords_are_cartesian=True)
예제 #3
0
    def _parse_structure(self, xml_structure, xml_lattice):
        coordinates = []
        symbols = []
        for atom in xml_structure:
            symbols.append(atom.attrib["elementType"])
            coordinates.append(
                [atom.attrib["x3"], atom.attrib["y3"], atom.attrib["z3"]])
        coordinates = np.array(coordinates).reshape(-1, 3).astype(float)

        namespaces = {'xml': 'http://www.xml-cml.org/schema'}
        XML_LATTICE_LENGTHS = './xml:cellParameter[@parameterType="length"]'
        XML_LATTICE_ANGLES = './xml:cellParameter[@parameterType="angle"]'
        lattice_lengths = [
            float(_)
            for _ in xml_lattice.find(XML_LATTICE_LENGTHS,
                                      namespaces=namespaces).text.split()
        ]
        lattice_angles = [
            float(_)
            for _ in xml_lattice.find(XML_LATTICE_ANGLES,
                                      namespaces=namespaces).text.split()
        ]

        lattice = pmg.Lattice.from_parameters(*lattice_lengths,
                                              *lattice_angles)
        return pmg.Structure(lattice,
                             symbols,
                             coordinates,
                             coords_are_cartesian=True)
예제 #4
0
def test_show_pymatgen():
    import pymatgen as mg
    lattice = mg.Lattice.cubic(4.2)
    structure = mg.Structure(lattice, ["Cs", "Cl"],
                             [[0, 0, 0], [0.5, 0.5, 0.5]])
    view = nv.show_pymatgen(structure)
    view
예제 #5
0
def Structure_start(sn, fn, coords):
    'Write lattice, elements, coords to pymatgen structure; returns pymatgen structure.'
    if sn.Lattice.size == 6:  #tests for lattice vectors or parameters
        lattice = mg.Lattice.from_parameters(sn.Lattice[0][0],sn.Lattice[0][1],sn.Lattice[0][2],\
                                         sn.Lattice[1][0],sn.Lattice[1][1],sn.Lattice[1][2])
    else:
        lattice = sn.Lattice
    wn = 6  #the (max) number of water molecules. This part handles missing waters.
    for i in [sn.L1, sn.L2, sn.L3]:
        for j in [i.W1, i.W2]:
            if True in np.isnan(j):
                wn -= 1
            else:
                pass
    #Writes the list of atoms by element, which must be in the same order as the list of coordinates.
    On = wn + 45
    Hn = (wn * 2) + 36
    atoms = []
    for i in range(On):
        atoms.append('O')
    for i in range(Hn):
        atoms.append('H')
    for i in range(6):
        atoms.append('Li')
    for i in range(12):
        atoms.append('Al')
    for i in range(3):
        atoms.append('C')
    s = mg.Structure(lattice, atoms, coords)  #makes the pymatgen structure
    return s
예제 #6
0
def Layer_transform(s, sn):
    'This takes the previous M+ layer and transforms it according to the symmetry genes.'
    #define symmop as mg.symmop, then apply using s.apply(symop)
    lat = s.lattice; atoms = s.species; coords = s.frac_coords
    s1 = mg.Structure(lat, atoms, coords)
    i = sn.Polytope.Symmetry #rotate by Cn, translate by (x,y) vector
    if i.Cn == 0: Cn = 0
    else: Cn = 360/i.Cn
    so = mg.SymmOp.from_axis_angle_and_translation(axis=[0,0,1], angle=Cn,\
                                                   translation_vec=(i.Tx,i.Ty,0))
    s1.apply_operation(so, fractional=True)
    #reflect across xy plane
    if i.Sz == 1:
        so = mg.SymmOp.reflection([0,0,1], origin=(0.5,0.5,0.5))
        s1.apply_operation(so, fractional=True)
    else: pass
    #reflect across xz or yz plane
    if i.Sxy == 0: pass
    else:
        if i.Sxy < 0: #zx plane
            nd = (0,1)
        elif i.Sxy > 0: #zy plane
            nd = (1,0)
        so = mg.SymmOp.reflection([nd[0],nd[1],0],origin=(0.5,0.5,0.5))
        s1.apply_operation(so, fractional=True)
    lat = s1.lattice; atoms = s1.species; coords = s1.frac_coords
    snew = mg.IStructure(lat, atoms, coords, to_unit_cell=True)
    return snew
예제 #7
0
    def get_supercell(self, sc, vac=[0, 0, 0]):
        '''
         Input-
         sc:super cell lattice 3x3 
         vaccume: 1x3
         returns: pymatgen structure
         
         usefull for making use of pymatgen's codes for making finite complex slabs and defects
        '''
        try:
            import pymatgen as p
        except:
            print("Needs pymatgen please install using pip install pymatgen")
        new_s = p.Structure(lattice=self.get_lattice(),
                            species=[i.element for i in self.atoms],
                            coords=[list(i.pos) for i in self.atoms])
        new_s.make_supercell(sc)

        def get_vaccume(s, vac):
            abc = np.add([new_s.lattice.a, new_s.lattice.b, new_s.lattice.c],
                         vac)
            ang = new_s.lattice.angles
            l = p.core.lattice.Lattice.from_parameters(a=abc[0],
                                                       b=abc[1],
                                                       c=abc[2],
                                                       alpha=ang[0],
                                                       beta=ang[1],
                                                       gamma=ang[2])
            return p.Structure(lattice=l,
                               species=new_s.species,
                               coords=new_s.frac_coords)

        final = get_vaccume(new_s, vac)
        return final
예제 #8
0
    def create_pure_structure(self,
                              oxidation_states,
                              basic_atoms,
                              noCells,
                              lattice_system='cubic',
                              lattice_lengths=None,
                              lattice_angles=None,
                              supercell=False):
        """Creates pure structure given input parameters.

        """

        oxidationA = oxidation_states[0]
        oxidationB = oxidation_states[1]
        oxidationC = oxidation_states[2]

        dopantAtoms = []
        noDopants = []
        noVacancies = []
        noInterstitials = []
        vacancyAtoms = []
        interstitialAtoms = []

        siteA = basic_atoms[0]
        siteB = basic_atoms[1]
        siteC = basic_atoms[2]

        atomA = mg.Element(siteA)
        atomB = mg.Element(siteB)
        atomC = mg.Element(siteC)

        if not lattice_lengths:
            ionic_radiiA = atomA.ionic_radii[oxidationA]
            ionic_radiiB = atomB.ionic_radii[oxidationB]
            ionic_radiiC = atomC.ionic_radii[oxidationC]
            latticeVal1 = 2 * (ionic_radiiA + ionic_radiiB) / math.pow(
                3, 1 / 2)
            latticeVal2 = 2 * (ionic_radiiA + ionic_radiiC) / math.pow(
                2, 1 / 2)
            latticeConst = max(latticeVal1, latticeVal2)
            latticeLength = [latticeConst, latticeConst, latticeConst]
            latticeAngles = [90, 90, 90]  # WARNING: HARD-CODE ALERT
        else:
            latticeLength = lattice_lengths
            latticeAngles = lattice_angles

        lattice = mg.Lattice.from_lengths_and_angles(latticeLength,
                                                     latticeAngles)
        structure = mg.Structure(lattice, [siteA, siteB, siteC, siteC, siteC],
                                 [[0, 0, 0], [0.5, 0.5, 0.5], [0.5, 0.5, 0],
                                  [0.5, 0, 0.5], [0, 0.5, 0.5]])
        if supercell:
            structure.make_supercell(noCells)

        keyVal = self.structureKey(lattice_system, basic_atoms, dopantAtoms,
                                   noDopants, vacancyAtoms, noVacancies,
                                   noCells, interstitialAtoms, noInterstitials)

        return structure, keyVal
예제 #9
0
def CreateTemplateStructure(strutype, size, specie):
    if strutype == 'bcc':
        lattice = [[size, 0, 0], [0, size, 0], [0, 0, size]]
        species = [specie, specie]
        coords = [[0, 0, 0], [1.0 / 2.0, 1.0 / 2.0, 1.0 / 2.0]]
        return pmg.Structure(lattice, species, coords)
    elif strutype == 'fcc':
        lattice = [[size, 0, 0], [0, size, 0], [0, 0, size]]
        species = [specie] * 4
        coords = [[0, 0, 0], [0.5, 0.5, 0], [0.5, 0, 0.5], [0, 0.5, 0.5]]
        return pmg.Structure(lattice, species, coords)
    elif strutype == 'hcp':
        lattice = [[size, 0, 0], [0, size, 0],
                   [0, 0, size * math.sqrt(6) * (2 / 3)]]
        species = [specie] * 2
        coords = [[0, 0, 0], [2.0 / 3.0, 1.0 / 3.0, 1.0 / 2.0]]
        return pmg.Structure(lattice, species, coords)
예제 #10
0
def get_distortion_dec_struct(wycks, struct_to_match, high_sym_wyckoff,
                              struct_hs):
    coords = []
    species = []
    proj_vecs = []
    wycks_done = []  # dirty maybe wrong fix
    for wyck in wycks:  # CURRENTLY ONLY ONE WYCKOFF IS PASSED AT A TIME, SO THIS IS FINE, BUT UNNECESSARY
        w = wyck["Wyckoff"]
        # PEROVSKITE SPECIFIC, AND I DON'T KNOW IF IT'S THE RIGHT THING TO DO!!!!
        if w in wycks_done:
            # print("SKIPPING duplicate instance of wyckoff {} in irrep {}, this is a perovskite specific thing, and may be wrong even here".format(w, irrep))
            # print("I believe the two sets isotropy returns are equivalent choices, but I'm not certain")
            continue
        wycks_done.append(w)  # dirty maybe wrong fix

        for i, ss in enumerate(high_sym_wyckoff):
            if ss == w:
                sp = struct_hs[i].specie
                break
        for coord, pv in zip(wyck["Point"], wyck["Projected Vectors"]):
            species.append(sp)
            coords.append(coord)
            proj_vecs.append(pv)
    logger.debug("get_distortion_dec_struct:")
    logger.debug("coords:\n{}".format(coords))
    logger.debug("species:\n{}".format(species))
    logger.debug("proj_vecs:\n{}".format(proj_vecs))
    lat = struct_to_match.lattice
    dist_struct = pmg.Structure(lat,
                                species,
                                coords,
                                site_properties={"projvecs": proj_vecs})
    logger.debug("dist_struct:\n{}".format(dist_struct))

    # sm_dist = StructureMatcher(ltol = 0.02, primitive_cell=False, allow_subset=True)
    sm_dist = ModifiedSM_I(ltol=0.02, primitive_cell=False, allow_subset=True)
    try:
        sc_d, trans_d, mapping = sm_dist.get_transformation(
            struct_to_match, dist_struct)
    except TypeError:
        logger.warning(
            "couldn't map dist decorated structure to actual structure")
        logger.warning("dist dec struct:\n{}".format(dist_struct))
        logger.warning("struct to match:\n{}".format(struct_to_match))
    logger.debug("matching dist def to struct")
    dist_struct_matched = dist_struct * sc_d
    dist_struct_matched.translate_sites(list(range(len(dist_struct_matched))),
                                        trans_d)
    logger.debug(struct_to_match)
    logger.debug(dist_struct)
    logger.debug(sc_d)
    logger.debug(trans_d)
    logger.debug(mapping)
    logger.debug(dist_struct_matched)
    logger.debug("\n")
    return dist_struct_matched, mapping
예제 #11
0
파일: GenCif.py 프로젝트: funashima/Metis
 def main(self, filename='crystal.cif'):
     a, b, c = self.configure.lattice_length[:3]
     a, b, c = [self.bohr2ang(x) for x in [a, b, c]]
     alpha, beta, gamma = self.configure.lattice_angle[:3]
     lattice = mg.Lattice.from_parameters(a, b, c, alpha, beta, gamma)
     atoms = self.configure.atom_list
     atomic_position = self.configure.atomic_position
     structure = mg.Structure(lattice, atoms, atomic_position)
     structure.to(filename=filename)
     print('generated:{}'.format(filename))
예제 #12
0
    def set_structure(self):
        #
        # ======= ATOMIC POSITIONS =======
        #
        a, b, c = self.config_obj.lattice_length[:3]
        alpha, beta, gamma = self.config_obj.lattice_angle[:3]
        lattice = mg.Lattice.from_parameters(a, b, c, alpha, beta, gamma)

        self.atoms = self.config_obj.atom_list
        atomic_positions = self.config_obj.atomic_position
        self.structure = mg.Structure(lattice, self.atoms, atomic_positions)
예제 #13
0
def calculate_standard_path(structure):
    lattice = mg.Lattice(structure.lattice_vectors)
    atoms = structure.atoms
    structure_mg = mg.Structure(lattice, atoms[:, 3], atoms[:, :3])
    hs_path = HighSymmKpath(structure_mg, symprec=0.1)

    if not hs_path.kpath:  # fix for bug in pymatgen that for certain structures no path is returned
        raise Exception('High symmetry path generation failed.')

    conv_path = convert_hs_path_to_own(hs_path)
    return conv_path
예제 #14
0
def read_structure(filename, lattice, charges):
    # Lattice was not specified in file
    # Charges supplied as dict { specie : charge }
    with open(filename) as f:
        species = []
        positions = []
        for line in f:
            specie, x, y, z = line.split()
            species.append(specie)
            positions.append([float(_) for _ in [x, y, z]])
    structure = pmg.Structure(lattice, species, positions, coords_are_cartesian=True)
    structure.add_oxidation_state_by_element(charges)
    return structure
예제 #15
0
 def get_vaccume(s, vac):
     abc = np.add([new_s.lattice.a, new_s.lattice.b, new_s.lattice.c],
                  vac)
     ang = new_s.lattice.angles
     l = p.core.lattice.Lattice.from_parameters(a=abc[0],
                                                b=abc[1],
                                                c=abc[2],
                                                alpha=ang[0],
                                                beta=ang[1],
                                                gamma=ang[2])
     return p.Structure(lattice=l,
                        species=new_s.species,
                        coords=new_s.frac_coords)
예제 #16
0
    def lattice_information(self):

        lattice = mg.Lattice(self.lattice_vectors)
        atoms = self.atoms
        if len(atoms) == 0:
            return {'space group': '', 'point group': '', 'crystal system': ''}
        structure_mg = mg.Structure(lattice, atoms[:, 3], atoms[:, :3])
        analyzer = SpacegroupAnalyzer(structure_mg)
        res = {
            'space group': analyzer.get_space_group_symbol(),
            'point group': analyzer.get_point_group_symbol(),
            'crystal system': analyzer.get_crystal_system()
        }
        return res
예제 #17
0
파일: test_ccd.py 프로젝트: tsaie79/nonrad
    def test_get_Q_from_struct(self):
        q = get_Q_from_struct(self.gnd_test, self.exd_test, self.sct_test)
        self.assertAlmostEqual(q, 0.5 * 0.86945, places=4)
        q = get_Q_from_struct(self.gnd_real, self.exd_real,
                              str(TEST_FILES / 'POSCAR.C0.gz'))
        self.assertAlmostEqual(q, 0., places=4)
        gs, es = get_cc_structures(self.gnd_real, self.exd_real,
                                   np.linspace(-0.5, 0.5, 100),
                                   remove_zero=False)
        Q = 1.68587 * np.linspace(-0.5, 0.5, 100)
        for s, q in zip(gs, Q):
            tq = get_Q_from_struct(self.gnd_real, self.exd_real, s)
            self.assertAlmostEqual(tq, q, places=4)
        for s, q in zip(es, Q + 1.68587):
            tq = get_Q_from_struct(self.gnd_real, self.exd_real, s)
            self.assertAlmostEqual(tq, q, places=4)

        # test when one of the coordinates stays the same
        sg = pmg.Structure(np.eye(3), ['H'], [[0.0, 0.0, 0.0]])
        sq = pmg.Structure(np.eye(3), ['H'], [[0.1, 0.0, 0.1]])
        se = pmg.Structure(np.eye(3), ['H'], [[0.2, 0.0, 0.2]])
        dQ = get_dQ(sg, se)
        self.assertAlmostEqual(get_Q_from_struct(sg, se, sq)/dQ, 0.5)
예제 #18
0
def get_structure(filename):
    if filename.lower().endswith('.cif'):
        structure = CifParser(filename).get_structures()[0]
        lattice = pmg.Lattice.from_parameters(*structure.lattice.abc,
                                              *structure.lattice.angles)
        return pmg.Structure(lattice,
                             structure.species,
                             structure.frac_coords,
                             coords_are_cartesian=False)
    elif filename.lower().endswith('poscar'):
        return Poscar.from_file(filename).structure
    else:
        raise ValueError(
            'Cannot determine file type from filename [.cif, poscar]')
예제 #19
0
 def _parse_structure(self, structure_schema):
     data = structure_schema['data']
     format = structure_schema['format']
     if format == 'cif':
         # cif lattice can be weird non standard shape
         structure = (CifParser.from_string(data)).get_structures()[0]
         lattice = pmg.Lattice.from_parameters(*structure.lattice.abc,
                                               *structure.lattice.angles)
         structure = pmg.Structure(lattice,
                                   structure.species,
                                   structure.frac_coords,
                                   coords_are_cartesian=False)
     elif format == 'POSCAR':
         structure = (Poscar.from_string(data)).structure
     return structure
예제 #20
0
def dump(system, symbols=None):
    """
    Convert an atomman.System into a pymatgen.Structure.
    
    Parameters
    ----------
    system : atomman.System
        A atomman representation of a system.
    symbols : tuple, optional
        List of the element symbols that correspond to the atom types.  If not
        given, will use system.symbols if set, otherwise no element content
        will be included.
    
    Returns
    -------
    structure : pymatgen.Structure
        A pymatgen representation of a structure.
    """

    assert has_pmg, 'pymatgen not imported'

    # Get box/lattice information
    lattice = pmg.Lattice(system.box.vects)

    # Get symbols information
    if symbols is None:
        symbols = system.symbols
    symbols = np.asarray(symbols)
    if None in symbols:
        raise ValueError('Symbols needed for all atypes')

    # Convert short symbols list to full species list
    atype = system.atoms.atype
    species = symbols[atype - 1]

    # Get atomic information
    sites = system.atoms_prop(key='pos', scale=True)
    prop = {}
    for p in system.atoms_prop():
        if p != 'atype' and p != 'pos':
            prop[p] = system.atoms_prop(key=p)

    # Build structure
    structure = pmg.Structure(lattice, species, sites, site_properties=prop)

    return structure
예제 #21
0
def to_pymatgen(mol):
    """
    Creates a pymatgen structure object from a mol object
    :Parameters:
        - mol: mol object
    """
    try:
        import pymatgen as mg
    except ImportError:
        logger.error("Pymatgen not available!")
        exit()
    latt = mg.Lattice.from_parameters(*mol.get_cellparams())
    elems = mol.get_elems()
    nelems = []
    for e in elems:
        nelems.append(e.title())
    structure = mg.Structure(latt, nelems, mol.get_frac_xyz())
    return structure
예제 #22
0
def Layer_A(sn, layer):
    'Generates A- layers.'
    atoms = ['C', 'O', 'O', 'O']
    lat, g = setlat(sn)
    coords = C_positions(sn, layer) #start the carbonate with C, then with O.
    oc, oa = O_positions(sn, layer, lat, g)
    for i in oc:
        coords.append(i)
    if len(oa): #only add water atoms if O_pos found water in layer
        for i in oa:
            atoms.append(i)
        hc, ha = H_positions(sn, layer, lat, g)
        for i in hc:
            coords.append(i)
        for i in ha:
            atoms.append(i)
    else: pass
    s = mg.Structure(lat, atoms, coords)
    return s
예제 #23
0
파일: caesar.py 프로젝트: jrbp/caesar_py
def readCaesarEquilibriumStructure(equilibrium_dat,
                                   lattice_dat,
                                   get_spins=True):
    """
    Helper method for reading structures written by caesar
    Args:
        equilibrium_dat:
            dat file containing atomic positions
        lattice_dat:
            dat file containing lattice
        get_spins:
            whether or not to read spins from equilibrium_dat (default is True) 

    Returns:
        if get_spins==True:
            returns a tuple (structure, masses, spins) where structure is a pymatgen structure and masses, spins are numpy arrays
        if get_spins==False:
            returns a tuple (structure, masses) where structure is a pymatgen structure and masses is a numpy array
    """
    latdat = np.genfromtxt(lattice_dat)
    lattice = pmg.Lattice(BOHR_TO_ANG * latdat)
    with open(equilibrium_dat) as f:
        num_sites = int(f.readline())
        species = []
        coords = []
        spins = []
        masses = []
        for i in range(num_sites):
            line = f.readline().strip('\n').split()
            species.append(line[0])
            coords.append(line[2:5])
            if get_spins:
                spins.append(float(line[-1]))
            masses.append(float(line[1]))
        coords = np.array(coords, dtype=float) * BOHR_TO_ANG
    structure = pmg.Structure(lattice,
                              species,
                              coords,
                              coords_are_cartesian=True)
    if get_spins:
        return (structure, masses, spins)
    else:
        return (structure, masses)
예제 #24
0
def match_structures(s1, s2, scale_lattice=False, rh_only=True):
    """
    Args
        s1: high sym structure
        s2: low sym structure
        scale_lattice (optional): high_sym_superlcell has same lattice vectors as s2 (no strain)
    Returns
        basis: should be the basis that when applied to s1 makes a supercell of the size and orentation of s2
        origin: any additional translation to best match (applied before applying the basis change to match what isotropy does)
        displacements
        high_sym_supercell
"""
    sm = StructureMatcher(ltol=0.3,
                          stol=0.3,
                          angle_tol=15,
                          scale=True,
                          attempt_supercell=True,
                          primitive_cell=False)
    basis, origin, mapping = sm.get_transformation(s1, s2, rh_only=rh_only)

    struct_hs_supercell = sm.get_s2_like_s1(s1, s2, rh_only=rh_only)

    # change origin from the supercell basis to the high sym basis
    origin = np.round_(frac_vec_convert(origin, struct_hs_supercell.lattice,
                                        s2.lattice),
                       decimals=5)
    if scale_lattice:
        hs_lat = struct_hs_supercell.lattice
        hs_std = pmg.Lattice.from_lengths_and_angles(hs_lat.abc, hs_lat.angles)
        ls_lat = s2.lattice
        ls_std = pmg.Lattice.from_lengths_and_angles(ls_lat.abc, ls_lat.angles)
        for aligned, rot, scale in hs_lat.find_all_mappings(hs_std):
            if (abs(aligned.matrix - hs_lat.matrix) < 1.e-3).all():
                strained_hs_lattice = pmg.Lattice(np.inner(ls_std.matrix, rot))
        struct_hs_supercell = pmg.Structure(
            strained_hs_lattice, struct_hs_supercell.species,
            [site.frac_coords for site in struct_hs_supercell])
    displacements = []
    for s_hs, s_ls in zip(struct_hs_supercell, s1):
        disp = np.round_(smallest_disp(s_hs.frac_coords, s_ls.frac_coords),
                         decimals=5)
        displacements.append(disp)
    return basis, origin, displacements, struct_hs_supercell
예제 #25
0
    def poscar(self,
               perturb_dist=0.0,
               comment='Automatically generated POSCAR'):
        structure = mg.Structure(
            self._lattice,
            self._site_species_list(),
            self._site_position_list(),
        )

        poscar = mg.io.vaspio.Poscar(
            structure,
            comment,
            selective_dynamics=self._site_dynamics_list(),
            velocities=self._site_velocity_list()
            if self.has_velocity() else None,
        )

        poscar.structure.perturb(perturb_dist)

        return poscar
예제 #26
0
파일: utils.py 프로젝트: usccolumbia/icsg3d
def to_pymatgen_structure(lattice_params, coords, alpha=90, beta=90, gamma=90):
    """ Convert lattice params and coords to pymatgen """
    species = [c[0] for c in coords]
    positions = np.array([c[1:] for c in coords])

    # Create a lattice to place the sites
    lattice = mg.Lattice.from_parameters(*lattice_params,
                                         alpha=90,
                                         beta=90,
                                         gamma=90)

    # Create the structure
    structure = mg.Structure(lattice,
                             species,
                             positions,
                             coords_are_cartesian=True)
    new_lattice = mg.Lattice.from_parameters(*lattice_params,
                                             alpha=alpha,
                                             beta=beta,
                                             gamma=gamma)
    structure.lattice = new_lattice
    return structure
예제 #27
0
def read_lammps_dump_file(filename=''):
    ''' Attributes: path of a LAMMPS dump file
        Returns: pymatgen structure of final relaxed structure.
        '''
    dump = parse_lammps_dumps(filename)
    for i in dump:
        a = i
    lattice = a.box.to_lattice()
    df = a.data.sort_values(by=['id'])

    element_array = []
    for i in df['type'].tolist():
        if i == 1:
            element_array.append('Al')
        if i == 2:
            element_array.append('N')
        if i == 3:
            element_array.append('Ti')

    cord_np = df[['xs', 'ys', 'zs']].values
    pymatgen_struct = mg.Structure(lattice, element_array, cord_np)
    return pymatgen_struct
예제 #28
0
    def inner(projections_dict={'kind_name': 'As', 'ang_mtm_name': 'sp3'}):
        from aiida.orm import DataFactory, CalculationFactory
        from aiida_wannier90.orbitals import generate_projections

        res = dict()

        a = 5.367 * pymatgen.core.units.bohr_to_ang
        structure_pmg = pymatgen.Structure(lattice=[[-a, 0, a], [0, a, a],
                                                    [-a, a, 0]],
                                           species=['Ga', 'As'],
                                           coords=[[0] * 3, [0.25] * 3])
        structure = DataFactory('structure')()
        structure.set_pymatgen_structure(structure_pmg)
        res['structure'] = structure

        res['projections'] = generate_projections(projections_dict,
                                                  structure=structure)

        KpointsData = DataFactory('array.kpoints')
        kpoints = KpointsData()
        kpoints.set_kpoints_mesh([2, 2, 2])
        res['kpoints'] = kpoints

        kpoint_path_tmp = KpointsData()
        kpoint_path_tmp.set_cell_from_structure(structure)
        kpoint_path_tmp.set_kpoints_path()
        point_coords, path = kpoint_path_tmp.get_special_points()
        kpoint_path = DataFactory('parameter')(dict={
            'path': path,
            'point_coords': point_coords,
        })
        res['kpoint_path'] = kpoint_path

        res['parameters'] = DataFactory('parameter')(
            dict=dict(num_wann=4, num_iter=12, wvfn_formatted=True))
        return res
예제 #29
0
파일: s01-GaAs.py 프로젝트: yabeiwu/BGWpy
BGWpy relies on pymatgen.Structure objects to construct
the primitive cells for all calculations.

See http://pymatgen.org/ for more information.
"""
import os
import numpy as np
import pymatgen

# Construct the structure object.
acell_angstrom = 5.6535
rprim = np.array([[.0, .5, .5], [.5, .0, .5], [.5, .5, .0]]) * acell_angstrom
structure = pymatgen.Structure(
    lattice=pymatgen.core.lattice.Lattice(rprim),
    species=['Ga', 'As'],
    coords=[3 * [.0], 3 * [.25]],
)

# Create a directory to store the structure.
dirname = '01-GaAs'
if not os.path.exists(dirname):
    os.mkdir(dirname)

# Write file in Crystallographic Information Framework.
# This the format defined by the International Union of Crystallography.
structure.to(filename=os.path.join(dirname, 'GaAs.cif'))

# Write in json format. This is the prefered format
# since it preserves the above definition of the unit cell.
structure.to(filename=os.path.join(dirname, 'GaAs.json'))
예제 #30
0
    model_nosym = tb.Model.from_hdf5_file('data/model_nosym.hdf5')
    reference_model = tb.Model.from_hdf5_file('data/reference_model.hdf5')

    # change the order of the orbitals from (In: s, py, pz, px; As: py, pz, px) * 2
    # to (In: s, px, py, pz; As: s, px, py, pz) * 2
    model_nosym = model_nosym.slice_orbitals(
        [0, 2, 3, 1, 5, 6, 4, 7, 9, 10, 8, 12, 13, 11])

    # set up symmetry operations
    time_reversal = SymmetryOperation(rotation_matrix=np.eye(3),
                                      repr_matrix=np.kron([[0, -1j], [1j, 0]],
                                                          np.eye(7)),
                                      repr_has_cc=True)

    structure = mg.Structure(lattice=model_nosym.uc,
                             species=['In', 'As'],
                             coords=np.array([[0, 0, 0], [0.25, 0.25, 0.25]]))

    # get real-space representations
    analyzer = mg.symmetry.analyzer.SpacegroupAnalyzer(structure)
    symops = analyzer.get_symmetry_operations(cartesian=False)
    symops_cart = analyzer.get_symmetry_operations(cartesian=True)
    rots = [x.rotation_matrix for x in symops]
    taus = [x.translation_vector for x in symops]

    # get corresponding represesentations in the Hamiltonian basis
    reps = []
    for n, (rot, tau) in enumerate(zip(rots, taus)):
        C = symops_cart[n].rotation_matrix
        tauc = symops_cart[n].translation_vector
        prep = C