Coverage for ase/lattice/bravais.py: 81.18%
287 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
1"""Bravais.py - class for generating Bravais lattices etc.
3This is a base class for numerous classes setting up pieces of crystal.
4"""
6import math
7from collections.abc import Sequence
9import numpy as np
11import ase.data
12from ase.atoms import Atoms
15class Bravais:
16 """Bravais lattice factory.
18 This is a base class for the objects producing various lattices
19 (SC, FCC, ...).
20 """
22 # The following methods are NOT defined here, but must be defined
23 # in classes inhering from Bravais:
24 # get_lattice_constant
25 # make_crystal_basis
26 # The following class attributes are NOT defined here, but must be defined
27 # in classes inhering from Bravais:
28 # int_basis
29 # inverse_basis
31 other = {0: (1, 2), 1: (2, 0), 2: (0, 1)}
33 # For Bravais lattices with a basis, set the basis here. Leave as
34 # None if no basis is present.
35 bravais_basis: Sequence[Sequence[float]] | None = None
37 # If more than one type of element appear in the crystal, give the
38 # order here. For example, if two elements appear in a 3:1 ratio,
39 # bravais_basis could contain four vectors, and element_basis
40 # could be (0,0,1,0) - the third atom in the basis is different
41 # from the other three. Leave as None if all atoms are of the
42 # same type.
43 element_basis: Sequence[int] | None = None
45 # How small numbers should be considered zero in the unit cell?
46 chop_tolerance = 1e-10
48 def __call__(
49 self,
50 symbol,
51 directions=(None, None, None),
52 miller=(None, None, None),
53 size=(1, 1, 1),
54 latticeconstant=None,
55 pbc=True,
56 align=True,
57 debug=0,
58 ):
59 "Create a lattice."
60 self.size = size
61 self.pbc = pbc
62 self.debug = debug
63 self.process_element(symbol)
64 self.find_directions(directions, miller)
65 if self.debug:
66 self.print_directions_and_miller()
67 self.convert_to_natural_basis()
68 if self.debug >= 2:
69 self.print_directions_and_miller(' (natural basis)')
70 if latticeconstant is None:
71 if self.element_basis is None:
72 self.latticeconstant = self.get_lattice_constant()
73 else:
74 raise ValueError(
75 'A lattice constant must be specified for a compound'
76 )
77 else:
78 self.latticeconstant = latticeconstant
79 if self.debug:
80 print(
81 'Expected number of atoms in unit cell:', self.calc_num_atoms()
82 )
83 if self.debug >= 2:
84 print('Bravais lattice basis:', self.bravais_basis)
85 if self.bravais_basis is not None:
86 print(' ... in natural basis:', self.natural_bravais_basis)
87 self.make_crystal_basis()
88 self.make_unit_cell()
89 if align:
90 self.align()
91 return self.make_list_of_atoms()
93 def align(self):
94 "Align the first axis along x-axis and the second in the x-y plane."
95 degree = 180 / np.pi
96 if self.debug >= 2:
97 print('Basis before alignment:')
98 print(self.basis)
99 if (
100 self.basis[0][0] ** 2 + self.basis[0][2] ** 2
101 < 0.01 * self.basis[0][1] ** 2
102 ):
103 # First basis vector along y axis - rotate 90 deg along z
104 t = np.array([[0, -1, 0], [1, 0, 0], [0, 0, 1]], float)
105 self.basis = np.dot(self.basis, t)
106 transf = t
107 if self.debug >= 2:
108 print(
109 'Rotating -90 degrees around z axis for numerical '
110 'stability.'
111 )
112 print(self.basis)
113 else:
114 transf = np.identity(3, float)
115 assert abs(np.linalg.det(transf) - 1) < 1e-6
116 # Rotate first basis vector into xy plane
117 theta = math.atan2(self.basis[0, 2], self.basis[0, 0])
118 t = np.array(
119 [
120 [np.cos(theta), 0, -np.sin(theta)],
121 [0, 1, 0],
122 [np.sin(theta), 0, np.cos(theta)],
123 ]
124 )
125 self.basis = np.dot(self.basis, t)
126 transf = np.dot(transf, t)
127 if self.debug >= 2:
128 print(f'Rotating {-theta * degree:f} degrees around y axis.')
129 print(self.basis)
130 assert abs(np.linalg.det(transf) - 1) < 1e-6
131 # Rotate first basis vector to point along x axis
132 theta = math.atan2(self.basis[0, 1], self.basis[0, 0])
133 t = np.array(
134 [
135 [np.cos(theta), -np.sin(theta), 0],
136 [np.sin(theta), np.cos(theta), 0],
137 [0, 0, 1],
138 ]
139 )
140 self.basis = np.dot(self.basis, t)
141 transf = np.dot(transf, t)
142 if self.debug >= 2:
143 print(f'Rotating {-theta * degree:f} degrees around z axis.')
144 print(self.basis)
145 assert abs(np.linalg.det(transf) - 1) < 1e-6
146 # Rotate second basis vector into xy plane
147 theta = math.atan2(self.basis[1, 2], self.basis[1, 1])
148 t = np.array(
149 [
150 [1, 0, 0],
151 [0, np.cos(theta), -np.sin(theta)],
152 [0, np.sin(theta), np.cos(theta)],
153 ]
154 )
155 self.basis = np.dot(self.basis, t)
156 transf = np.dot(transf, t)
157 if self.debug >= 2:
158 print(f'Rotating {-theta * degree:f} degrees around x axis.')
159 print(self.basis)
160 assert abs(np.linalg.det(transf) - 1) < 1e-6
161 # Now we better rotate the atoms as well
162 self.atoms = np.dot(self.atoms, transf)
163 # ... and rotate miller_basis
164 self.miller_basis = np.dot(self.miller_basis, transf)
166 def make_list_of_atoms(self):
167 "Repeat the unit cell."
168 nrep = self.size[0] * self.size[1] * self.size[2]
169 if nrep <= 0:
170 raise ValueError(
171 'Cannot create a non-positive number of unit cells'
172 )
173 # Now the unit cells must be merged.
174 a2 = []
175 e2 = []
176 for i in range(self.size[0]):
177 offset = self.basis[0] * i
178 a2.append(self.atoms + offset[np.newaxis, :])
179 e2.append(self.elements)
180 atoms = np.concatenate(a2)
181 elements = np.concatenate(e2)
182 a2 = []
183 e2 = []
184 for j in range(self.size[1]):
185 offset = self.basis[1] * j
186 a2.append(atoms + offset[np.newaxis, :])
187 e2.append(elements)
188 atoms = np.concatenate(a2)
189 elements = np.concatenate(e2)
190 a2 = []
191 e2 = []
192 for k in range(self.size[2]):
193 offset = self.basis[2] * k
194 a2.append(atoms + offset[np.newaxis, :])
195 e2.append(elements)
196 atoms = np.concatenate(a2)
197 elements = np.concatenate(e2)
198 del a2, e2
199 assert len(atoms) == nrep * len(self.atoms)
200 basis = np.array(
201 [[self.size[0], 0, 0], [0, self.size[1], 0], [0, 0, self.size[2]]]
202 )
203 basis = np.dot(basis, self.basis)
205 # Tiny elements should be replaced by zero. The cutoff is
206 # determined by chop_tolerance which is a class attribute.
207 basis = np.where(np.abs(basis) < self.chop_tolerance, 0.0, basis)
209 # None should be replaced, and memory should be freed.
210 lattice = Lattice(
211 positions=atoms, cell=basis, numbers=elements, pbc=self.pbc
212 )
213 lattice.millerbasis = self.miller_basis
214 # Add info for lattice.surface.AddAdsorbate
215 lattice._addsorbate_info_size = np.array(self.size[:2])
216 return lattice
218 def process_element(self, element):
219 "Extract atomic number from element"
220 # The types that can be elements: integers and strings
221 if self.element_basis is None:
222 if isinstance(element, str):
223 self.atomicnumber = ase.data.atomic_numbers[element]
224 elif isinstance(element, int):
225 self.atomicnumber = element
226 else:
227 raise TypeError(
228 'The symbol argument must be a string or an atomic number.'
229 )
230 else:
231 atomicnumber = []
232 try:
233 if len(element) != max(self.element_basis) + 1:
234 oops = True
235 else:
236 oops = False
237 except TypeError:
238 oops = True
239 if oops:
240 raise TypeError(
241 (
242 'The symbol argument must be a sequence of length %d'
243 + ' (one for each kind of lattice position'
244 )
245 % (max(self.element_basis) + 1,)
246 )
247 for e in element:
248 if isinstance(e, str):
249 atomicnumber.append(ase.data.atomic_numbers[e])
250 elif isinstance(e, int):
251 atomicnumber.append(e)
252 else:
253 raise TypeError(
254 'The symbols argument must be a sequence of strings '
255 'or atomic numbers.'
256 )
257 self.atomicnumber = [atomicnumber[i] for i in self.element_basis]
258 assert len(self.atomicnumber) == len(self.bravais_basis)
260 def convert_to_natural_basis(self):
261 "Convert directions and miller indices to the natural basis."
262 self.directions = np.dot(self.directions, self.inverse_basis)
263 if self.bravais_basis is not None:
264 self.natural_bravais_basis = np.dot(
265 self.bravais_basis, self.inverse_basis
266 )
267 for i in (0, 1, 2):
268 self.directions[i] = reduceindex(self.directions[i])
269 for i in (0, 1, 2):
270 (j, k) = self.other[i]
271 self.miller[i] = reduceindex(
272 self.handedness * cross(self.directions[j], self.directions[k])
273 )
275 def calc_num_atoms(self):
276 v = int(round(abs(np.linalg.det(self.directions))))
277 if self.bravais_basis is None:
278 return v
279 else:
280 return v * len(self.bravais_basis)
282 def make_unit_cell(self):
283 "Make the unit cell."
284 # Make three loops, and find the positions in the integral
285 # lattice. Each time a position is found, the atom is placed
286 # in the real unit cell by put_atom().
287 self.natoms = self.calc_num_atoms()
288 self.nput = 0
289 self.atoms = np.zeros((self.natoms, 3), float)
290 self.elements = np.zeros(self.natoms, int)
291 self.farpoint = sum(self.directions)
292 # printprogress = self.debug and (len(self.atoms) > 250)
293 # Find the radius of the sphere containing the whole system
294 sqrad = 0
295 for i in (0, 1):
296 for j in (0, 1):
297 for k in (0, 1):
298 vect = (
299 i * self.directions[0]
300 + j * self.directions[1]
301 + k * self.directions[2]
302 )
303 if np.dot(vect, vect) > sqrad:
304 sqrad = np.dot(vect, vect)
305 del i, j, k
306 # Loop along first crystal axis (i)
307 for istart, istep in ((0, 1), (-1, -1)):
308 i = istart
309 icont = True
310 while icont:
311 nj = 0
312 for jstart, jstep in ((0, 1), (-1, -1)):
313 j = jstart
314 jcont = True
315 while jcont:
316 nk = 0
317 for kstart, kstep in ((0, 1), (-1, -1)):
318 k = kstart
319 kcont = True
320 while kcont:
321 # Now (i,j,k) loops over Z^3, except that
322 # the loops can be cut off when we get outside
323 # the unit cell.
324 point = np.array((i, j, k))
325 if self.inside(point):
326 self.put_atom(point)
327 nk += 1
328 nj += 1
329 # Is k too high?
330 if np.dot(point, point) > sqrad:
331 assert not self.inside(point)
332 kcont = False
333 k += kstep
334 # Is j too high?
335 if i * i + j * j > sqrad:
336 jcont = False
337 j += jstep
338 # Is i too high?
339 if i * i > sqrad:
340 icont = False
341 i += istep
342 # if printprogress:
343 # perce = int(100*self.nput / len(self.atoms))
344 # if perce > percent + 10:
345 # print ("%d%%" % perce),
346 # percent = perce
347 assert self.nput == self.natoms
349 def inside(self, point):
350 "Is a point inside the unit cell?"
351 return (
352 np.dot(self.miller[0], point) >= 0
353 and np.dot(self.miller[0], point - self.farpoint) < 0
354 and np.dot(self.miller[1], point) >= 0
355 and np.dot(self.miller[1], point - self.farpoint) < 0
356 and np.dot(self.miller[2], point) >= 0
357 and np.dot(self.miller[2], point - self.farpoint) < 0
358 )
360 def put_atom(self, point):
361 "Place an atom given its integer coordinates."
362 if self.bravais_basis is None:
363 # No basis - just place a single atom
364 pos = np.dot(point, self.crystal_basis)
365 if self.debug >= 2:
366 print(
367 'Placing an atom at (%d,%d,%d) ~ (%.3f, %.3f, %.3f).'
368 % (tuple(point) + tuple(pos))
369 )
370 self.atoms[self.nput] = pos
371 self.elements[self.nput] = self.atomicnumber
372 self.nput += 1
373 else:
374 for i, offset in enumerate(self.natural_bravais_basis):
375 pos = np.dot(point + offset, self.crystal_basis)
376 if self.debug >= 2:
377 print(
378 'Placing an atom at (%d+%f, %d+%f, %d+%f) ~ '
379 '(%.3f, %.3f, %.3f).'
380 % (
381 point[0],
382 offset[0],
383 point[1],
384 offset[1],
385 point[2],
386 offset[2],
387 pos[0],
388 pos[1],
389 pos[2],
390 )
391 )
392 self.atoms[self.nput] = pos
393 if self.element_basis is None:
394 self.elements[self.nput] = self.atomicnumber
395 else:
396 self.elements[self.nput] = self.atomicnumber[i]
397 self.nput += 1
399 def find_directions(self, directions, miller):
400 """
401 Find missing directions and miller indices from the specified ones.
402 """
403 directions = np.asarray(directions).tolist()
404 miller = list(miller) # np.asarray(miller).tolist()
405 # If no directions etc are specified, use a sensible default.
406 if directions == [None, None, None] and miller == [None, None, None]:
407 directions = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
408 # Now fill in missing directions and miller indices. This is an
409 # iterative process.
410 change = 1
411 while change:
412 change = False
413 missing = 0
414 for i in (0, 1, 2):
415 j, k = self.other[i]
416 if directions[i] is None:
417 missing += 1
418 if miller[j] is not None and miller[k] is not None:
419 directions[i] = reduceindex(cross(miller[j], miller[k]))
420 change = True
421 if self.debug >= 2:
422 print(
423 'Calculating directions[%d] from miller '
424 'indices' % i
425 )
426 if miller[i] is None:
427 missing += 1
428 if directions[j] is not None and directions[k] is not None:
429 miller[i] = reduceindex(
430 cross(directions[j], directions[k])
431 )
432 change = True
433 if self.debug >= 2:
434 print('Calculating miller[%d] from directions' % i)
435 if missing:
436 raise ValueError(
437 'Specification of directions and miller indices is incomplete.'
438 )
439 # Make sure that everything is Numeric arrays
440 self.directions = np.array(directions)
441 self.miller = np.array(miller)
442 # Check for zero-volume unit cell
443 if abs(np.linalg.det(self.directions)) < 1e-10:
444 raise ValueError(
445 'The direction vectors are linearly dependent '
446 '(unit cell volume would be zero)'
447 )
448 # Check for left-handed coordinate system
449 if np.linalg.det(self.directions) < 0:
450 print('WARNING: Creating a left-handed coordinate system!')
451 self.miller = -self.miller
452 self.handedness = -1
453 else:
454 self.handedness = 1
455 # Now check for consistency
456 for i in (0, 1, 2):
457 (j, k) = self.other[i]
458 m = reduceindex(
459 self.handedness * cross(self.directions[j], self.directions[k])
460 )
461 if sum(np.not_equal(m, self.miller[i])):
462 print(
463 'ERROR: Miller index %s is inconsisten with '
464 'directions %d and %d' % (i, j, k)
465 )
466 print('Miller indices:')
467 print(str(self.miller))
468 print('Directions:')
469 print(str(self.directions))
470 raise ValueError(
471 'Inconsistent specification of miller indices and '
472 'directions.'
473 )
475 def print_directions_and_miller(self, txt=''):
476 "Print direction vectors and Miller indices."
477 print(f'Direction vectors of unit cell{txt}:')
478 for i in (0, 1, 2):
479 print(' ', self.directions[i])
480 print(f'Miller indices of surfaces{txt}:')
481 for i in (0, 1, 2):
482 print(' ', self.miller[i])
485class MillerInfo:
486 """Mixin class to provide information about Miller indices."""
488 def miller_to_direction(self, miller):
489 """Returns the direction corresponding to a given Miller index."""
490 return np.dot(miller, self.millerbasis)
493class Lattice(Atoms, MillerInfo):
494 """List of atoms initially containing a regular lattice of atoms.
496 A part from the usual list of atoms methods this list of atoms type
497 also has a method, `miller_to_direction`, used to convert from Miller
498 indices to directions in the coordinate system of the lattice.
499 """
502# Helper functions
503def cross(a, b):
504 """The cross product of two vectors."""
505 return np.array(
506 (
507 a[1] * b[2] - b[1] * a[2],
508 a[2] * b[0] - b[2] * a[0],
509 a[0] * b[1] - b[0] * a[1],
510 )
511 )
514def reduceindex(M):
515 """Reduce Miller index to the lowest equivalent integers."""
516 oldM = M
517 g = math.gcd(M[0], M[1])
518 h = math.gcd(g, M[2])
519 while h != 1:
520 if h == 0:
521 raise ValueError(
522 'Division by zero: Are the miller indices linearly dependent?'
523 )
524 M = M // h
525 g = math.gcd(M[0], M[1])
526 h = math.gcd(g, M[2])
527 if np.dot(oldM, M) > 0:
528 return M
529 else:
530 return -M