当前位置: 首页>>代码示例>>Python>>正文


Python SpacegroupAnalyzer.get_symmetry_operations方法代码示例

本文整理汇总了Python中pymatgen.symmetry.analyzer.SpacegroupAnalyzer.get_symmetry_operations方法的典型用法代码示例。如果您正苦于以下问题:Python SpacegroupAnalyzer.get_symmetry_operations方法的具体用法?Python SpacegroupAnalyzer.get_symmetry_operations怎么用?Python SpacegroupAnalyzer.get_symmetry_operations使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pymatgen.symmetry.analyzer.SpacegroupAnalyzer的用法示例。


在下文中一共展示了SpacegroupAnalyzer.get_symmetry_operations方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: symmetry_reduce

# 需要导入模块: from pymatgen.symmetry.analyzer import SpacegroupAnalyzer [as 别名]
# 或者: from pymatgen.symmetry.analyzer.SpacegroupAnalyzer import get_symmetry_operations [as 别名]
def symmetry_reduce(tensors, structure, tol=1e-8, **kwargs):
    """
    Function that converts a list of tensors corresponding to a structure
    and returns a dictionary consisting of unique tensor keys with symmop
    values corresponding to transformations that will result in derivative
    tensors from the original list

    Args:
        tensors (list of tensors): list of Tensor objects to test for
            symmetrically-equivalent duplicates
        structure (Structure): structure from which to get symmetry
        tol (float): tolerance for tensor equivalence
        kwargs: keyword arguments for the SpacegroupAnalyzer

    returns:
        dictionary consisting of unique tensors with symmetry operations
        corresponding to those which will reconstruct the remaining
        tensors as values
    """
    sga = SpacegroupAnalyzer(structure, **kwargs)
    symmops = sga.get_symmetry_operations(cartesian=True)
    unique_tdict = {}
    for tensor in tensors:
        is_unique = True
        for unique_tensor, symmop in itertools.product(unique_tdict, symmops):
            if (np.abs(unique_tensor.transform(symmop) - tensor) < tol).all():
                unique_tdict[unique_tensor].append(symmop)
                is_unique = False
                break
        if is_unique:
            unique_tdict[tensor] = []
    return unique_tdict
开发者ID:xhqu1981,项目名称:pymatgen,代码行数:34,代码来源:tensors.py

示例2: unique_symmetry_operations_as_vectors_from_structure

# 需要导入模块: from pymatgen.symmetry.analyzer import SpacegroupAnalyzer [as 别名]
# 或者: from pymatgen.symmetry.analyzer.SpacegroupAnalyzer import get_symmetry_operations [as 别名]
def unique_symmetry_operations_as_vectors_from_structure( structure, subset = None ):
    """
    Uses pymatgen symmetry analysis to find the minimum complete set of symmetry operations for the space group of a structure.

    Args:
        structure (pymatgen Structure): structure to be analysed.
        subset    (Optional [list]):    list of atom indices to be used for generating the symmetry operations

    Returns:
        a list of lists, containing the symmetry operations as vector mappings.
    """
    symmetry_analyzer = SpacegroupAnalyzer( structure )

    print( "The spacegroup for structure is {}".format(symmetry_analyzer.get_spacegroup_symbol()) )

    symmetry_operations = symmetry_analyzer.get_symmetry_operations()

    mappings = []
    if subset:
        species_subset = [ spec for i,spec in enumerate(structure.species) if i in subset]
        frac_coords_subset = [ coord for i, coord in enumerate( structure.frac_coords ) if i in subset ]
        mapping_structure = Structure( structure.lattice, species_subset, frac_coords_subset ) 
    else:
        mapping_structure = structure

    for symmop in symmetry_operations:
        new_structure = Structure( mapping_structure.lattice, mapping_structure.species, symmop.operate_multi( mapping_structure.frac_coords ) )
        new_mapping = [ x+1 for x in list( coord_list_mapping_pbc( new_structure.frac_coords, mapping_structure.frac_coords ) ) ]
        if new_mapping not in mappings:
            mappings.append( new_mapping )

    return mappings
开发者ID:connorourke,项目名称:bsym,代码行数:34,代码来源:pymatgen_interface.py

示例3: symm_reduce

