Coverage for ase/cluster/factory.py: 80.00%

150 statements  

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

1import numpy as np 

2 

3from ase.cluster.base import ClusterBase 

4from ase.cluster.cluster import Cluster 

5from ase.data import atomic_numbers as ref_atomic_numbers 

6from ase.spacegroup import Spacegroup 

7 

8 

9class ClusterFactory(ClusterBase): 

10 directions = [[1, 0, 0], [0, 1, 0], [0, 0, 1]] 

11 

12 atomic_basis = np.array([[0.0, 0.0, 0.0]]) 

13 

14 element_basis: list[int] | None = None 

15 

16 # Make it possible to change the class of the object returned. 

17 Cluster = Cluster 

18 

19 def __call__( 

20 self, 

21 symbols, 

22 surfaces, 

23 layers, 

24 latticeconstant=None, 

25 center=None, 

26 vacuum=0.0, 

27 debug=0, 

28 ): 

29 self.debug = debug 

30 

31 # Interpret symbol 

32 self.set_atomic_numbers(symbols) 

33 

34 # Interpret lattice constant 

35 if latticeconstant is None: 

36 if self.element_basis is None: 

37 self.lattice_constant = self.get_lattice_constant() 

38 else: 

39 raise ValueError( 

40 'A lattice constant must be specified for a compound' 

41 ) 

42 else: 

43 self.lattice_constant = latticeconstant 

44 

45 self.set_basis() 

46 

47 if self.debug: 

48 print('Lattice constant(s):', self.lattice_constant) 

49 print('Lattice basis:\n', self.lattice_basis) 

50 print('Resiprocal basis:\n', self.resiproc_basis) 

51 print('Atomic basis:\n', self.atomic_basis) 

52 

53 self.set_surfaces_layers(surfaces, layers) 

54 self.set_lattice_size(center) 

55 

56 if self.debug: 

57 print('Center position:', self.center.round(2)) 

58 print('Base lattice size:', self.size) 

59 

60 cluster = self.make_cluster(vacuum) 

61 cluster.symmetry = self.xtal_name 

62 cluster.surfaces = self.surfaces.copy() 

63 cluster.lattice_basis = self.lattice_basis.copy() 

64 cluster.atomic_basis = self.atomic_basis.copy() 

65 cluster.resiproc_basis = self.resiproc_basis.copy() 

66 return cluster 

67 

68 def make_cluster(self, vacuum): 

69 # Make the base crystal by repeating the unit cell 

70 size = np.array(self.size) 

71 translations = np.zeros((size.prod(), 3)) 

72 for h in range(size[0]): 

73 for k in range(size[1]): 

74 for l_ in range(size[2]): 

75 i = h * (size[1] * size[2]) + k * size[2] + l_ 

76 translations[i] = np.dot([h, k, l_], self.lattice_basis) 

77 

78 atomic_basis = np.dot(self.atomic_basis, self.lattice_basis) 

79 positions = np.zeros((len(translations) * len(atomic_basis), 3)) 

80 numbers = np.zeros(len(positions)) 

81 n = len(atomic_basis) 

82 for i, trans in enumerate(translations): 

83 positions[n * i : n * (i + 1)] = atomic_basis + trans 

84 numbers[n * i : n * (i + 1)] = self.atomic_numbers 

85 

86 # Remove all atoms that is outside the defined surfaces 

87 for s, l in zip(self.surfaces, self.layers): 

88 n = self.miller_to_direction(s) 

89 rmax = self.get_layer_distance(s, l + 0.1) 

90 

91 r = np.dot(positions - self.center, n) 

92 mask = np.less(r, rmax) 

93 

94 if self.debug > 1: 

95 print('Cutting %s at %i layers ~ %.3f A' % (s, l, rmax)) 

96 

97 positions = positions[mask] 

98 numbers = numbers[mask] 

99 

100 atoms = self.Cluster(symbols=numbers, positions=positions) 

101 

102 atoms.cell = (1, 1, 1) # XXX ugly hack to center around zero 

103 atoms.center(about=(0, 0, 0)) 

104 atoms.cell[:] = 0 

105 return atoms 

106 

107 def set_atomic_numbers(self, symbols): 

108 "Extract atomic number from element" 

109 # The types that can be elements: integers and strings 

110 atomic_numbers = [] 

111 if self.element_basis is None: 

112 if isinstance(symbols, str): 

113 atomic_numbers.append(ref_atomic_numbers[symbols]) 

114 elif isinstance(symbols, int): 

115 atomic_numbers.append(symbols) 

116 else: 

117 raise TypeError( 

118 'The symbol argument must be a ' 

119 + 'string or an atomic number.' 

120 ) 

121 element_basis = [0] * len(self.atomic_basis) 

122 else: 

123 if isinstance(symbols, (list, tuple)): 

124 nsymbols = len(symbols) 

125 else: 

126 nsymbols = 0 

127 

128 nelement_basis = max(self.element_basis) + 1 

