Coverage for ase/geometry/geometry.py: 97.93%
193 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# Copyright (C) 2010, Jesper Friis
2# (see accompanying license files for details).
4"""Utility tools for atoms/geometry manipulations.
5 - convenient creation of slabs and interfaces of
6different orientations.
7 - detection of duplicate atoms / atoms within cutoff radius
8"""
10import itertools
12import numpy as np
14from ase.cell import Cell
15from ase.geometry import complete_cell
16from ase.geometry.minkowski_reduction import minkowski_reduce
17from ase.utils import pbc2pbc
20def translate_pretty(fractional, pbc):
21 """Translates atoms such that fractional positions are minimized."""
23 for i in range(3):
24 if not pbc[i]:
25 continue
27 indices = np.argsort(fractional[:, i])
28 sp = fractional[indices, i]
30 widths = (np.roll(sp, 1) - sp) % 1.0
31 fractional[:, i] -= sp[np.argmin(widths)]
32 fractional[:, i] %= 1.0
33 return fractional
36def wrap_positions(
37 positions,
38 cell,
39 pbc=True,
40 center=(0.5, 0.5, 0.5),
41 pretty_translation=False,
42 eps=1e-7,
43):
44 """Wrap positions to unit cell.
46 Returns positions changed by a multiple of the unit cell vectors to
47 fit inside the space spanned by these vectors. See also the
48 :meth:`ase.Atoms.wrap` method.
50 Parameters
51 ----------
53 positions: float ndarray of shape (n, 3)
54 Positions of the atoms
55 cell: float ndarray of shape (3, 3)
56 Unit cell vectors.
57 pbc: one or 3 bool
58 For each axis in the unit cell decides whether the positions
59 will be moved along this axis.
60 center: three float
61 The positons in fractional coordinates that the new positions
62 will be nearest possible to.
63 pretty_translation: bool
64 Translates atoms such that fractional coordinates are minimized.
65 eps: float
66 Small number to prevent slightly negative coordinates from being
67 wrapped.
69 Examples
70 --------
71 >>> from ase.geometry import wrap_positions
72 >>> wrap_positions([[-0.1, 1.01, -0.5]],
73 ... [[1, 0, 0], [0, 1, 0], [0, 0, 4]],
74 ... pbc=[1, 1, 0])
75 array([[ 0.9 , 0.01, -0.5 ]])
76 """
78 if not hasattr(center, '__len__'):
79 center = (center,) * 3
81 pbc = pbc2pbc(pbc)
82 shift = np.asarray(center) - 0.5 - eps
84 # Don't change coordinates when pbc is False
85 shift[np.logical_not(pbc)] = 0.0
87 assert np.asarray(cell)[np.asarray(pbc)].any(axis=1).all(), (cell, pbc)
89 cell = complete_cell(cell)
90 fractional = np.linalg.solve(cell.T, np.asarray(positions).T).T - shift
92 if pretty_translation:
93 fractional = translate_pretty(fractional, pbc)
94 shift = np.asarray(center) - 0.5
95 shift[np.logical_not(pbc)] = 0.0
96 fractional += shift
97 else:
98 for i, periodic in enumerate(pbc):
99 if periodic:
100 fractional[:, i] %= 1.0
101 fractional[:, i] += shift[i]
103 return np.dot(fractional, cell)
106def get_layers(atoms, miller, tolerance=0.001):
107 """Returns two arrays describing which layer each atom belongs
108 to and the distance between the layers and origo.
110 Parameters
111 ----------
113 miller: 3 integers
114 The Miller indices of the planes. Actually, any direction
115 in reciprocal space works, so if a and b are two float
116 vectors spanning an atomic plane, you can get all layers
117 parallel to this with miller=np.cross(a,b).
118 tolerance: float
119 The maximum distance in Angstrom along the plane normal for
120 counting two atoms as belonging to the same plane.
122 Returns
123 -------
125 tags: array of integres
126 Array of layer indices for each atom.
127 levels: array of floats
128 Array of distances in Angstrom from each layer to origo.
130 Example:
132 >>> import numpy as np
134 >>> from ase.spacegroup import crystal
135 >>> from ase.geometry.geometry import get_layers
137 >>> atoms = crystal('Al', [(0,0,0)], spacegroup=225, cellpar=4.05)
138 >>> np.round(atoms.positions, decimals=5) # doctest: +NORMALIZE_WHITESPACE
139 array([[0. , 0. , 0. ],
140 [0. , 2.025, 2.025],
141 [2.025, 0. , 2.025],
142 [2.025, 2.025, 0. ]])
143 >>> get_layers(atoms, (0, 0, 1)) # doctest: +ELLIPSIS
144 (array([0, 1, 1, 0]), array([0. , 2.025]))
145 """
146 miller = np.asarray(miller)
148 metric = np.dot(atoms.cell, atoms.cell.T)
149 c = np.linalg.solve(metric.T, miller.T).T
150 miller_norm = np.sqrt(np.dot(c, miller))
151 d = np.dot(atoms.get_scaled_positions(), miller) / miller_norm
153 keys = np.argsort(d)
154 ikeys = np.argsort(keys)
155 mask = np.concatenate(([True], np.diff(d[keys]) > tolerance))
156 tags = np.cumsum(mask)[ikeys]
157 if tags.min() == 1:
158 tags -= 1
160 levels = d[keys][mask]
161 return tags, levels
164def naive_find_mic(v, cell):
165 """Finds the minimum-image representation of vector(s) v.
166 Safe to use for (pbc.all() and (norm(v_mic) < 0.5 * min(cell.lengths()))).
167 Can otherwise fail for non-orthorhombic cells.
168 Described in:
169 W. Smith, "The Minimum Image Convention in Non-Cubic MD Cells", 1989,
170 http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.57.1696."""
171 f = Cell(cell).scaled_positions(v)
172 f -= np.floor(f + 0.5)
173 vmin = f @ cell
174 vlen = np.linalg.norm(vmin, axis=1)
175 return vmin, vlen
178def general_find_mic(v, cell, pbc=True):
179 """Finds the minimum-image representation of vector(s) v. Using the
180 Minkowski reduction the algorithm is relatively slow but safe for any cell.
181 """
183 cell = complete_cell(cell)
184 rcell, _ = minkowski_reduce(cell, pbc=pbc)
185 positions = wrap_positions(v, rcell, pbc=pbc, eps=0)
187 # In a Minkowski-reduced cell we only need to test nearest neighbors,
188 # or "Voronoi-relevant" vectors. These are a subset of combinations of
189 # [-1, 0, 1] of the reduced cell vectors.
191 # Define ranges [-1, 0, 1] for periodic directions and [0] for aperiodic
192 # directions.
193 ranges = [np.arange(-1 * p, p + 1) for p in pbc]
195 # Get Voronoi-relevant vectors.
196 # Pre-pend (0, 0, 0) to resolve issue #772
197 hkls = np.array([(0, 0, 0)] + list(itertools.product(*ranges)))
198 vrvecs = hkls @ rcell
200 # Map positions into neighbouring cells.
201 x = positions + vrvecs[:, None]
203 # Find minimum images
204 lengths = np.linalg.norm(x, axis=2)
205 indices = np.argmin(lengths, axis=0)
206 vmin = x[indices, np.arange(len(positions)), :]
207 vlen = lengths[indices, np.arange(len(positions))]
208 return vmin, vlen
211def find_mic(v, cell, pbc=True):
212 """Finds the minimum-image representation of vector(s) v using either one
213 of two find mic algorithms depending on the given cell, v and pbc."""
215 cell = Cell(cell)
216 pbc = cell.any(1) & pbc2pbc(pbc)
217 dim = np.sum(pbc)
218 v = np.asarray(v)
219 single = v.ndim == 1
220 v = np.atleast_2d(v)
222 if dim > 0:
223 naive_find_mic_is_safe = False
224 if dim == 3:
225 vmin, vlen = naive_find_mic(v, cell)
226 # naive find mic is safe only for the following condition
227 if (vlen < 0.5 * min(cell.lengths())).all():
228 naive_find_mic_is_safe = True # hence skip Minkowski reduction
230 if not naive_find_mic_is_safe:
231 vmin, vlen = general_find_mic(v, cell, pbc=pbc)
232 else:
233 vmin = v.copy()
234 vlen = np.linalg.norm(vmin, axis=1)
236 if single:
237 return vmin[0], vlen[0]
238 else:
239 return vmin, vlen
242def conditional_find_mic(vectors, cell, pbc):
243 """Return vectors and their lengths considering cell and pbc.
245 The minimum image convention is applied if cell and pbc are set.
246 This can be used like a simple version of get_distances.
247 """
248 vectors = np.array(vectors)
249 if (cell is None) != (pbc is None):
250 raise ValueError('cell or pbc must be both set or both be None')
251 if cell is not None:
252 mics = [find_mic(v, cell, pbc) for v in vectors]
253 vectors, vector_lengths = zip(*mics)
254 else:
255 vector_lengths = np.sqrt(np.add.reduce(vectors**2, axis=-1))
256 return vectors, vector_lengths
259def get_angles(v0, v1, cell=None, pbc=None):
260 """Get angles formed by two lists of vectors.
262 Calculate angle in degrees between vectors v0 and v1
264 Set a cell and pbc to enable minimum image
265 convention, otherwise angles are taken as-is.
266 """
267 (v0, v1), (nv0, nv1) = conditional_find_mic([v0, v1], cell, pbc)
269 if (nv0 <= 0).any() or (nv1 <= 0).any():
270 raise ZeroDivisionError('Undefined angle')
271 v0n = v0 / nv0[:, np.newaxis]
272 v1n = v1 / nv1[:, np.newaxis]
273 # We just normalized the vectors, but in some cases we can get
274 # bad things like 1+2e-16. These we clip away:
275 angles = np.arccos(np.einsum('ij,ij->i', v0n, v1n).clip(-1.0, 1.0))
276 return np.degrees(angles)
279def get_angles_derivatives(v0, v1, cell=None, pbc=None):
280 """Get derivatives of angles formed by two lists of vectors (v0, v1) w.r.t.
281 Cartesian coordinates in degrees.
283 Set a cell and pbc to enable minimum image
284 convention, otherwise derivatives of angles are taken as-is.
286 There is a singularity in the derivatives for sin(angle) -> 0 for which
287 a ZeroDivisionError is raised.
289 Derivative output format: [[dx_a0, dy_a0, dz_a0], [...], [..., dz_a2].
290 """
291 (v0, v1), (nv0, nv1) = conditional_find_mic([v0, v1], cell, pbc)
293 angles = np.radians(get_angles(v0, v1, cell=cell, pbc=pbc))
294 sin_angles = np.sin(angles)
295 cos_angles = np.cos(angles)
296 if (sin_angles == 0.0).any(): # identify singularities
297 raise ZeroDivisionError('Singularity for derivative of a planar angle')
299 product = nv0 * nv1
300 deriv_d0 = (
301 -(
302 v1 / product[:, np.newaxis] # derivatives by atom 0
303 - np.einsum('ij,i->ij', v0, cos_angles / nv0**2)
304 )
305 / sin_angles[:, np.newaxis]
306 )
307 deriv_d2 = (
308 -(
309 v0 / product[:, np.newaxis] # derivatives by atom 2
310 - np.einsum('ij,i->ij', v1, cos_angles / nv1**2)
311 )
312 / sin_angles[:, np.newaxis]
313 )
314 deriv_d1 = -(deriv_d0 + deriv_d2) # derivatives by atom 1
315 derivs = np.stack((deriv_d0, deriv_d1, deriv_d2), axis=1)
316 return np.degrees(derivs)
319def get_dihedrals(v0, v1, v2, cell=None, pbc=None):
320 """Get dihedral angles formed by three lists of vectors.
322 Calculate dihedral angle (in degrees) between the vectors a0->a1,
323 a1->a2 and a2->a3, written as v0, v1 and v2.
325 Set a cell and pbc to enable minimum image
326 convention, otherwise angles are taken as-is.
327 """
328 (v0, v1, v2), (_, nv1, _) = conditional_find_mic([v0, v1, v2], cell, pbc)
330 v1n = v1 / nv1[:, np.newaxis]
331 # v, w: projection of v0, v2 onto plane perpendicular to v1
332 v = -v0 - np.einsum('ij,ij,ik->ik', -v0, v1n, v1n)
333 w = v2 - np.einsum('ij,ij,ik->ik', v2, v1n, v1n)
335 # formula returns 0 for undefined dihedrals; prefer ZeroDivisionError
336 undefined_v = np.all(v == 0.0, axis=1)
337 undefined_w = np.all(w == 0.0, axis=1)
338 if np.any([undefined_v, undefined_w]):
339 raise ZeroDivisionError('Undefined dihedral for planar inner angle')
341 x = np.einsum('ij,ij->i', v, w)
342 y = np.einsum('ij,ij->i', np.cross(v1n, v, axis=1), w)
343 dihedrals = np.arctan2(y, x) # dihedral angle in [-pi, pi]
344 dihedrals[dihedrals < 0.0] += 2 * np.pi # dihedral angle in [0, 2*pi]
345 return np.degrees(dihedrals)
348def get_dihedrals_derivatives(v0, v1, v2, cell=None, pbc=None):
349 """Get derivatives of dihedrals formed by three lists of vectors
350 (v0, v1, v2) w.r.t Cartesian coordinates in degrees.
352 Set a cell and pbc to enable minimum image
353 convention, otherwise dihedrals are taken as-is.
355 Derivative output format: [[dx_a0, dy_a0, dz_a0], ..., [..., dz_a3]].
356 """
357 (v0, v1, v2), (nv0, nv1, nv2) = conditional_find_mic(
358 [v0, v1, v2], cell, pbc
359 )
361 v0n = v0 / nv0[:, np.newaxis]
362 v1n = v1 / nv1[:, np.newaxis]
363 v2n = v2 / nv2[:, np.newaxis]
364 normal_v01 = np.cross(v0n, v1n, axis=1)
365 normal_v12 = np.cross(v1n, v2n, axis=1)
366 cos_psi01 = np.einsum('ij,ij->i', v0n, v1n) # == np.sum(v0 * v1, axis=1)
367 sin_psi01 = np.sin(np.arccos(cos_psi01))
368 cos_psi12 = np.einsum('ij,ij->i', v1n, v2n)
369 sin_psi12 = np.sin(np.arccos(cos_psi12))
370 if (sin_psi01 == 0.0).any() or (sin_psi12 == 0.0).any():
371 msg = (
372 'Undefined derivative for undefined dihedral with planar inner '
373 'angle'
374 )
375 raise ZeroDivisionError(msg)
377 deriv_d0 = -normal_v01 / (nv0 * sin_psi01**2)[:, np.newaxis] # by atom 0
378 deriv_d3 = normal_v12 / (nv2 * sin_psi12**2)[:, np.newaxis] # by atom 3
379 deriv_d1 = ((nv1 + nv0 * cos_psi01) / nv1)[:, np.newaxis] * -deriv_d0 + (
380 cos_psi12 * nv2 / nv1
381 )[:, np.newaxis] * deriv_d3 # by a1
382 deriv_d2 = (
383 -((nv1 + nv2 * cos_psi12) / nv1)[:, np.newaxis] * deriv_d3
384 - (cos_psi01 * nv0 / nv1)[:, np.newaxis] * -deriv_d0
385 ) # by a2
386 derivs = np.stack((deriv_d0, deriv_d1, deriv_d2, deriv_d3), axis=1)
387 return np.degrees(derivs)
390def get_distances(p1, p2=None, cell=None, pbc=None):
391 """Return distance matrix of every position in p1 with every position in p2
393 If p2 is not set, it is assumed that distances between all positions in p1
394 are desired. p2 will be set to p1 in this case.
396 Use set cell and pbc to use the minimum image convention.
397 """
398 p1 = np.atleast_2d(p1)
399 if p2 is None:
400 np1 = len(p1)
401 ind1, ind2 = np.triu_indices(np1, k=1)
402 D = p1[ind2] - p1[ind1]
403 else:
404 p2 = np.atleast_2d(p2)
405 D = (p2[np.newaxis, :, :] - p1[:, np.newaxis, :]).reshape((-1, 3))
407 (D,), (D_len,) = conditional_find_mic([D], cell=cell, pbc=pbc)
409 if p2 is None:
410 Dout = np.zeros((np1, np1, 3))
411 Dout[(ind1, ind2)] = D
412 Dout -= np.transpose(Dout, axes=(1, 0, 2))
414 Dout_len = np.zeros((np1, np1))
415 Dout_len[(ind1, ind2)] = D_len
416 Dout_len += Dout_len.T
417 return Dout, Dout_len
419 # Expand back to matrix indexing
420 return D.reshape((-1, len(p2), 3)), D_len.reshape((-1, len(p2)))
423def get_distances_derivatives(v0, cell=None, pbc=None):
424 """Get derivatives of distances for all vectors in v0 w.r.t. Cartesian
425 coordinates in Angstrom.
427 Set cell and pbc to use the minimum image convention.
429 There is a singularity for distances -> 0 for which a ZeroDivisionError is
430 raised.
431 Derivative output format: [[dx_a0, dy_a0, dz_a0], [dx_a1, dy_a1, dz_a1]].
432 """
433 (v0,), (dists,) = conditional_find_mic([v0], cell, pbc)
435 if (dists <= 0.0).any(): # identify singularities
436 raise ZeroDivisionError('Singularity for derivative of a zero distance')
438 derivs_d0 = np.einsum('i,ij->ij', -1.0 / dists, v0) # derivatives by atom 0
439 derivs_d1 = -derivs_d0 # derivatives by atom 1
440 derivs = np.stack((derivs_d0, derivs_d1), axis=1)
441 return derivs
444def get_duplicate_atoms(atoms, cutoff=0.1, delete=False):
445 """Get list of duplicate atoms and delete them if requested.
447 Identify all atoms which lie within the cutoff radius of each other.
448 Delete one set of them if delete == True.
449 """
450 dists = get_distances(atoms.positions, cell=atoms.cell, pbc=atoms.pbc)[1]
451 dup = np.argwhere(dists < cutoff)
452 dup = dup[dup[:, 0] < dup[:, 1]] # indices at upper triangle
453 if delete and dup.size != 0:
454 del atoms[dup[:, 0]]
455 return dup
458def permute_axes(atoms, permutation):
459 """Permute axes of unit cell and atom positions. Considers only cell and
460 atomic positions. Other vector quantities such as momenta are not
461 modified."""
462 assert (np.sort(permutation) == np.arange(3)).all()
464 permuted = atoms.copy()
465 scaled = permuted.get_scaled_positions()
466 permuted.set_cell(
467 permuted.cell.permute_axes(permutation), scale_atoms=False
468 )
469 permuted.set_scaled_positions(scaled[:, permutation])
470 permuted.set_pbc(permuted.pbc[permutation])
471 return permuted