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
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
1import numpy as np
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
9class ClusterFactory(ClusterBase):
10 directions = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
12 atomic_basis = np.array([[0.0, 0.0, 0.0]])
14 element_basis: list[int] | None = None
16 # Make it possible to change the class of the object returned.
17 Cluster = Cluster
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
31 # Interpret symbol
32 self.set_atomic_numbers(symbols)
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
45 self.set_basis()
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)
53 self.set_surfaces_layers(surfaces, layers)
54 self.set_lattice_size(center)
56 if self.debug:
57 print('Center position:', self.center.round(2))
58 print('Base lattice size:', self.size)
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
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)
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
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)
91 r = np.dot(positions - self.center, n)
92 mask = np.less(r, rmax)
94 if self.debug > 1:
95 print('Cutting %s at %i layers ~ %.3f A' % (s, l, rmax))
97 positions = positions[mask]
98 numbers = numbers[mask]
100 atoms = self.Cluster(symbols=numbers, positions=positions)
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
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
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 )
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
148 self.atomic_numbers = [atomic_numbers[n] for n in element_basis]
149 assert len(self.atomic_numbers) == len(self.atomic_basis)
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 )
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])
173 if self.debug > 1:
174 print(
175 'Spaning %i layers in %s in lattice basis ~ %s' % (l, s, k)
176 )
178 max[k > max] = k[k > max]
179 min[k < min] = k[k < min]
181 self.center = np.dot(offset - min, self.lattice_basis)
182 self.size = (max - min + np.ones(3)).astype(int)
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 )
191 sg = Spacegroup(self.spacegroup)
192 surfaces = np.array(surfaces)
193 layers = np.array(layers)
195 for i, s in enumerate(surfaces):
196 s = reduce_miller(s)
197 surfaces[i] = s
199 surfaces_full = surfaces.copy()
200 layers_full = layers.copy()
202 for s, l in zip(surfaces, layers):
203 equivalent_surfaces = sg.equivalent_reflections(s.reshape(-1, 3))
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)
214 self.surfaces = surfaces_full.copy()
215 self.layers = layers_full.copy()
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]))
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 )
231# Helping functions
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 )
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
255def reduce_miller(hkl):
256 """Reduce Miller index to the lowest equivalent integers."""
257 hkl = np.array(hkl)
258 old = hkl.copy()
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])
265 if np.dot(old, hkl) > 0:
266 return hkl
267 else:
268 return -hkl