Coverage for ase/spacegroup/utils.py: 90.16%

61 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-27 15:21 +0000

1from typing import Literal 

2 

3import numpy as np 

4 

5from ase import Atoms 

6 

7from .spacegroup import _SPACEGROUP, Spacegroup 

8 

9__all__ = ('get_basis',) 

10 

11 

12def _has_spglib() -> bool: 

13 """Check if spglib is available""" 

14 try: 

15 import spglib 

16 

17 assert spglib # silence flakes 

18 except ImportError: 

19 return False 

20 return True 

21 

22 

23def _get_basis_ase( 

24 atoms: Atoms, spacegroup: _SPACEGROUP, tol: float = 1e-5 

25) -> np.ndarray: 

26 """Recursively get a reduced basis, by removing equivalent sites. 

27 Uses the first index as a basis, then removes all equivalent sites, 

28 uses the next index which hasn't been placed into a basis, etc. 

29 

30 Parameters 

31 ---------- 

32 atoms : Atoms 

33 ASE Atoms object to get basis from. 

34 spacegroup : int | str | Spacegroup 

35 Space group. 

36 tol : float, default: 1e-5 

37 Tolerance for positional comparisons. 

38 

39 """ 

40 scaled_positions = atoms.get_scaled_positions() 

41 spacegroup = Spacegroup(spacegroup) 

42 

43 def scaled_in_sites(scaled_pos: np.ndarray, sites: np.ndarray): 

44 """Check if a scaled position is in a site""" 

45 for site in sites: 

46 if np.allclose(site, scaled_pos, atol=tol): 

47 return True 

48 return False 

49 

50 def _get_basis( 

51 scaled_positions: np.ndarray, spacegroup: Spacegroup, all_basis=None 

52 ) -> np.ndarray: 

53 """Main recursive function to be executed""" 

54 if all_basis is None: 

55 # Initialization, first iteration 

56 all_basis = [] 

57 if len(scaled_positions) == 0: 

58 # End termination 

59 return np.array(all_basis) 

60 

61 basis = scaled_positions[0] 

62 all_basis.append(basis.tolist()) # Add the site as a basis 

63 

64 # Get equivalent sites 

65 sites, _ = spacegroup.equivalent_sites(basis) 

66 

67 # Remove equivalent 

68 new_scaled = np.array( 

69 [sc for sc in scaled_positions if not scaled_in_sites(sc, sites)] 

70 ) 

71 # We should always have at least popped off the site itself 

72 assert len(new_scaled) < len(scaled_positions) 

73 

74 return _get_basis(new_scaled, spacegroup, all_basis=all_basis) 

75 

76 return _get_basis(scaled_positions, spacegroup) 

77 

78 

79def _get_basis_spglib(atoms: Atoms, tol: float = 1e-5) -> np.ndarray: 

80 """Get a reduced basis using spglib. This requires having the 

81 spglib package installed. 

82 

83 Parameters 

84 ---------- 

85 atoms : Atoms 

86 ASE Atoms object to get basis from. 

87 tol : float, default: 1e-5 

88 Tolerance for positional comparisons. 

89 

90 """ 

91 if not _has_spglib(): 

92 # Give a reasonable alternative solution to this function. 

93 raise ImportError( 

94 'This function requires spglib. Use "get_basis" and specify ' 

95 'the spacegroup instead, or install spglib.' 

96 ) 

97 

98 scaled_positions = atoms.get_scaled_positions() 

99 reduced_indices = _get_reduced_indices(atoms, tol=tol) 

100 return scaled_positions[reduced_indices] 

101 

102 

103def _can_use_spglib(spacegroup: _SPACEGROUP | None = None) -> bool: 

104 """Helper dispatch function, for deciding if the spglib implementation 

105 can be used""" 

106 if not _has_spglib(): 

107 # Spglib not installed 

108 return False 

109 if spacegroup is not None: 

110 # Currently, passing an explicit space group is not supported 

111 # in spglib implementation 

112 return False 

113 return True 

114 

115 

116# Dispatcher function for chosing get_basis implementation. 

117def get_basis( 

118 atoms: Atoms, 

119 spacegroup: _SPACEGROUP | None = None, 

120 method: Literal['auto', 'ase', 'spglib'] = 'auto', 

121 tol: float = 1e-5, 

122) -> np.ndarray: 

123 """Function for determining a reduced basis of an atoms object. 

124 Can use either an ASE native algorithm or an spglib based one. 

125 The native ASE version requires specifying a space group, 

126 while the (current) spglib version cannot. 

127 The default behavior is to automatically determine which implementation 

128 to use, based on the the ``spacegroup`` parameter, 

129 and whether spglib is installed. 

130 

131 Parameters 

132 ---------- 

133 atoms : Atoms 

134 ASE Atoms object to get basis from. 

135 spacegroup : int | str | Spacegroup | None, default: None 

136 Space group. 

137 If unspecified, the spacegroup can be inferred using spglib, 

138 if spglib is installed, and ``method`` is set to either 

139 ``'spglib'`` or ``'auto'``. 

140 Inferring the spacegroup requires spglib. 

141 method : Literal['auto', 'ase', 'spglib'], default: 'auto' 

142 Selection of which implementation to use. 

143 It is recommended to use ``'auto'``, which is also the default. 

144 tol : float, default: 1e-5 

145 Tolerance for positional comparisons. 

146 

147 """ 

148 ALLOWED_METHODS = ('auto', 'ase', 'spglib') 

149 

150 if method not in ALLOWED_METHODS: 

151 raise ValueError( 

152 'Expected one of {} methods, got {}'.format(ALLOWED_METHODS, method) 

153 ) 

154 

155 if method == 'auto': 

156 # Figure out which implementation we want to use automatically 

157 # Essentially figure out if we can use the spglib version or not 

158 use_spglib = _can_use_spglib(spacegroup=spacegroup) 

159 else: 

160 # User told us which implementation they wanted 

161 use_spglib = method == 'spglib' 

162 

163 if use_spglib: 

164 # Use the spglib implementation 

165 # Note, we do not pass the spacegroup, as the function cannot handle 

166 # an explicit space group right now. This may change in the future. 

167 return _get_basis_spglib(atoms, tol=tol) 

168 else: 

169 # Use the ASE native non-spglib version, since a specific 

170 # space group is requested 

171 if spacegroup is None: 

172 # We have reached this point either because spglib is not installed, 

173 # or ASE was explicitly required 

174 raise ValueError( 

175 'A space group must be specified for the native ASE ' 

176 'implementation. Try using the spglib version instead, ' 

177 'or explicitly specifying a space group.' 

178 ) 

179 return _get_basis_ase(atoms, spacegroup, tol=tol) 

180 

181 

182def _get_reduced_indices(atoms: Atoms, tol: float = 1e-5) -> list[int]: 

183 """Get a list of the reduced atomic indices using spglib. 

184 Note: Does no checks to see if spglib is installed. 

185 

186 Parameters 

187 ---------- 

188 atoms : Atoms 

189 ASE Atoms object to reduce. 

190 tol : float, default: 1e-5 

191 Tolerance for positional comparisons. 

192 

193 """ 

194 from ase.spacegroup.symmetrize import spglib_get_symmetry_dataset 

195 

196 # Create input for spglib 

197 spglib_cell = ( 

198 atoms.get_cell(), 

199 atoms.get_scaled_positions(), 

200 atoms.numbers, 

201 ) 

202 symmetry_data = spglib_get_symmetry_dataset(spglib_cell, symprec=tol) 

203 return list(set(symmetry_data.equivalent_atoms))