129 if nsymbols != nelement_basis: 

130 raise TypeError( 

131 'The symbol argument must be a sequence ' 

132 + 'of length %d' % (nelement_basis,) 

133 + ' (one for each kind of lattice position' 

134 ) 

135 

136 for s in symbols: 

137 if isinstance(s, str): 

138 atomic_numbers.append(ref_atomic_numbers[s]) 

139 elif isinstance(s, int): 

140 atomic_numbers.append(s) 

141 else: 

142 raise TypeError( 

143 'The symbol argument must be a ' 

144 + 'string or an atomic number.' 

145 ) 

146 element_basis = self.element_basis 

147 

148 self.atomic_numbers = [atomic_numbers[n] for n in element_basis] 

149 assert len(self.atomic_numbers) == len(self.atomic_basis) 

150 

151 def set_lattice_size(self, center): 

152 if center is None: 

153 offset = np.zeros(3) 

154 else: 

155 offset = np.array(center) 

156 if (offset > 1.0).any() or (offset < 0.0).any(): 

157 raise ValueError( 

158 'Center offset must lie within the lattice unit cell.' 

159 ) 

160 

161 max = np.ones(3) 

162 min = -np.ones(3) 

163 v = np.linalg.inv(self.lattice_basis.T) 

164 for s, l in zip(self.surfaces, self.layers): 

165 n = self.miller_to_direction(s) * self.get_layer_distance(s, l) 

166 k = np.round(np.dot(v, n), 2) 

167 for i in range(3): 

168 if k[i] > 0.0: 

169 k[i] = np.ceil(k[i]) 

170 elif k[i] < 0.0: 

171 k[i] = np.floor(k[i]) 

172 

173 if self.debug > 1: 

174 print( 

175 'Spaning %i layers in %s in lattice basis ~ %s' % (l, s, k) 

176 ) 

177 

178 max[k > max] = k[k > max] 

179 min[k < min] = k[k < min] 

180 

181 self.center = np.dot(offset - min, self.lattice_basis) 

182 self.size = (max - min + np.ones(3)).astype(int) 

183 

184 def set_surfaces_layers(self, surfaces, layers): 

185 if len(surfaces) != len(layers): 

186 raise ValueError( 

187 'Improper size of surface and layer arrays: %i != %i' 

188 % (len(surfaces), len(layers)) 

189 ) 

190 

191 sg = Spacegroup(self.spacegroup) 

192 surfaces = np.array(surfaces) 

193 layers = np.array(layers) 

194 

195 for i, s in enumerate(surfaces): 

196 s = reduce_miller(s) 

197 surfaces[i] = s 

198 

199 surfaces_full = surfaces.copy() 

200 layers_full = layers.copy() 

201 

202 for s, l in zip(surfaces, layers): 

203 equivalent_surfaces = sg.equivalent_reflections(s.reshape(-1, 3)) 

204 

205 for es in equivalent_surfaces: 

206 # If the equivalent surface (es) is not in the surface list, 

207 # then append it. 

208 if not np.equal(es, surfaces_full).all(axis=1).any(): 

209 surfaces_full = np.append( 

210 surfaces_full, es.reshape(1, 3), axis=0 

211 ) 

212 layers_full = np.append(layers_full, l) 

213 

214 self.surfaces = surfaces_full.copy() 

215 self.layers = layers_full.copy() 

216 

217 def get_resiproc_basis(self, basis): 

218 """Returns the resiprocal basis to a given lattice (crystal) basis""" 

219 k = 1 / np.dot(basis[0], cross(basis[1], basis[2])) 

220 

221 # The same as the inversed basis matrix transposed 

222 return k * np.array( 

223 [ 

224 cross(basis[1], basis[2]), 

225 cross(basis[2], basis[0]), 

226 cross(basis[0], basis[1]), 

227 ] 

228 ) 

229 

230 

231# Helping functions 

232 

233 

234def cross(a, b): 

235 """The cross product of two vectors.""" 

236 return np.array( 

237 [ 

238 a[1] * b[2] - b[1] * a[2], 

239 a[2] * b[0] - b[2] * a[0], 

240 a[0] * b[1] - b[0] * a[1], 

241 ] 

242 ) 

243 

244 

245def GCD(a, b): 

246 """Greatest Common Divisor of a and b.""" 

247 # print "--" 

248 while a != 0: 

249 # print a,b,">", 

250 a, b = b % a, a 

251 # print a,b 

252 return b 

253 

254 

255def reduce_miller(hkl): 

256 """Reduce Miller index to the lowest equivalent integers.""" 

257 hkl = np.array(hkl) 

258 old = hkl.copy() 

259 

260 d = GCD(GCD(hkl[0], hkl[1]), hkl[2]) 

261 while d != 1: 

262 hkl = hkl // d 

263 d = GCD(GCD(hkl[0], hkl[1]), hkl[2]) 

264 

265 if np.dot(old, hkl) > 0: 

266 return hkl 

267 else: 

268 return -hkl