Coverage for ase/build/tools.py: 72.99%
211 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.build.niggli import niggli_reduce_cell
6def cut(
7 atoms,
8 a=(1, 0, 0),
9 b=(0, 1, 0),
10 c=None,
11 clength=None,
12 origo=(0, 0, 0),
13 nlayers=None,
14 extend=1.0,
15 tolerance=0.01,
16 maxatoms=None,
17):
18 """Cuts out a cell defined by *a*, *b*, *c* and *origo* from a
19 sufficiently repeated copy of *atoms*.
21 Typically, this function is used to create slabs of different
22 sizes and orientations. The vectors *a*, *b* and *c* are in scaled
23 coordinates and defines the returned cell and should normally be
24 integer-valued in order to end up with a periodic
25 structure. However, for systems with sub-translations, like fcc,
26 integer multiples of 1/2 or 1/3 might also make sense for some
27 directions (and will be treated correctly).
29 Parameters
30 ----------
32 atoms: Atoms instance
33 This should correspond to a repeatable unit cell.
34 a: int | 3 floats
35 The a-vector in scaled coordinates of the cell to cut out. If
36 integer, the a-vector will be the scaled vector from *origo* to the
37 atom with index *a*.
38 b: int | 3 floats
39 The b-vector in scaled coordinates of the cell to cut out. If
40 integer, the b-vector will be the scaled vector from *origo* to the
41 atom with index *b*.
42 c: None | int | 3 floats
43 The c-vector in scaled coordinates of the cell to cut out.
44 if integer, the c-vector will be the scaled vector from *origo* to
45 the atom with index *c*.
46 If *None* it will be along cross(a, b) converted to real space
47 and normalised with the cube root of the volume. Note that this
48 in general is not perpendicular to a and b for non-cubic
49 systems. For cubic systems however, this is redused to
50 c = cross(a, b).
51 clength: None | float
52 If not None, the length of the c-vector will be fixed to
53 *clength* Angstroms. Should not be used together with
54 *nlayers*.
55 origo: int | 3 floats
56 Position of origo of the new cell in scaled coordinates. If
57 integer, the position of the atom with index *origo* is used.
58 nlayers: None | int
59 If *nlayers* is not *None*, the returned cell will have
60 *nlayers* atomic layers in the c-direction.
61 extend: 1 or 3 floats
62 The *extend* argument scales the effective cell in which atoms
63 will be included. It must either be three floats or a single
64 float scaling all 3 directions. By setting to a value just
65 above one, e.g. 1.05, it is possible to all the corner and
66 edge atoms in the returned cell. This will of cause make the
67 returned cell non-repeatable, but is very useful for
68 visualisation.
69 tolerance: float
70 Determines what is defined as a plane. All atoms within
71 *tolerance* Angstroms from a given plane will be considered to
72 belong to that plane.
73 maxatoms: None | int
74 This option is used to auto-tune *tolerance* when *nlayers* is
75 given for high zone axis systems. For high zone axis one
76 needs to reduce *tolerance* in order to distinguise the atomic
77 planes, resulting in the more atoms will be added and
78 eventually MemoryError. A too small *tolerance*, on the other
79 hand, might result in inproper splitting of atomic planes and
80 that too few layers are returned. If *maxatoms* is not None,
81 *tolerance* will automatically be gradually reduced until
82 *nlayers* atomic layers is obtained, when the number of atoms
83 exceeds *maxatoms*.
85 Examples
86 --------
87 Create an aluminium (111) slab with three layers.
89 >>> import ase
90 >>> from ase.spacegroup import crystal
91 >>> from ase.build.tools import cut
93 # First, a unit cell of Al
94 >>> a = 4.05
95 >>> aluminium = crystal('Al', [(0,0,0)], spacegroup=225,
96 ... cellpar=[a, a, a, 90, 90, 90])
98 # Then cut out the slab
99 >>> al111 = cut(aluminium, (1,-1,0), (0,1,-1), nlayers=3)
101 Example: Visualisation of the skutterudite unit cell
103 >>> from ase.spacegroup import crystal
104 >>> from ase.build.tools import cut
106 # Again, create a skutterudite unit cell
107 >>> a = 9.04
108 >>> skutterudite = crystal(
109 ... ('Co', 'Sb'),
110 ... basis=[(0.25,0.25,0.25), (0.0, 0.335, 0.158)],
111 ... spacegroup=204,
112 ... cellpar=[a, a, a, 90, 90, 90])
114 # Then use *origo* to put 'Co' at the corners and *extend* to
115 # include all corner and edge atoms.
116 >>> s = cut(skutterudite, origo=(0.25, 0.25, 0.25), extend=1.01)
117 >>> ase.view(s) # doctest:+SKIP
118 """
119 atoms = atoms.copy()
120 cell = atoms.cell
122 if isinstance(origo, int):
123 origo = atoms.get_scaled_positions()[origo]
124 origo = np.array(origo, dtype=float)
126 scaled = (atoms.get_scaled_positions() - origo) % 1.0
127 scaled %= 1.0 # needed to ensure that all numbers are *less* than one
128 atoms.set_scaled_positions(scaled)
130 if isinstance(a, int):
131 a = scaled[a] - origo
132 if isinstance(b, int):
133 b = scaled[b] - origo
134 if isinstance(c, int):
135 c = scaled[c] - origo
137 a = np.array(a, dtype=float)
138 b = np.array(b, dtype=float)
139 if c is None:
140 metric = np.dot(cell, cell.T)
141 vol = np.sqrt(np.linalg.det(metric))
142 h = np.cross(a, b)
143 H = np.linalg.solve(metric.T, h.T)
144 c = vol * H / vol ** (1.0 / 3.0)
145 c = np.array(c, dtype=float)
147 if nlayers:
148 # Recursive increase the length of c until we have at least
149 # *nlayers* atomic layers parallel to the a-b plane
150 while True:
151 at = cut(
152 atoms, a, b, c, origo=origo, extend=extend, tolerance=tolerance
153 )
154 scaled = at.get_scaled_positions()
155 d = scaled[:, 2]
156 keys = np.argsort(d)
157 ikeys = np.argsort(keys)
158 tol = tolerance
159 while True:
160 mask = np.concatenate(([True], np.diff(d[keys]) > tol))
161 tags = np.cumsum(mask)[ikeys] - 1
162 levels = d[keys][mask]
163 if (
164 maxatoms is None
165 or len(at) < maxatoms
166 or len(levels) > nlayers
167 ):
168 break
169 tol *= 0.9
170 if len(levels) > nlayers:
171 break
172 c *= 2
174 at.cell[2] *= levels[nlayers]
175 return at[tags < nlayers]
177 newcell = np.dot(np.array([a, b, c]), cell)
178 if nlayers is None and clength is not None:
179 newcell[2, :] *= clength / np.linalg.norm(newcell[2])
181 # Create a new atoms object, repeated and translated such that
182 # it completely covers the new cell
183 scorners_newcell = np.array(
184 [
185 [0.0, 0.0, 0.0],
186 [0.0, 0.0, 1.0],
187 [0.0, 1.0, 0.0],
188 [0.0, 1.0, 1.0],
189 [1.0, 0.0, 0.0],
190 [1.0, 0.0, 1.0],
191 [1.0, 1.0, 0.0],
192 [1.0, 1.0, 1.0],
193 ]
194 )
195 corners = np.dot(scorners_newcell, newcell * extend)
196 scorners = np.linalg.solve(cell.T, corners.T).T
197 rep = np.ceil(np.ptp(scorners, axis=0)).astype('int') + 1
198 trans = np.dot(np.floor(scorners.min(axis=0)), cell)
199 atoms = atoms.repeat(rep)
200 atoms.translate(trans)
201 atoms.set_cell(newcell)
203 # Mask out atoms outside new cell
204 stol = 0.1 * tolerance # scaled tolerance, XXX
205 maskcell = atoms.cell * extend
206 sp = np.linalg.solve(maskcell.T, (atoms.positions).T).T
207 mask = np.all(np.logical_and(-stol <= sp, sp < 1 - stol), axis=1)
208 atoms = atoms[mask]
209 return atoms
212class IncompatibleCellError(ValueError):
213 """Exception raised if stacking fails due to incompatible cells
214 between *atoms1* and *atoms2*."""
217def stack(
218 atoms1,
219 atoms2,
220 axis=2,
221 cell=None,
222 fix=0.5,
223 maxstrain=0.5,
224 distance=None,
225 reorder=False,
226 output_strained=False,
227):
228 """Return a new Atoms instance with *atoms2* stacked on top of
229 *atoms1* along the given axis. Periodicity in all directions is
230 ensured.
232 The size of the final cell is determined by *cell*, except
233 that the length alongh *axis* will be the sum of
234 *atoms1.cell[axis]* and *atoms2.cell[axis]*. If *cell* is None,
235 it will be interpolated between *atoms1* and *atoms2*, where
236 *fix* determines their relative weight. Hence, if *fix* equals
237 zero, the final cell will be determined purely from *atoms1* and
238 if *fix* equals one, it will be determined purely from
239 *atoms2*.
241 An ase.geometry.IncompatibleCellError exception is raised if the
242 cells of *atoms1* and *atoms2* are incompatible, e.g. if the far
243 corner of the unit cell of either *atoms1* or *atoms2* is
244 displaced more than *maxstrain*. Setting *maxstrain* to None
245 disables this check.
247 If *distance* is not None, the size of the final cell, along the
248 direction perpendicular to the interface, will be adjusted such
249 that the distance between the closest atoms in *atoms1* and
250 *atoms2* will be equal to *distance*. This option uses
251 scipy.optimize.fmin() and hence require scipy to be installed.
253 If *reorder* is True, then the atoms will be reordered such that
254 all atoms with the same symbol will follow sequencially after each
255 other, eg: 'Al2MnAl10Fe' -> 'Al12FeMn'.
257 If *output_strained* is True, then the strained versions of
258 *atoms1* and *atoms2* are returned in addition to the stacked
259 structure.
261 Example: Create an Ag(110)-Si(110) interface with three atomic layers
262 on each side.
264 >>> import ase
265 >>> from ase.spacegroup import crystal
266 >>> from ase.build.tools import cut, stack
267 >>>
268 >>> a_ag = 4.09
269 >>> ag = crystal(['Ag'], basis=[(0,0,0)], spacegroup=225,
270 ... cellpar=[a_ag, a_ag, a_ag, 90., 90., 90.])
271 >>> ag110 = cut(ag, (0, 0, 3), (-1.5, 1.5, 0), nlayers=3)
272 >>>
273 >>> a_si = 5.43
274 >>> si = crystal(['Si'], basis=[(0,0,0)], spacegroup=227,
275 ... cellpar=[a_si, a_si, a_si, 90., 90., 90.])
276 >>> si110 = cut(si, (0, 0, 2), (-1, 1, 0), nlayers=3)
277 >>>
278 >>> interface = stack(ag110, si110, maxstrain=1)
279 >>> ase.view(interface) # doctest: +SKIP
280 >>>
281 # Once more, this time adjusted such that the distance between
282 # the closest Ag and Si atoms will be 2.3 Angstrom (requires scipy).
283 >>> interface2 = stack(ag110, si110,
284 ... maxstrain=1, distance=2.3) # doctest:+ELLIPSIS
285 Optimization terminated successfully.
286 ...
287 >>> ase.view(interface2) # doctest: +SKIP
288 """
289 atoms1 = atoms1.copy()
290 atoms2 = atoms2.copy()
292 for atoms in [atoms1, atoms2]:
293 if not atoms.cell[axis].any():
294 atoms.center(vacuum=0.0, axis=axis)
296 if np.sign(np.linalg.det(atoms1.cell)) != np.sign(
297 np.linalg.det(atoms2.cell)
298 ):
299 raise IncompatibleCellError(
300 'Cells of *atoms1* and *atoms2* must have same handedness.'
301 )
303 c1 = np.linalg.norm(atoms1.cell[axis])
304 c2 = np.linalg.norm(atoms2.cell[axis])
305 if cell is None:
306 cell1 = atoms1.cell.copy()
307 cell2 = atoms2.cell.copy()
308 cell1[axis] /= c1
309 cell2[axis] /= c2
310 cell = cell1 + fix * (cell2 - cell1)
311 cell[axis] /= np.linalg.norm(cell[axis])
312 cell1 = cell.copy()
313 cell2 = cell.copy()
314 cell1[axis] *= c1
315 cell2[axis] *= c2
317 if maxstrain:
318 strain1 = np.sqrt(((cell1 - atoms1.cell).sum(axis=0) ** 2).sum())
319 strain2 = np.sqrt(((cell2 - atoms2.cell).sum(axis=0) ** 2).sum())
320 if strain1 > maxstrain or strain2 > maxstrain:
321 raise IncompatibleCellError(
322 '*maxstrain* exceeded. *atoms1* strained %f and '
323 '*atoms2* strained %f.' % (strain1, strain2)
324 )
326 atoms1.set_cell(cell1, scale_atoms=True)
327 atoms2.set_cell(cell2, scale_atoms=True)
328 if output_strained:
329 atoms1_strained = atoms1.copy()
330 atoms2_strained = atoms2.copy()
332 if distance is not None:
333 from scipy.optimize import fmin
335 def mindist(pos1, pos2):
336 n1 = len(pos1)
337 n2 = len(pos2)
338 idx1 = np.arange(n1).repeat(n2)
339 idx2 = np.tile(np.arange(n2), n1)
340 return np.sqrt(((pos1[idx1] - pos2[idx2]) ** 2).sum(axis=1).min())
342 def func(x):
343 t1, t2, h1, h2 = x[0:3], x[3:6], x[6], x[7]
344 pos1 = atoms1.positions + t1
345 pos2 = atoms2.positions + t2
346 d1 = mindist(pos1, pos2 + (h1 + 1.0) * atoms1.cell[axis])
347 d2 = mindist(pos2, pos1 + (h2 + 1.0) * atoms2.cell[axis])
348 return (d1 - distance) ** 2 + (d2 - distance) ** 2
350 atoms1.center()
351 atoms2.center()
352 x0 = np.zeros((8,))
353 x = fmin(func, x0)
354 t1, t2, h1, h2 = x[0:3], x[3:6], x[6], x[7]
355 atoms1.translate(t1)
356 atoms2.translate(t2)
357 atoms1.cell[axis] *= 1.0 + h1
358 atoms2.cell[axis] *= 1.0 + h2
360 atoms2.translate(atoms1.cell[axis])
361 atoms1.cell[axis] += atoms2.cell[axis]
362 atoms1.extend(atoms2)
364 if reorder:
365 atoms1 = sort(atoms1)
367 if output_strained:
368 return atoms1, atoms1_strained, atoms2_strained
369 else:
370 return atoms1
373def rotation_matrix(a1, a2, b1, b2):
374 """Returns a rotation matrix that rotates the vectors *a1* in the
375 direction of *a2* and *b1* in the direction of *b2*.
377 In the case that the angle between *a2* and *b2* is not the same
378 as between *a1* and *b1*, a proper rotation matrix will anyway be
379 constructed by first rotate *b2* in the *b1*, *b2* plane.
380 """
381 a1 = np.asarray(a1, dtype=float) / np.linalg.norm(a1)
382 b1 = np.asarray(b1, dtype=float) / np.linalg.norm(b1)
383 c1 = np.cross(a1, b1)
384 c1 /= np.linalg.norm(c1) # clean out rounding errors...
386 a2 = np.asarray(a2, dtype=float) / np.linalg.norm(a2)
387 b2 = np.asarray(b2, dtype=float) / np.linalg.norm(b2)
388 c2 = np.cross(a2, b2)
389 c2 /= np.linalg.norm(c2) # clean out rounding errors...
391 # Calculate rotated *b2*
392 theta = np.arccos(np.dot(a2, b2)) - np.arccos(np.dot(a1, b1))
393 b3 = np.sin(theta) * a2 + np.cos(theta) * b2
394 b3 /= np.linalg.norm(b3) # clean out rounding errors...
396 A1 = np.array([a1, b1, c1])
397 A2 = np.array([a2, b3, c2])
398 R = np.linalg.solve(A1, A2).T
399 return R
402def rotate(atoms, a1, a2, b1, b2, rotate_cell=True, center=(0, 0, 0)):
403 """Rotate *atoms*, such that *a1* will be rotated in the direction
404 of *a2* and *b1* in the direction of *b2*. The point at *center*
405 is fixed. Use *center='COM'* to fix the center of mass. If
406 *rotate_cell* is true, the cell will be rotated together with the
407 atoms.
409 Note that the 000-corner of the cell is by definition fixed at
410 origo. Hence, setting *center* to something other than (0, 0, 0)
411 will rotate the atoms out of the cell, even if *rotate_cell* is
412 True.
413 """
414 if isinstance(center, str) and center.lower() == 'com':
415 center = atoms.get_center_of_mass()
417 R = rotation_matrix(a1, a2, b1, b2)
418 atoms.positions[:] = np.dot(atoms.positions - center, R.T) + center
420 if rotate_cell:
421 atoms.cell[:] = np.dot(atoms.cell, R.T)
424def minimize_tilt_ij(atoms, modified=1, fixed=0, fold_atoms=True):
425 """Minimize the tilt angle for two given axes.
427 The problem is underdetermined. Therefore one can choose one axis
428 that is kept fixed.
429 """
431 orgcell_cc = atoms.get_cell()
432 pbc_c = atoms.get_pbc()
433 i = fixed
434 j = modified
435 if not (pbc_c[i] and pbc_c[j]):
436 raise RuntimeError('Axes have to be periodic')
438 prod_cc = np.dot(orgcell_cc, orgcell_cc.T)
439 cell_cc = 1.0 * orgcell_cc
440 nji = np.floor(-prod_cc[i, j] / prod_cc[i, i] + 0.5)
441 cell_cc[j] = orgcell_cc[j] + nji * cell_cc[i]
443 # sanity check
444 def volume(cell):
445 return np.abs(np.dot(cell[2], np.cross(cell[0], cell[1])))
447 V = volume(cell_cc)
448 assert abs(volume(orgcell_cc) - V) / V < 1.0e-10
450 atoms.set_cell(cell_cc)
452 if fold_atoms:
453 atoms.wrap()
456def minimize_tilt(atoms, order=range(3), fold_atoms=True):
457 """Minimize the tilt angles of the unit cell."""
458 pbc_c = atoms.get_pbc()
460 for i1, c1 in enumerate(order):
461 for c2 in order[i1 + 1 :]:
462 if pbc_c[c1] and pbc_c[c2]:
463 minimize_tilt_ij(atoms, c1, c2, fold_atoms)
466def update_cell_and_positions(atoms, new_cell, op):
467 """Helper method for transforming cell and positions of atoms object."""
468 scpos = np.linalg.solve(op, atoms.get_scaled_positions().T).T
470 # We do this twice because -1e-20 % 1 == 1:
471 scpos[:, atoms.pbc] %= 1.0
472 scpos[:, atoms.pbc] %= 1.0
474 atoms.set_cell(new_cell)
475 atoms.set_scaled_positions(scpos)
478def niggli_reduce(atoms):
479 """Convert the supplied atoms object's unit cell into its
480 maximally-reduced Niggli unit cell. Even if the unit cell is already
481 maximally reduced, it will be converted into its unique Niggli unit cell.
482 This will also wrap all atoms into the new unit cell.
484 References
485 ----------
487 Niggli, P. "Krystallographische und strukturtheoretische Grundbegriffe.
488 Handbuch der Experimentalphysik", 1928, Vol. 7, Part 1, 108-176.
490 Krivy, I. and Gruber, B., "A Unified Algorithm for Determining the
491 Reduced (Niggli) Cell", Acta Cryst. 1976, A32, 297-298.
493 Grosse-Kunstleve, R.W.; Sauter, N. K.; and Adams, P. D. "Numerically
494 stable algorithms for the computation of reduced unit cells", Acta Cryst.
495 2004, A60, 1-6.
496 """
497 from ase.geometry.geometry import permute_axes
499 # Make sure non-periodic cell vectors are orthogonal
500 non_periodic_cv = atoms.cell[~atoms.pbc]
501 periodic_cv = atoms.cell[atoms.pbc]
502 if not np.isclose(np.dot(non_periodic_cv, periodic_cv.T), 0).all():
503 raise ValueError('Non-orthogonal cell along non-periodic dimensions')
505 input_atoms = atoms
507 # Permute axes, such that the non-periodic are along the last dimensions,
508 # since niggli_reduce_cell will change the order of axes.
509 permutation = np.argsort(~atoms.pbc)
510 ipermutation = np.empty_like(permutation)
511 ipermutation[permutation] = np.arange(len(permutation))
512 atoms = permute_axes(atoms, permutation)
514 # Perform the Niggli reduction on the cell
515 nonpbc = ~atoms.pbc
516 uncompleted_cell = atoms.cell.uncomplete(atoms.pbc)
517 new_cell, op = niggli_reduce_cell(uncompleted_cell)
518 new_cell[nonpbc] = atoms.cell[nonpbc]
519 update_cell_and_positions(atoms, new_cell, op)
521 # Undo the prior permutation.
522 atoms = permute_axes(atoms, ipermutation)
523 input_atoms.cell[:] = atoms.cell
524 input_atoms.positions[:] = atoms.positions
527def reduce_lattice(atoms, eps=2e-4):
528 """Reduce atoms object to canonical lattice.
530 This changes the cell and positions such that the atoms object has
531 the canonical form used for defining band paths but is otherwise
532 physically equivalent. The eps parameter is used as a tolerance
533 for determining the cell's Bravais lattice."""
534 from ase.lattice import identify_lattice
536 niggli_reduce(atoms)
537 lat, op = identify_lattice(atoms.cell, eps=eps)
538 update_cell_and_positions(atoms, lat.tocell(), np.linalg.inv(op))
541def sort(atoms, tags=None):
542 """Return a new Atoms object with sorted atomic order. The default
543 is to order according to chemical symbols, but if *tags* is not
544 None, it will be used instead. A stable sorting algorithm is used.
546 Example:
548 >>> from ase.build import bulk
549 >>> from ase.build.tools import sort
550 >>> # Two unit cells of NaCl:
551 >>> a = 5.64
552 >>> nacl = bulk('NaCl', 'rocksalt', a=a) * (2, 1, 1)
553 >>> list(nacl.symbols)
554 ['Na', 'Cl', 'Na', 'Cl']
555 >>> nacl_sorted = sort(nacl)
556 >>> list(nacl_sorted.symbols)
557 ['Cl', 'Cl', 'Na', 'Na']
558 >>> np.all(nacl_sorted.cell == nacl.cell)
559 np.True_
560 """
561 if tags is None:
562 tags = atoms.get_chemical_symbols()
563 else:
564 tags = list(tags)
565 deco = sorted([(tag, i) for i, tag in enumerate(tags)])
566 indices = [i for tag, i in deco]
567 return atoms[indices]