# 需要导入模块: from pymatgen.symmetry.analyzer import SpacegroupAnalyzer [as 别名]
# 或者: from pymatgen.symmetry.analyzer.SpacegroupAnalyzer import get_symmetry_operations [as 别名]
    def symm_reduce(self, coords_set, threshold=1e-6):
        """
        Reduces the set of adsorbate sites by finding removing
        symmetrically equivalent duplicates

        Args:
            coords_set: coordinate set in cartesian coordinates
            threshold: tolerance for distance equivalence, used
                as input to in_coord_list_pbc for dupl. checking
        """
        surf_sg = SpacegroupAnalyzer(self.slab, 0.1)
        symm_ops = surf_sg.get_symmetry_operations()
        unique_coords = []
        # Convert to fractional
        coords_set = [self.slab.lattice.get_fractional_coords(coords)
                      for coords in coords_set]
        for coords in coords_set:
            incoord = False
            for op in symm_ops:
                if in_coord_list_pbc(unique_coords, op.operate(coords),
                                     atol=threshold):
                    incoord = True
                    break
            if not incoord:
                unique_coords += [coords]
        # convert back to cartesian
        return [self.slab.lattice.get_cartesian_coords(coords)
                for coords in unique_coords]
开发者ID:ExpHP,项目名称:pymatgen,代码行数:30,代码来源:adsorption.py

示例4: set_miller_family

# 需要导入模块: from pymatgen.symmetry.analyzer import SpacegroupAnalyzer [as 别名]
# 或者: from pymatgen.symmetry.analyzer.SpacegroupAnalyzer import get_symmetry_operations [as 别名]
    def set_miller_family(self):
        """
        get all miller indices for the given maximum index
        get the list of indices that correspond to the given family
        of indices
        """
        recp_structure = Structure(self.recp_lattice, ["H"], [[0, 0, 0]])
        analyzer = SpacegroupAnalyzer(recp_structure, symprec=0.001)
        symm_ops = analyzer.get_symmetry_operations()

        max_index = max(max(m) for m in self.hkl_family)
        r = list(range(-max_index, max_index + 1))
        r.reverse()
        miller_indices = []
        self.all_equiv_millers = []
        self.all_surface_energies = []
        for miller in itertools.product(r, r, r):
            if any([i != 0 for i in miller]):
                d = abs(reduce(gcd, miller))
                miller_index = tuple([int(i / d) for i in miller])
                for op in symm_ops:
                    for i, u_miller in enumerate(self.hkl_family):
                        if in_coord_list(u_miller, op.operate(miller_index)):
                            self.all_equiv_millers.append(miller_index)
                            self.all_surface_energies.append(self.surface_energies[i])
开发者ID:izxle,项目名称:MPInterfaces,代码行数:27,代码来源:nanoparticle.py

示例5: create_saturated_interstitial_structure

# 需要导入模块: from pymatgen.symmetry.analyzer import SpacegroupAnalyzer [as 别名]
# 或者: from pymatgen.symmetry.analyzer.SpacegroupAnalyzer import get_symmetry_operations [as 别名]
def create_saturated_interstitial_structure( interstitial_def, dist_tol=0.1):
    """
    this takes a Interstitial defect object and generates the
    sublattice for it based on the structure's space group.
    Useful for understanding multiplicity of an interstitial
    defect in thermodynamic analysis.

    NOTE: if large relaxation happens to interstitial or
        defect involves a complex then there may be additional
        degrees of freedom that need to be considered for
        the multiplicity.

    Args:
        dist_tol: changing distance tolerance of saturated structure,
                allowing for possibly overlapping sites
                but ensuring space group is maintained

    Returns:
        Structure object decorated with interstitial site equivalents
    """
    sga = SpacegroupAnalyzer( interstitial_def.bulk_structure.copy())
    sg_ops = sga.get_symmetry_operations( cartesian=True)

    # copy bulk structure to make saturated interstitial structure out of
    # artificially lower distance_tolerance to allow for distinct interstitials
    # with lower symmetry to be replicated - This is OK because one would never
    # actually use this structure for a practical calcualtion...
    saturated_defect_struct = interstitial_def.bulk_structure.copy()
    saturated_defect_struct.DISTANCE_TOLERANCE = dist_tol

    for sgo in sg_ops:
        new_interstit_coords = sgo.operate( interstitial_def.site.coords[:])
        poss_new_site = PeriodicSite(
                interstitial_def.site.specie,
                new_interstit_coords,
                saturated_defect_struct.lattice,
                to_unit_cell=True,
                coords_are_cartesian=True)
        try:
            #will raise value error if site already exists in structure
            saturated_defect_struct.append(
                        poss_new_site.specie, poss_new_site.coords,
                        coords_are_cartesian=True, validate_proximity=True)
        except ValueError:
            pass

    # do final space group analysis to make sure symmetry not lowered by saturating defect structure
    saturated_sga = SpacegroupAnalyzer( saturated_defect_struct)
    if saturated_sga.get_space_group_number() != sga.get_space_group_number():
        raise ValueError("Warning! Interstitial sublattice generation "
                         "has changed space group symmetry. Recommend "
                         "reducing dist_tol and trying again...")

    return saturated_defect_struct
