Coverage for ase/build/surface.py: 84.10%
239 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"""Helper functions for creating the most common surfaces and related tasks.
3The helper functions can create the most common low-index surfaces,
4add vacuum layers and add adsorbates.
6"""
8from math import sqrt
9from operator import itemgetter
11import numpy as np
13from ase.atom import Atom
14from ase.atoms import Atoms
15from ase.data import atomic_numbers, reference_states
16from ase.lattice.cubic import FaceCenteredCubic
19def fcc100(symbol, size, a=None, vacuum=None, orthogonal=True, periodic=False):
20 """FCC(100) surface.
22 Supported special adsorption sites: 'ontop', 'bridge', 'hollow'."""
23 if not orthogonal:
24 raise NotImplementedError("Can't do non-orthogonal cell yet!")
26 return _surface(
27 symbol,
28 'fcc',
29 '100',
30 size,
31 a,
32 None,
33 vacuum,
34 periodic=periodic,
35 orthogonal=orthogonal,
36 )
39def fcc110(symbol, size, a=None, vacuum=None, orthogonal=True, periodic=False):
40 """FCC(110) surface.
42 Supported special adsorption sites: 'ontop', 'longbridge',
43 'shortbridge', 'hollow'."""
44 if not orthogonal:
45 raise NotImplementedError("Can't do non-orthogonal cell yet!")
47 return _surface(
48 symbol,
49 'fcc',
50 '110',
51 size,
52 a,
53 None,
54 vacuum,
55 periodic=periodic,
56 orthogonal=orthogonal,
57 )
60def bcc100(symbol, size, a=None, vacuum=None, orthogonal=True, periodic=False):
61 """BCC(100) surface.
63 Supported special adsorption sites: 'ontop', 'bridge', 'hollow'."""
64 if not orthogonal:
65 raise NotImplementedError("Can't do non-orthogonal cell yet!")
67 return _surface(
68 symbol,
69 'bcc',
70 '100',
71 size,
72 a,
73 None,
74 vacuum,
75 periodic=periodic,
76 orthogonal=orthogonal,
77 )
80def bcc110(symbol, size, a=None, vacuum=None, orthogonal=False, periodic=False):
81 """BCC(110) surface.
83 Supported special adsorption sites: 'ontop', 'longbridge',
84 'shortbridge', 'hollow'.
86 Use *orthogonal=True* to get an orthogonal unit cell - works only
87 for size=(i,j,k) with j even."""
88 return _surface(
89 symbol,
90 'bcc',
91 '110',
92 size,
93 a,
94 None,
95 vacuum,
96 periodic=periodic,
97 orthogonal=orthogonal,
98 )
101def bcc111(symbol, size, a=None, vacuum=None, orthogonal=False, periodic=False):
102 """BCC(111) surface.
104 Supported special adsorption sites: 'ontop'.
106 Use *orthogonal=True* to get an orthogonal unit cell - works only
107 for size=(i,j,k) with j even."""
108 return _surface(
109 symbol,
110 'bcc',
111 '111',
112 size,
113 a,
114 None,
115 vacuum,
116 periodic=periodic,
117 orthogonal=orthogonal,
118 )
121def fcc111(symbol, size, a=None, vacuum=None, orthogonal=False, periodic=False):
122 """FCC(111) surface.
124 Supported special adsorption sites: 'ontop', 'bridge', 'fcc' and 'hcp'.
126 Use *orthogonal=True* to get an orthogonal unit cell - works only
127 for size=(i,j,k) with j even."""
128 return _surface(
129 symbol,
130 'fcc',
131 '111',
132 size,
133 a,
134 None,
135 vacuum,
136 periodic=periodic,
137 orthogonal=orthogonal,
138 )
141def hcp0001(
142 symbol, size, a=None, c=None, vacuum=None, orthogonal=False, periodic=False
143):
144 """HCP(0001) surface.
146 Supported special adsorption sites: 'ontop', 'bridge', 'fcc' and 'hcp'.
148 Use *orthogonal=True* to get an orthogonal unit cell - works only
149 for size=(i,j,k) with j even."""
150 return _surface(
151 symbol,
152 'hcp',
153 '0001',
154 size,
155 a,
156 c,
157 vacuum,
158 periodic=periodic,
159 orthogonal=orthogonal,
160 )
163def hcp10m10(
164 symbol, size, a=None, c=None, vacuum=None, orthogonal=True, periodic=False
165):
166 """HCP(10m10) surface.
168 Supported special adsorption sites: 'ontop'.
170 Works only for size=(i,j,k) with j even."""
171 if not orthogonal:
172 raise NotImplementedError("Can't do non-orthogonal cell yet!")
174 return _surface(
175 symbol,
176 'hcp',
177 '10m10',
178 size,
179 a,
180 c,
181 vacuum,
182 periodic=periodic,
183 orthogonal=orthogonal,
184 )
187def diamond100(
188 symbol, size, a=None, vacuum=None, orthogonal=True, periodic=False
189):
190 """DIAMOND(100) surface.
192 Supported special adsorption sites: 'ontop'."""
193 if not orthogonal:
194 raise NotImplementedError("Can't do non-orthogonal cell yet!")
196 return _surface(
197 symbol,
198 'diamond',
199 '100',
200 size,
201 a,
202 None,
203 vacuum,
204 periodic=periodic,
205 orthogonal=orthogonal,
206 )
209def diamond111(
210 symbol, size, a=None, vacuum=None, orthogonal=False, periodic=False
211):
212 """DIAMOND(111) surface.
214 Supported special adsorption sites: 'ontop'."""
216 if orthogonal:
217 raise NotImplementedError("Can't do orthogonal cell yet!")
218 return _surface(
219 symbol,
220 'diamond',
221 '111',
222 size,
223 a,
224 None,
225 vacuum,
226 periodic=periodic,
227 orthogonal=orthogonal,
228 )
231def add_adsorbate(
232 slab, adsorbate, height, position=(0, 0), offset=None, mol_index=0
233):
234 """Add an adsorbate to a surface.
236 This function adds an adsorbate to a slab. If the slab is
237 produced by one of the utility functions in ase.build, it
238 is possible to specify the position of the adsorbate by a keyword
239 (the supported keywords depend on which function was used to
240 create the slab).
242 If the adsorbate is a molecule, the atom indexed by the mol_index
243 optional argument is positioned on top of the adsorption position
244 on the surface, and it is the responsibility of the user to orient
245 the adsorbate in a sensible way.
247 This function can be called multiple times to add more than one
248 adsorbate.
250 Parameters
251 ----------
253 slab: The surface onto which the adsorbate should be added.
255 adsorbate: The adsorbate. Must be one of the following three types:
256 A string containing the chemical symbol for a single atom.
257 An atom object.
258 An atoms object (for a molecular adsorbate).
260 height: Height above the surface.
262 position: The x-y position of the adsorbate, either as a tuple of
263 two numbers or as a keyword (if the surface is produced by one
264 of the functions in ase.build).
266 offset (default: None): Offsets the adsorbate by a number of unit
267 cells. Mostly useful when adding more than one adsorbate.
269 mol_index (default: 0): If the adsorbate is a molecule, index of
270 the atom to be positioned above the location specified by the
271 position argument.
273 Note *position* is given in absolute xy coordinates (or as
274 a keyword), whereas offset is specified in unit cells. This
275 can be used to give the positions in units of the unit cell by
276 using *offset* instead.
278 """
279 info = slab.info.get('adsorbate_info', {})
281 pos = np.array([0.0, 0.0]) # (x, y) part
282 spos = np.array([0.0, 0.0]) # part relative to unit cell
283 if offset is not None:
284 spos += np.asarray(offset, float)
286 if isinstance(position, str):
287 # A site-name:
288 if 'sites' not in info:
289 raise TypeError(
290 'If the atoms are not made by an '
291 + 'ase.build function, '
292 + 'position cannot be a name.'
293 )
294 if position not in info['sites']:
295 raise TypeError(f'Adsorption site {position} not supported.')
296 spos += info['sites'][position]
297 else:
298 pos += position
300 if 'cell' in info:
301 cell = info['cell']
302 else:
303 cell = slab.get_cell()[:2, :2]
305 pos += np.dot(spos, cell)
307 # Convert the adsorbate to an Atoms object
308 if isinstance(adsorbate, Atoms):
309 ads = adsorbate
310 elif isinstance(adsorbate, Atom):
311 ads = Atoms([adsorbate])
312 else:
313 # Assume it is a string representing a single Atom
314 ads = Atoms([Atom(adsorbate)])
316 # Get the z-coordinate:
317 if 'top layer atom index' in info:
318 a = info['top layer atom index']
319 else:
320 a = slab.positions[:, 2].argmax()
321 if 'adsorbate_info' not in slab.info:
322 slab.info['adsorbate_info'] = {}
323 slab.info['adsorbate_info']['top layer atom index'] = a
324 z = slab.positions[a, 2] + height
326 # Move adsorbate into position
327 ads.translate([pos[0], pos[1], z] - ads.positions[mol_index])
329 # Attach the adsorbate
330 slab.extend(ads)
333def add_vacuum(atoms, vacuum):
334 """Add vacuum layer to the atoms.
336 Parameters
337 ----------
339 atoms: Atoms object
340 Most likely created by one of the surface functions.
341 vacuum: float
342 The thickness of the vacuum layer (in Angstrom).
343 """
344 uc = atoms.get_cell()
345 normal = np.cross(uc[0], uc[1])
346 costheta = np.dot(normal, uc[2]) / np.sqrt(
347 np.dot(normal, normal) * np.dot(uc[2], uc[2])
348 )
349 length = np.sqrt(np.dot(uc[2], uc[2]))
350 newlength = length + vacuum / costheta
351 uc[2] *= newlength / length
352 atoms.set_cell(uc)
355def create_tags(size) -> np.ndarray:
356 """Function to create layer tags."""
357 # tag atoms by layer
358 # create blocks of descending integers of length size[0]*size[1]
359 return np.arange(size[2], 0, -1).repeat(size[0] * size[1])
362def _surface(
363 symbol, structure, face, size, a, c, vacuum, periodic, orthogonal=True
364):
365 """Function to build often used surfaces.
367 Don't call this function directly - use fcc100, fcc110, bcc111, ..."""
369 Z = atomic_numbers[symbol]
371 if a is None:
372 sym = reference_states[Z]['symmetry']
373 if sym != structure:
374 raise ValueError(
375 f"Can't guess lattice constant for {structure}-{symbol}!"
376 )
377 a = reference_states[Z]['a']
379 if structure == 'hcp' and c is None:
380 if reference_states[Z]['symmetry'] == 'hcp':
381 c = reference_states[Z]['c/a'] * a
382 else:
383 c = sqrt(8 / 3.0) * a
385 positions = np.empty((size[2], size[1], size[0], 3))
386 positions[..., 0] = np.arange(size[0]).reshape((1, 1, -1))
387 positions[..., 1] = np.arange(size[1]).reshape((1, -1, 1))
388 positions[..., 2] = np.arange(size[2]).reshape((-1, 1, 1))
390 numbers = np.ones(size[0] * size[1] * size[2], int) * Z
392 slab = Atoms(
393 numbers, tags=create_tags(size), pbc=(True, True, periodic), cell=size
394 )
396 surface_cell = None
397 sites = {'ontop': (0, 0)}
398 surf = structure + face
399 if surf == 'fcc100':
400 cell = (sqrt(0.5), sqrt(0.5), 0.5)
401 positions[-2::-2, ..., :2] += 0.5
402 sites.update({'hollow': (0.5, 0.5), 'bridge': (0.5, 0)})
403 elif surf == 'diamond100':
404 cell = (sqrt(0.5), sqrt(0.5), 0.5 / 2)
405 positions[-4::-4, ..., :2] += (0.5, 0.5)
406 positions[-3::-4, ..., :2] += (0.0, 0.5)
407 positions[-2::-4, ..., :2] += (0.0, 0.0)
408 positions[-1::-4, ..., :2] += (0.5, 0.0)
409 elif surf == 'fcc110':
410 cell = (1.0, sqrt(0.5), sqrt(0.125))
411 positions[-2::-2, ..., :2] += 0.5
412 sites.update(
413 {
414 'hollow': (0.5, 0.5),
415 'longbridge': (0.5, 0),
416 'shortbridge': (0, 0.5),
417 }
418 )
419 elif surf == 'bcc100':
420 cell = (1.0, 1.0, 0.5)
421 positions[-2::-2, ..., :2] += 0.5
422 sites.update({'hollow': (0.5, 0.5), 'bridge': (0.5, 0)})
423 else:
424 if orthogonal and size[1] % 2 == 1:
425 raise ValueError(
426 (
427 "Can't make orthorhombic cell with size=%r. "
428 % (tuple(size),)
429 )
430 + 'Second number in size must be even.'
431 )
432 if surf == 'fcc111':
433 cell = (sqrt(0.5), sqrt(0.375), 1 / sqrt(3))
434 if orthogonal:
435 positions[-1::-3, 1::2, :, 0] += 0.5
436 positions[-2::-3, 1::2, :, 0] += 0.5
437 positions[-3::-3, 1::2, :, 0] -= 0.5
438 positions[-2::-3, ..., :2] += (0.0, 2.0 / 3)
439 positions[-3::-3, ..., :2] += (0.5, 1.0 / 3)
440 else:
441 positions[-2::-3, ..., :2] += (-1.0 / 3, 2.0 / 3)
442 positions[-3::-3, ..., :2] += (1.0 / 3, 1.0 / 3)
443 sites.update(
444 {
445 'bridge': (0.5, 0),
446 'fcc': (1.0 / 3, 1.0 / 3),
447 'hcp': (2.0 / 3, 2.0 / 3),
448 }
449 )
450 elif surf == 'diamond111':
451 cell = (sqrt(0.5), sqrt(0.375), 1 / sqrt(3) / 2)
452 assert not orthogonal
453 positions[-1::-6, ..., :3] += (0.0, 0.0, 0.5)
454 positions[-2::-6, ..., :2] += (0.0, 0.0)
455 positions[-3::-6, ..., :3] += (-1.0 / 3, 2.0 / 3, 0.5)
456 positions[-4::-6, ..., :2] += (-1.0 / 3, 2.0 / 3)
457 positions[-5::-6, ..., :3] += (1.0 / 3, 1.0 / 3, 0.5)
458 positions[-6::-6, ..., :2] += (1.0 / 3, 1.0 / 3)
459 elif surf == 'hcp0001':
460 cell = (1.0, sqrt(0.75), 0.5 * c / a)
461 if orthogonal:
462 positions[:, 1::2, :, 0] += 0.5
463 positions[-2::-2, ..., :2] += (0.0, 2.0 / 3)
464 else:
465 positions[-2::-2, ..., :2] += (-1.0 / 3, 2.0 / 3)
466 sites.update(
467 {
468 'bridge': (0.5, 0),
469 'fcc': (1.0 / 3, 1.0 / 3),
470 'hcp': (2.0 / 3, 2.0 / 3),
471 }
472 )
473 elif surf == 'hcp10m10':
474 cell = (1.0, 0.5 * c / a, sqrt(0.75))
475 assert orthogonal
476 positions[-2::-2, ..., 0] += 0.5
477 positions[:, ::2, :, 2] += 2.0 / 3
478 elif surf == 'bcc110':
479 cell = (1.0, sqrt(0.5), sqrt(0.5))
480 if orthogonal:
481 positions[:, 1::2, :, 0] += 0.5
482 positions[-2::-2, ..., :2] += (0.0, 1.0)
483 else:
484 positions[-2::-2, ..., :2] += (-0.5, 1.0)
485 sites.update(
486 {
487 'shortbridge': (0, 0.5),
488 'longbridge': (0.5, 0),
489 'hollow': (0.375, 0.25),
490 }
491 )
492 elif surf == 'bcc111':
493 cell = (sqrt(2), sqrt(1.5), sqrt(3) / 6)
494 if orthogonal:
495 positions[-1::-3, 1::2, :, 0] += 0.5
496 positions[-2::-3, 1::2, :, 0] += 0.5
497 positions[-3::-3, 1::2, :, 0] -= 0.5
498 positions[-2::-3, ..., :2] += (0.0, 2.0 / 3)
499 positions[-3::-3, ..., :2] += (0.5, 1.0 / 3)
500 else:
501 positions[-2::-3, ..., :2] += (-1.0 / 3, 2.0 / 3)
502 positions[-3::-3, ..., :2] += (1.0 / 3, 1.0 / 3)
503 sites.update({'hollow': (1.0 / 3, 1.0 / 3)})
504 else:
505 2 / 0
507 surface_cell = a * np.array([(cell[0], 0), (cell[0] / 2, cell[1])])
508 if not orthogonal:
509 cell = np.array(
510 [(cell[0], 0, 0), (cell[0] / 2, cell[1], 0), (0, 0, cell[2])]
511 )
513 if surface_cell is None:
514 surface_cell = a * np.diag(cell[:2])
516 if isinstance(cell, tuple):
517 cell = np.diag(cell)
519 slab.set_positions(positions.reshape((-1, 3)))
520 slab.set_cell([a * v * n for v, n in zip(cell, size)], scale_atoms=True)
522 if not periodic:
523 slab.cell[2] = 0.0
525 if vacuum is not None:
526 slab.center(vacuum, axis=2)
528 if 'adsorbate_info' not in slab.info:
529 slab.info.update({'adsorbate_info': {}})
531 slab.info['adsorbate_info']['cell'] = surface_cell
532 slab.info['adsorbate_info']['sites'] = sites
533 return slab
536def fcc211(symbol, size, a=None, vacuum=None, orthogonal=True):
537 """FCC(211) surface.
539 Does not currently support special adsorption sites.
541 Currently only implemented for *orthogonal=True* with size specified
542 as (i, j, k), where i, j, and k are number of atoms in each direction.
543 i must be divisible by 3 to accommodate the step width.
544 """
545 if not orthogonal:
546 raise NotImplementedError('Only implemented for orthogonal unit cells.')
547 if size[0] % 3 != 0:
548 raise NotImplementedError(
549 'First dimension of size must be divisible by 3.'
550 )
551 atoms = FaceCenteredCubic(
552 symbol,
553 directions=[[1, -1, -1], [0, 2, -2], [2, 1, 1]],
554 miller=(None, None, (2, 1, 1)),
555 latticeconstant=a,
556 size=(1, 1, 1),
557 pbc=True,
558 )
559 z = (size[2] + 1) // 2
560 atoms = atoms.repeat((size[0] // 3, size[1], z))
561 if size[2] % 2: # Odd: remove bottom layer and shrink cell.
562 remove_list = [atom.index for atom in atoms if atom.z < atoms[1].z]
563 del atoms[remove_list]
564 dz = atoms[0].z
565 atoms.translate((0.0, 0.0, -dz))
566 atoms.cell[2][2] -= dz
568 atoms.cell[2] = 0.0
569 atoms.pbc[2] = False
570 if vacuum:
571 atoms.center(vacuum, axis=2)
573 # Renumber systematically from top down.
574 orders = [
575 (
576 atom.index,
577 round(atom.x, 3),
578 round(atom.y, 3),
579 -round(atom.z, 3),
580 atom.index,
581 )
582 for atom in atoms
583 ]
584 orders.sort(key=itemgetter(3, 1, 2))
585 newatoms = atoms.copy()
586 for index, order in enumerate(orders):
587 newatoms[index].position = atoms[order[0]].position.copy()
589 # Add empty 'sites' dictionary for consistency with other functions
590 newatoms.info['adsorbate_info'] = {'sites': {}}
591 return newatoms
594def mx2(
595 formula='MoS2',
596 kind='2H',
597 a=3.18,
598 thickness=3.19,
599 size=(1, 1, 1),
600 vacuum=None,
601):
602 """Create three-layer 2D materials with hexagonal structure.
604 This can be used for e.g. metal dichalcogenides :mol:`MX_2` 2D structures
605 such as :mol:`MoS_2`.
607 https://en.wikipedia.org/wiki/Transition_metal_dichalcogenide_monolayers
609 Parameters
610 ----------
611 kind : {'2H', '1T'}, default: '2H'
613 - '2H': mirror-plane symmetry
614 - '1T': inversion symmetry
615 """
616 if kind == '2H':
617 basis = [
618 (0, 0, 0),
619 (2 / 3, 1 / 3, 0.5 * thickness),
620 (2 / 3, 1 / 3, -0.5 * thickness),
621 ]
622 elif kind == '1T':
623 basis = [
624 (0, 0, 0),
625 (2 / 3, 1 / 3, 0.5 * thickness),
626 (1 / 3, 2 / 3, -0.5 * thickness),
627 ]
628 else:
629 raise ValueError('Structure not recognized:', kind)
631 cell = [[a, 0, 0], [-a / 2, a * 3**0.5 / 2, 0], [0, 0, 0]]
633 atoms = Atoms(formula, cell=cell, pbc=(1, 1, 0))
634 atoms.set_scaled_positions(basis)
635 if vacuum is not None:
636 atoms.center(vacuum, axis=2)
637 atoms = atoms.repeat(size)
638 return atoms
641def graphene(formula='C2', a=2.460, thickness=0.0, size=(1, 1, 1), vacuum=None):
642 """Create a graphene monolayer structure.
644 Parameters
645 ----------
646 thickness : float, default: 0.0
647 Thickness of the layer; maybe for a buckled structure like silicene.
648 """
649 cell = [[a, 0, 0], [-a / 2, a * 3**0.5 / 2, 0], [0, 0, 0]]
650 basis = [[0, 0, -0.5 * thickness], [2 / 3, 1 / 3, 0.5 * thickness]]
651 atoms = Atoms(formula, cell=cell, pbc=(1, 1, 0))
652 atoms.set_scaled_positions(basis)
653 if vacuum is not None:
654 atoms.center(vacuum, axis=2)
655 atoms = atoms.repeat(size)
656 return atoms
659def _all_surface_functions():
660 # Convenient for debugging.
661 d = {
662 func.__name__: func
663 for func in [
664 fcc100,
665 fcc110,
666 bcc100,
667 bcc110,
668 bcc111,
669 fcc111,
670 hcp0001,
671 hcp10m10,
672 diamond100,
673 diamond111,
674 fcc111,
675 mx2,
676 graphene,
677 ]
678 }
679 return d