How to use spglib - 10 common examples

To help you get started, we’ve selected a few spglib examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github qzhu2017 / PyXtal / pyxtal / test_cases / Random_vasp_ase.py View on Github external
struc.set_calculator(set_vasp(level=3, pstress=pstress, setup=setup))
            print(struc.get_potential_energy())
            time, ncore = read_OUTCAR()
            time0 += time
            print("time for vasp calcs3 (seconds):  ", time)
            struc = read("CONTCAR", format="vasp")

            if good_lattice(struc):
                struc = symmetrize_cell(struc, mode="P")
                struc.set_calculator(set_vasp(level=4, pstress=pstress, setup=setup))
                struc.get_potential_energy()
                time, ncore = read_OUTCAR()
                print("time for vasp calcs4 (seconds):  ", time)
                time0 += time
                result = vasprun().values
                spg = get_symmetry_dataset(struc, symprec=5e-2)["international"]
                print(
                    "#####%-10s %-10s %12.6f %6.2f %8.2f %4d %12s"
                    % (
                        dir1,
                        struc.get_chemical_formula(),
                        result["calculation"]["energy_per_atom"],
                        result["gap"],
                        time0,
                        ncore,
                        spg,
                    )
github qzhu2017 / PyXtal / pyxtal / test_cases / test_all.py View on Github external
t = str(timespent)
            if len(t) == 3:
                t += "0"
            t += " s"
            if timespent >= 1.0:
                t += " ~"
            if timespent >= 3.0:
                t += "~"
            if timespent >= 10.0:
                t += "~"
            if timespent >= 60.0:
                t += "~"
                slow.append(num)
            if rand_crystal.valid:
                try:
                    ans1 = get_symmetry_dataset(rand_crystal.spg_struct, symprec=1e-1)
                except:
                    ans1 = "???"
                if ans1 is None or ans1 == "???":
                    ans1 = "???"
                else:
                    ans1 = ans1["number"]
                sga = SpacegroupAnalyzer(rand_crystal.struct)
                try:
                    ans2 = sga.get_space_group_number()
                except:
                    ans2 = "???"
                if ans2 is None:
                    ans2 = "???"

                check = True
github pyiron / pyiron / pyiron / atomistics / structure / atoms.py View on Github external
def get_spacegroup(self, symprec=1e-5, angle_tolerance=-1.0):
        """
        
        Args:
            symprec: 
            angle_tolerance: 

        Returns:

        https://atztogo.github.io/spglib/python-spglib.html
        """
        lattice = np.array(self.get_cell(), dtype='double', order='C')
        positions = np.array(self.get_scaled_positions(), dtype='double', order='C')
        numbers = np.array(self.get_atomic_numbers(), dtype='intc')
        space_group = spglib.get_spacegroup(cell=(lattice, positions, numbers),
                                            symprec=symprec,
                                            angle_tolerance=angle_tolerance).split()
        if len(space_group) == 1:
            return {"Number": ast.literal_eval(space_group[0])}
        else:
            return {"InternationalTableSymbol": space_group[0],
                    "Number": ast.literal_eval(space_group[1])}
github elcorto / pwtools / pwtools / symmetry.py View on Github external
`angle_tolerance` last time I checked

    Returns
    -------
    spg_num, spg_sym
    spg_num : int
        space group number
    spg_sym : str
        space group symbol

    Notes
    -----
    The used function ``spglib.get_spacegroup()`` returns a string, which we
    split into `spg_num` and `spg_sym`.
    """
    ret = spglib.get_spacegroup(struct.get_spglib(), **kwds)
    spl = ret.split()
    spg_sym = spl[0]
    spg_num = spl[1]
    spg_num = spg_num.replace('(','').replace(')','')
    spg_num = int(spg_num)
    return spg_num,spg_sym
github pyiron / pyiron / pyiron / atomistics / structure / atoms.py View on Github external
def get_spacegroup(self, symprec=1e-5, angle_tolerance=-1.0):
        """
        
        Args:
            symprec: 
            angle_tolerance: 

        Returns:

        https://atztogo.github.io/spglib/python-spglib.html
        """
        lattice = np.array(self.get_cell(), dtype='double', order='C')
        positions = np.array(self.get_scaled_positions(), dtype='double', order='C')
        numbers = np.array(self.get_atomic_numbers(), dtype='intc')
        space_group = spglib.get_spacegroup(cell=(lattice, positions, numbers),
                                            symprec=symprec,
                                            angle_tolerance=angle_tolerance).split()
        if len(space_group) == 1:
            return {"Number": ast.literal_eval(space_group[0])}
        else:
            return {"InternationalTableSymbol": space_group[0],
                    "Number": ast.literal_eval(space_group[1])}
github materialsproject / pymatgen / pymatgen / io / lobster.py View on Github external
else:
                unique_species.append(species)
                zs.extend([len(unique_species)] * len(tuple(g)))

        for site in structure:
            if hasattr(site, 'magmom'):
                magmoms.append(site.magmom)
            elif site.is_ordered and hasattr(site.specie, 'spin'):
                magmoms.append(site.specie.spin)
            else:
                magmoms.append(0)

        # For now, we are setting magmom to zero. (Taken from INCAR class)
        cell = latt, positions, zs, magmoms
        # TODO: what about this shift?
        mapping, grid = spglib.get_ir_reciprocal_mesh(mesh, cell, is_shift=[0, 0, 0])

        # exit()
        # get the kpoints for the grid
        if isym == -1:
            kpts = []
            weights = []
            all_labels = []
            for gp in grid:
                kpts.append(gp.astype(float) / mesh)
                weights.append(float(1))
                all_labels.append("")
        elif isym == 0:
            # time reversal symmetry: k and -k are equivalent
            kpts = []
            weights = []
            all_labels = []
github giovannipizzi / seekpath / seekpath / hpkot / tools.py View on Github external
older than 1.9.4.

    Also raises an warning if the user has a version of SPGLIB that is
    older than 1.13, because before then there were some bugs (e.g. 
    wrong treatment of oI, see e.g. issue )

    Return the spglib module.
    """
    try:
        import spglib
    except ImportError:
        raise ValueError("spglib >= 1.9.4 is required for the creation "
                         "of the k-paths, but it could not be imported")

    try:
        version = spglib.__version__
    except NameError:
        version = "1.8.0"  # or older, version was introduced only recently

    try:
        version_pieces = [int(_) for _ in version.split('.')]
        if len(version_pieces) < 3:
            raise ValueError
    except ValueError:
        raise ValueError("Unable to parse version number")

    if tuple(version_pieces[:2]) < (1, 9):
        raise ValueError("Invalid spglib version, need >= 1.9.4")

    if version_pieces[:2] == (1, 9) and version_pieces[2] < 4:
        raise ValueError("Invalid spglib version, need >= 1.9.4")
github SINGROUP / matid / systax / analysis / symmetryanalyzer.py View on Github external
def get_symmetry_dataset(self):
        """Calculates the symmetry dataset with spglib for the given system.
        """
        if self._symmetry_dataset is not None:
            return self._symmetry_dataset

        description = self._system_to_spglib_description(self.system)
        # Spglib has been observed to cause segmentation faults when fed with
        # invalid data, so run in separate process to catch those cases
        try:
            symmetry_dataset = segfault_protect(
                spglib.get_symmetry_dataset,
                description,
                self.spglib_precision)
        except RuntimeError:
            raise CellNormalizationError(
                "Segfault in spglib when finding symmetry dataset. Please check "
                " the given cell, scaled positions and atomic numbers."
            )
        if symmetry_dataset is None:
            raise CellNormalizationError(
                'Spglib error when finding symmetry dataset.')

        self._symmetry_dataset = symmetry_dataset

        return symmetry_dataset
github pyiron / pyiron / pyiron / atomistics / structure / atoms.py View on Github external
def get_symmetry_dataset(self, symprec=1e-5, angle_tolerance=-1.0):
        """
        
        Args:
            symprec: 
            angle_tolerance: 

        Returns:

        https://atztogo.github.io/spglib/python-spglib.html
        """
        lattice = np.array(self.get_cell().T, dtype='double', order='C')
        positions = np.array(self.get_scaled_positions(), dtype='double', order='C')
        numbers = np.array(self.get_atomic_numbers(), dtype='intc')
        return spglib.get_symmetry_dataset(cell=(lattice, positions, numbers),
                                           symprec=symprec,
                                           angle_tolerance=angle_tolerance)
github LaurentRDC / scikit-ued / skued / structure / crystal.py View on Github external
* ``'international_number'`` : International Tables of Crystallography space-group number (between 1 and 230);

            * ``'hall_number'`` : Hall number (between 1 and 531).

            If symmetry-determination has failed, None is returned.
        
        Raises
        ------
        RuntimeError : If symmetry-determination has yielded an error.
        
        Notes
        -----
        Note that crystals generated from the Protein Data Bank are often incomplete; 
        in such cases the space-group information will be incorrect.
        """
        dataset = get_symmetry_dataset(cell = self._spglib_cell(),
                                       symprec = symprec, 
                                       angle_tolerance = angle_tolerance)

        if dataset: 
            spg_type = get_spacegroup_type(dataset['hall_number'])

            info = {'international_symbol': dataset['international'],
                    'hall_symbol'         : dataset['hall'],
                    'international_number': dataset['number'],
                    'hall_number'         : dataset['hall_number'],
                    'international_full'  : spg_type['international_full'],
                    'pointgroup'          : spg_type['pointgroup_international']} 

            err_msg = get_error_message()
            if (err_msg != 'no error'):
                raise RuntimeError('Symmetry-determination has returned the following error: {}'.format(err_msg))