开发者ID:materialsproject,项目名称:pymatgen,代码行数:56,代码来源:core.py

示例6: __init__

# 需要导入模块: from pymatgen.symmetry.analyzer import SpacegroupAnalyzer [as 别名]
# 或者: from pymatgen.symmetry.analyzer.SpacegroupAnalyzer import get_symmetry_operations [as 别名]
    def __init__(self, rlxd_str, nd=0.01, ns=0.08,
                 num_norm=4, num_shear=4, symmetry=False):
        """
        constructs the deformed geometries of a structure.  Generates
        m + n deformed structures according to the supplied parameters.

        Args:
            rlxd_str (structure): structure to undergo deformation, if
                fitting elastic tensor is desired, should be a geometry
                optimized structure
            nd (float): maximum perturbation applied to normal deformation
            ns (float): maximum perturbation applied to shear deformation
            m (int): number of deformation structures to generate for
                normal deformation, must be even
            n (int): number of deformation structures to generate for
                shear deformation, must be even
        """

        if num_norm % 2 != 0:
            raise ValueError("Number of normal deformations (num_norm)"
                             " must be even.")
        if num_shear % 2 != 0:
            raise ValueError("Number of shear deformations (num_shear)"
                             " must be even.")

        norm_deformations = np.linspace(-nd, nd, num=num_norm + 1)
        norm_deformations = norm_deformations[norm_deformations.nonzero()]
        shear_deformations = np.linspace(-ns, ns, num=num_shear + 1)
        shear_deformations = shear_deformations[shear_deformations.nonzero()]

        self.undeformed_structure = rlxd_str
        self.deformations = []
        self.def_structs = []

        # Generate deformations
        for ind in [(0, 0), (1, 1), (2, 2)]:
            for amount in norm_deformations:
                defo = Deformation.from_index_amount(ind, amount)
                self.deformations.append(defo)

        for ind in [(0, 1), (0, 2), (1, 2)]:
            for amount in shear_deformations:
                defo = Deformation.from_index_amount(ind, amount)
                self.deformations.append(defo)

        # Perform symmetry reduction if specified
        if symmetry:
            sga = SpacegroupAnalyzer(self.undeformed_structure, tol=0.1)
            symm_ops = sga.get_symmetry_operations(cartesian=True)
            self.deformations = symm_reduce(symm_ops, self.deformations)

        self.def_structs = [defo.apply_to_structure(rlxd_str)
                            for defo in self.deformations]
开发者ID:adozier,项目名称:pymatgen,代码行数:55,代码来源:strain.py

示例7: fit_to_structure

# 需要导入模块: from pymatgen.symmetry.analyzer import SpacegroupAnalyzer [as 别名]
# 或者: from pymatgen.symmetry.analyzer.SpacegroupAnalyzer import get_symmetry_operations [as 别名]
    def fit_to_structure(self, structure, symprec=0.1):
        """
        Returns a tensor that is invariant with respect to symmetry
        operations corresponding to a structure

        Args: 
            structure (Structure): structure from which to generate 
                symmetry operations
            symprec (float): symmetry tolerance for the Spacegroup Analyzer
                used to generate the symmetry operations
        """
        sga = SpacegroupAnalyzer(structure, symprec)
        symm_ops = sga.get_symmetry_operations(cartesian=True)
        return sum([self.transform(symm_op) for symm_op in symm_ops]) / len(symm_ops)
开发者ID:shyamd,项目名称:pymatgen,代码行数:16,代码来源:tensors.py

示例8: unique_symmetry_operations_as_vectors_from_structure

# 需要导入模块: from pymatgen.symmetry.analyzer import SpacegroupAnalyzer [as 别名]
# 或者: from pymatgen.symmetry.analyzer.SpacegroupAnalyzer import get_symmetry_operations [as 别名]
def unique_symmetry_operations_as_vectors_from_structure( structure, verbose=False, subset=None, atol=1e-5 ):
    """
    Uses `pymatgen`_ symmetry analysis to find the minimum complete set of symmetry operations for the space group of a structure.

    Args:
        structure (pymatgen ``Structure``): structure to be analysed.
        subset    (Optional [list]):        list of atom indices to be used for generating the symmetry operations.
        atol      (Optional [float]):       tolerance factor for the ``pymatgen`` `coordinate mapping`_ under each symmetry operation.

    Returns:
        (list[list]): a list of lists, containing the symmetry operations as vector mappings.

    .. _pymatgen:
        http://pymatgen.org
    .. _coordinate mapping:
        http://pymatgen.org/pymatgen.util.coord_utils.html#pymatgen.util.coord_utils.coord_list_mapping_pbc

    """
    if isinstance( structure, Structure ):
        instantiate_structure = partial( Structure, lattice=structure.lattice, coords_are_cartesian=True )
        coord_mapping = structure_cartesian_coordinates_mapping
        mapping_list = structure_mapping_list
        symmetry_analyzer = SpacegroupAnalyzer( structure )
        if verbose:
            print( "The space group for this structure is {}".format( symmetry_analyzer.get_space_group_symbol()) )
    elif isinstance( structure, Molecule ):
        instantiate_structure = Molecule
        coord_mapping = molecule_cartesian_coordinates_mapping
        mapping_list = molecule_mapping_list
        symmetry_analyzer = PointGroupAnalyzer( structure, tolerance=atol )
        if verbose:
            print( "The point group for this structure is {}".format( symmetry_analyzer.get_pointgroup()) )
    else:
        raise ValueError( 'structure argument should be a Structure or Molecule object' )
    symmetry_operations = symmetry_analyzer.get_symmetry_operations()
    mappings = []
    if subset:
        species_subset = [ spec for i,spec in enumerate( structure.species ) if i in subset ]
        cart_coords_subset = [ coord for i, coord in enumerate( structure.cart_coords ) if i in subset ]
        mapping_structure = instantiate_structure( species=species_subset, coords=cart_coords_subset )
    else:
        mapping_structure = structure
    for symmop in symmetry_operations:
        cart_coords = coord_mapping( mapping_structure, symmop )
        new_structure = instantiate_structure( species=mapping_structure.species, coords=cart_coords )
        new_mapping = [ x+1 for x in list( mapping_list( new_structure, mapping_structure, atol ) ) ]
        if new_mapping not in mappings:
            mappings.append( new_mapping )
    return mappings
开发者ID:bjmorgan,项目名称:bsym,代码行数:51,代码来源:pymatgen.py

示例9: get_recp_symmetry_operation

# 需要导入模块: from pymatgen.symmetry.analyzer import SpacegroupAnalyzer [as 别名]
# 或者: from pymatgen.symmetry.analyzer.SpacegroupAnalyzer import get_symmetry_operations [as 别名]
def get_recp_symmetry_operation(structure, symprec=0.001):
    """
    Find the symmetric operations of the reciprocal lattice,
    to be used for hkl transformations
    Args:
        structure (Structure): conventional unit cell
        symprec: default is 0.001

    """
    recp_lattice = structure.lattice.reciprocal_lattice_crystallographic
    # get symmetry operations from input conventional unit cell
    # Need to make sure recp lattice is big enough, otherwise symmetry
    # determination will fail. We set the overall volume to 1.
    recp_lattice = recp_lattice.scale(1)
    recp = Structure(recp_lattice, ["H"], [[0, 0, 0]])
    # Creates a function that uses the symmetry operations in the
    # structure to find Miller indices that might give repetitive slabs
    analyzer = SpacegroupAnalyzer(recp, symprec=symprec)
    recp_symmops = analyzer.get_symmetry_operations()

    return recp_symmops
开发者ID:adozier,项目名称:pymatgen,代码行数:23,代码来源:surface.py

示例10: symmeterize

# 需要导入模块: from pymatgen.symmetry.analyzer import SpacegroupAnalyzer [as 别名]
# 或者: from pymatgen.symmetry.analyzer.SpacegroupAnalyzer import get_symmetry_operations [as 别名]
    def symmeterize(self, structure, symprec=0.1, tol=1e-3):
        """
        Averages the piezo tensor based on the symmetries of the structure

        Args:
            structure (Structure): structure to check against
            symprec (float): Tolerance for symmetry finding, default good for
                             as-made structures. Set to 0.1 for MP structures
            tol (float): tolerance for zero'ing out indicies. The average procedure produces very small numbers rather then 0. This tolerance is used to zero out those values to make the tensor less messy.
        """

        sg = SpacegroupAnalyzer(structure, symprec)
        new_pt = PiezoTensor(self)

        for symm in sg.get_symmetry_operations(cartesian=True):
            new_pt = (new_pt + new_pt.transform(symm)) / 2

        low_values_indices = np.abs(new_pt) < tol
        new_pt [low_values_indices] = 0

        return new_pt
开发者ID:PDoakORNL,项目名称:pymatgen,代码行数:23,代码来源:piezo.py

示例11: get_symmetrically_distinct_miller_indices

# 需要导入模块: from pymatgen.symmetry.analyzer import SpacegroupAnalyzer [as 别名]
# 或者: from pymatgen.symmetry.analyzer.SpacegroupAnalyzer import get_symmetry_operations [as 别名]
def get_symmetrically_distinct_miller_indices(structure, max_index):
    """
    Returns all symmetrically distinct indices below a certain max-index for
    a given structure. Analysis is based on the symmetry of the reciprocal
    lattice of the structure.

    Args:
        structure (Structure): input structure.
        max_index (int): The maximum index. For example, a max_index of 1
            means that (100), (110), and (111) are returned for the cubic
            structure. All other indices are equivalent to one of these.
    """

    recp_lattice = structure.lattice.reciprocal_lattice_crystallographic
    # Need to make sure recp lattice is big enough, otherwise symmetry
    # determination will fail. We set the overall volume to 1.
    recp_lattice = recp_lattice.scale(1)
    recp = Structure(recp_lattice, ["H"], [[0, 0, 0]])

    # Creates a function that uses the symmetry operations in the
    # structure to find Miller indices that might give repetitive slabs
    analyzer = SpacegroupAnalyzer(recp, symprec=0.001)
    symm_ops = analyzer.get_symmetry_operations()
    unique_millers = []

    def is_already_analyzed(miller_index):
        for op in symm_ops:
            if in_coord_list(unique_millers, op.operate(miller_index)):
                return True
        return False

    r = list(range(-max_index, max_index + 1))
    r.reverse()
    for miller in itertools.product(r, r, r):
        if any([i != 0 for i in miller]):
            d = abs(reduce(gcd, miller))
            miller = tuple([int(i / d) for i in miller])
            if not is_already_analyzed(miller):
                unique_millers.append(miller)
    return unique_millers
开发者ID:sonium0,项目名称:pymatgen,代码行数:42,代码来源:surface.py

示例12: is_valid

# 需要导入模块: from pymatgen.symmetry.analyzer import SpacegroupAnalyzer [as 别名]
# 或者: from pymatgen.symmetry.analyzer.SpacegroupAnalyzer import get_symmetry_operations [as 别名]
    def is_valid(self, structure, symprec=0.1, tol=1e-3):
        """
        Checks the piezo tensor against the symmetries of the structure and
        determine if the piezoelectric tensor is valid for that structure

        Args:
            structure (Structure): structure to check against
            symprec (float): Tolerance for symmetry finding, default good for
                             as-made structures. Set to 0.1 for MP structures
            tol (float): tolerance for equality
        """

        sg = SpacegroupAnalyzer(structure, symprec)

        # Check every symmetry operation in the space group
        for symm in sg.get_symmetry_operations(cartesian=True):
            # does it produce the same tensor?
            diff = self.transform(symm) - self
            if not (np.abs(diff) < tol).all():
                print(diff)
                return False

        return True
开发者ID:PDoakORNL,项目名称:pymatgen,代码行数:25,代码来源:piezo.py

示例13: __init__

# 需要导入模块: from pymatgen.symmetry.analyzer import SpacegroupAnalyzer [as 别名]
# 或者: from pymatgen.symmetry.analyzer.SpacegroupAnalyzer import get_symmetry_operations [as 别名]
    def __init__(self, struct, symprec=None):
        format_str = "{:.8f}"

        block = OrderedDict()
        loops = []
        spacegroup = ("P 1", 1)
        if symprec is not None:
            sf = SpacegroupAnalyzer(struct, symprec)
            spacegroup = (sf.get_space_group_symbol(),
                          sf.get_space_group_number())
            # Needs the refined struture when using symprec. This converts
            # primitive to conventional structures, the standard for CIF.
            struct = sf.get_refined_structure()

        latt = struct.lattice
        comp = struct.composition
        no_oxi_comp = comp.element_composition
        block["_symmetry_space_group_name_H-M"] = spacegroup[0]
        for cell_attr in ['a', 'b', 'c']:
            block["_cell_length_" + cell_attr] = format_str.format(
                getattr(latt, cell_attr))
        for cell_attr in ['alpha', 'beta', 'gamma']:
            block["_cell_angle_" + cell_attr] = format_str.format(
                getattr(latt, cell_attr))
        block["_symmetry_Int_Tables_number"] = spacegroup[1]
        block["_chemical_formula_structural"] = no_oxi_comp.reduced_formula
        block["_chemical_formula_sum"] = no_oxi_comp.formula
        block["_cell_volume"] = latt.volume.__str__()

        reduced_comp, fu = no_oxi_comp.get_reduced_composition_and_factor()
        block["_cell_formula_units_Z"] = str(int(fu))

        if symprec is None:
            block["_symmetry_equiv_pos_site_id"] = ["1"]
            block["_symmetry_equiv_pos_as_xyz"] = ["x, y, z"]
        else:
            sf = SpacegroupAnalyzer(struct, symprec)

            def round_symm_trans(i):

                for t in TRANSLATIONS.values():
                    if abs(i - t) < symprec:
                        return t
                if abs(i - round(i)) < symprec:
                    return 0
                raise ValueError("Invalid translation!")

            symmops = []
            for op in sf.get_symmetry_operations():
                v = op.translation_vector
                v = [round_symm_trans(i) for i in v]
                symmops.append(SymmOp.from_rotation_and_translation(
                    op.rotation_matrix, v))

            ops = [op.as_xyz_string() for op in symmops]
            block["_symmetry_equiv_pos_site_id"] = \
                ["%d" % i for i in range(1, len(ops) + 1)]
            block["_symmetry_equiv_pos_as_xyz"] = ops

        loops.append(["_symmetry_equiv_pos_site_id",
                      "_symmetry_equiv_pos_as_xyz"])

        contains_oxidation = True
        try:
            symbol_to_oxinum = OrderedDict([
                (el.__str__(), float(el.oxi_state))
                for el in sorted(comp.elements)])
        except AttributeError:
            symbol_to_oxinum = OrderedDict([(el.symbol, 0) for el in
                                            sorted(comp.elements)])
            contains_oxidation = False
        if contains_oxidation:
            block["_atom_type_symbol"] = symbol_to_oxinum.keys()
            block["_atom_type_oxidation_number"] = symbol_to_oxinum.values()
            loops.append(["_atom_type_symbol", "_atom_type_oxidation_number"])

        atom_site_type_symbol = []
        atom_site_symmetry_multiplicity = []
        atom_site_fract_x = []
        atom_site_fract_y = []
        atom_site_fract_z = []
        atom_site_label = []
        atom_site_occupancy = []
        count = 1
        if symprec is None:
            for site in struct:
                for sp, occu in site.species_and_occu.items():
                    atom_site_type_symbol.append(sp.__str__())
                    atom_site_symmetry_multiplicity.append("1")
                    atom_site_fract_x.append("{0:f}".format(site.a))
                    atom_site_fract_y.append("{0:f}".format(site.b))
                    atom_site_fract_z.append("{0:f}".format(site.c))
                    atom_site_label.append("{}{}".format(sp.symbol, count))
                    atom_site_occupancy.append(occu.__str__())
                    count += 1
        else:
            # The following just presents a deterministic ordering.
            unique_sites = [
                (sorted(sites, key=lambda s: tuple([abs(x) for x in
                                                   s.frac_coords]))[0],
#.........这里部分代码省略.........
开发者ID:shyamd,项目名称:pymatgen,代码行数:103,代码来源:cif.py

示例14: SpacegroupAnalyzerTest

# 需要导入模块: from pymatgen.symmetry.analyzer import SpacegroupAnalyzer [as 别名]
# 或者: from pymatgen.symmetry.analyzer.SpacegroupAnalyzer import get_symmetry_operations [as 别名]
class SpacegroupAnalyzerTest(PymatgenTest):

    def setUp(self):
        p = Poscar.from_file(os.path.join(test_dir, 'POSCAR'))
        self.structure = p.structure
        self.sg = SpacegroupAnalyzer(self.structure, 0.001)
        self.disordered_structure = self.get_structure('Li10GeP2S12')
        self.disordered_sg = SpacegroupAnalyzer(self.disordered_structure, 0.001)
        s = p.structure.copy()
        site = s[0]
        del s[0]
        s.append(site.species_and_occu, site.frac_coords)
        self.sg3 = SpacegroupAnalyzer(s, 0.001)
        graphite = self.get_structure('Graphite')
        graphite.add_site_property("magmom", [0.1] * len(graphite))
        self.sg4 = SpacegroupAnalyzer(graphite, 0.001)

    def test_get_space_symbol(self):
        self.assertEqual(self.sg.get_spacegroup_symbol(), "Pnma")
        self.assertEqual(self.disordered_sg.get_spacegroup_symbol(),
                         "P4_2/nmc")
        self.assertEqual(self.sg3.get_spacegroup_symbol(), "Pnma")
        self.assertEqual(self.sg4.get_spacegroup_symbol(), "R-3m")

    def test_get_space_number(self):
        self.assertEqual(self.sg.get_spacegroup_number(), 62)
        self.assertEqual(self.disordered_sg.get_spacegroup_number(), 137)
        self.assertEqual(self.sg4.get_spacegroup_number(), 166)

    def test_get_hall(self):
        self.assertEqual(self.sg.get_hall(), '-P 2ac 2n')
        self.assertEqual(self.disordered_sg.get_hall(), 'P 4n 2n -1n')

    def test_get_pointgroup(self):
        self.assertEqual(self.sg.get_point_group(), 'mmm')
        self.assertEqual(self.disordered_sg.get_point_group(), '4/mmm')

    def test_get_symmetry_dataset(self):
        ds = self.sg.get_symmetry_dataset()
        self.assertEqual(ds['international'], 'Pnma')

    def test_get_crystal_system(self):
        crystal_system = self.sg.get_crystal_system()
        self.assertEqual('orthorhombic', crystal_system)
        self.assertEqual('tetragonal', self.disordered_sg.get_crystal_system())

    def test_get_symmetry_operations(self):
        fracsymmops = self.sg.get_symmetry_operations()
        symmops = self.sg.get_symmetry_operations(True)
        self.assertEqual(len(symmops), 8)
        latt = self.structure.lattice
        for fop, op in zip(fracsymmops, symmops):
            for site in self.structure:
                newfrac = fop.operate(site.frac_coords)
                newcart = op.operate(site.coords)
                self.assertTrue(np.allclose(latt.get_fractional_coords(newcart),
                                            newfrac))
                found = False
                newsite = PeriodicSite(site.species_and_occu, newcart, latt,
                                       coords_are_cartesian=True)
                for testsite in self.structure:
                    if newsite.is_periodic_image(testsite, 1e-3):
                        found = True
                        break
                self.assertTrue(found)

    def test_get_refined_structure(self):
        for a in self.sg.get_refined_structure().lattice.angles:
            self.assertEqual(a, 90)
        refined = self.disordered_sg.get_refined_structure()
        for a in refined.lattice.angles:
            self.assertEqual(a, 90)
        self.assertEqual(refined.lattice.a, refined.lattice.b)
        s = self.get_structure('Li2O')
        sg = SpacegroupAnalyzer(s, 0.001)
        self.assertEqual(sg.get_refined_structure().num_sites, 4 * s.num_sites)

    def test_get_symmetrized_structure(self):
        symm_struct = self.sg.get_symmetrized_structure()
        for a in symm_struct.lattice.angles:
            self.assertEqual(a, 90)
        self.assertEqual(len(symm_struct.equivalent_sites), 5)

        symm_struct = self.disordered_sg.get_symmetrized_structure()
        self.assertEqual(len(symm_struct.equivalent_sites), 8)
        self.assertEqual([len(i) for i in symm_struct.equivalent_sites],
                         [16,4,8,4,2,8,8,8])
        s1 = symm_struct.equivalent_sites[1][1]
        s2 = symm_struct[symm_struct.equivalent_indices[1][1]]
        self.assertEqual(s1, s2)
        self.assertEqual(self.sg4.get_symmetrized_structure()[0].magmom, 0.1)

    def test_find_primitive(self):
        """
        F m -3 m Li2O testing of converting to primitive cell
        """
        parser = CifParser(os.path.join(test_dir, 'Li2O.cif'))
        structure = parser.get_structures(False)[0]
        s = SpacegroupAnalyzer(structure)
        primitive_structure = s.find_primitive()
#.........这里部分代码省略.........
开发者ID:anhhv,项目名称:pymatgen,代码行数:103,代码来源:test_analyzer.py

示例15: __init__

# 需要导入模块: from pymatgen.symmetry.analyzer import SpacegroupAnalyzer [as 别名]
# 或者: from pymatgen.symmetry.analyzer.SpacegroupAnalyzer import get_symmetry_operations [as 别名]
    def __init__(self, struct, find_spacegroup=False, symprec=None):
        """
        Args:
            struct (Structure): structure to write
            find_spacegroup (bool): whether to try to determine the spacegroup
            symprec (float): If not none, finds the symmetry of the structure and
                writes the cif with symmetry information. Passes symprec to the
                SpacegroupAnalyzer
        """
        format_str = "{:.8f}"
        
        block = OrderedDict()
        loops = []
        latt = struct.lattice
        comp = struct.composition
        no_oxi_comp = comp.element_composition
        spacegroup = ("P 1", 1)
        if find_spacegroup:
            sf = SpacegroupAnalyzer(struct, 0.001)
            spacegroup = (sf.get_spacegroup_symbol(),
                          sf.get_spacegroup_number())
        block["_symmetry_space_group_name_H-M"] = spacegroup[0]
        for cell_attr in ['a', 'b', 'c']:
            block["_cell_length_" + cell_attr] = format_str.format(
                getattr(latt, cell_attr))
        for cell_attr in ['alpha', 'beta', 'gamma']:
            block["_cell_angle_" + cell_attr] = format_str.format(
                getattr(latt, cell_attr))
        block["_symmetry_Int_Tables_number"] = spacegroup[1]
        block["_chemical_formula_structural"] = no_oxi_comp.reduced_formula
        block["_chemical_formula_sum"] = no_oxi_comp.formula
        block["_cell_volume"] = latt.volume.__str__()

        reduced_comp = no_oxi_comp.reduced_composition
        el = no_oxi_comp.elements[0]
        amt = comp[el]
        fu = int(amt / reduced_comp[Element(el.symbol)])

        block["_cell_formula_units_Z"] = str(fu)

        if symprec is None:
            block["_symmetry_equiv_pos_site_id"] = ["1"]
            block["_symmetry_equiv_pos_as_xyz"] = ["x, y, z"]
        else:
            sf = SpacegroupAnalyzer(struct, symprec)
            ops = [op.as_xyz_string() for op in sf.get_symmetry_operations()]
            block["_symmetry_equiv_pos_site_id"] = \
                ["%d" % i for i in range(1, len(ops) + 1)]
            block["_symmetry_equiv_pos_as_xyz"] = ops

        loops.append(["_symmetry_equiv_pos_site_id",
                      "_symmetry_equiv_pos_as_xyz"])

        contains_oxidation = True
        try:
            symbol_to_oxinum = OrderedDict([
                (el.__str__(), float(el.oxi_state))
                for el in sorted(comp.elements)])
        except AttributeError:
            symbol_to_oxinum = OrderedDict([(el.symbol, 0) for el in 
                                            sorted(comp.elements)])
            contains_oxidation = False
        if contains_oxidation:
            block["_atom_type_symbol"] = symbol_to_oxinum.keys()
            block["_atom_type_oxidation_number"] = symbol_to_oxinum.values()
            loops.append(["_atom_type_symbol", "_atom_type_oxidation_number"])

        atom_site_type_symbol = []
        atom_site_symmetry_multiplicity = []
        atom_site_fract_x = []
        atom_site_fract_y = []
        atom_site_fract_z = []
        atom_site_label = []
        atom_site_occupancy = []
        count = 1
        if symprec is None:
            for site in struct:
                for sp, occu in site.species_and_occu.items():
                    atom_site_type_symbol.append(sp.__str__())
                    atom_site_symmetry_multiplicity.append("1")
                    atom_site_fract_x.append("{0:f}".format(site.a))
                    atom_site_fract_y.append("{0:f}".format(site.b))
                    atom_site_fract_z.append("{0:f}".format(site.c))
                    atom_site_label.append("{}{}".format(sp.symbol, count))
                    atom_site_occupancy.append(occu.__str__())
                    count += 1
        else:
            for group in sf.get_symmetrized_structure().equivalent_sites:
                site = group[0]
                for sp, occu in site.species_and_occu.items():
                    atom_site_type_symbol.append(sp.__str__())
                    atom_site_symmetry_multiplicity.append("%d" % len(group))
                    atom_site_fract_x.append("{0:f}".format(site.a))
                    atom_site_fract_y.append("{0:f}".format(site.b))
                    atom_site_fract_z.append("{0:f}".format(site.c))
                    atom_site_label.append("{}{}".format(sp.symbol, count))
                    atom_site_occupancy.append(occu.__str__())
                    count += 1

        block["_atom_site_type_symbol"] = atom_site_type_symbol
#.........这里部分代码省略.........
开发者ID:antoinedewandre,项目名称:pymatgen,代码行数:103,代码来源:cifio.py


注:本文中的pymatgen.symmetry.analyzer.SpacegroupAnalyzer.get_symmetry_operations方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。