Coverage for ase/neighborlist.py: 95.30%
383 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 itertools
3import numpy as np
4import scipy.sparse.csgraph as csgraph
5from scipy import sparse as sp
6from scipy.spatial import cKDTree
8from ase.cell import Cell
9from ase.data import atomic_numbers, covalent_radii
10from ase.geometry import (
11 complete_cell,
12 find_mic,
13 minkowski_reduce,
14 wrap_positions,
15)
16from ase.utils import deprecated
19def natural_cutoffs(atoms, mult=1, **kwargs):
20 """Generate a radial cutoff for every atom based on covalent radii.
22 The covalent radii are a reasonable cutoff estimation for bonds in
23 many applications such as neighborlists, so function generates an
24 atoms length list of radii based on this idea.
26 * atoms: An atoms object
27 * mult: A multiplier for all cutoffs, useful for coarse grained adjustment
28 * kwargs: Symbol of the atom and its corresponding cutoff,
29 used to override the covalent radii
30 """
31 return [
32 kwargs.get(atom.symbol, covalent_radii[atom.number] * mult)
33 for atom in atoms
34 ]
37def build_neighbor_list(atoms, cutoffs=None, **kwargs):
38 """Automatically build and update a NeighborList.
40 Parameters
41 ----------
43 atoms : :class:`~ase.Atoms` object
44 Atoms to build Neighborlist for.
45 cutoffs: list of floats
46 Radii for each atom. If not given it will be produced by calling
47 :func:`ase.neighborlist.natural_cutoffs`
48 kwargs: arbitrary number of options
49 Will be passed to the constructor of
50 :class:`~ase.neighborlist.NeighborList`
52 Returns
53 -------
55 return: :class:`~ase.neighborlist.NeighborList`
56 A :class:`~ase.neighborlist.NeighborList` instance (updated).
57 """
58 if cutoffs is None:
59 cutoffs = natural_cutoffs(atoms)
61 nl = NeighborList(cutoffs, **kwargs)
62 nl.update(atoms)
64 return nl
67def get_distance_matrix(graph, limit=3):
68 """Get Distance Matrix from a Graph.
70 Parameters
71 ----------
73 graph: array, matrix or sparse matrix, 2 dimensions (N, N)
74 Graph representation of the connectivity.
75 See `scipy doc <https://docs.scipy.org/doc/scipy/reference/generated\
76/scipy.sparse.csgraph.dijkstra.html#scipy.sparse.csgraph.dijkstra>`_
77 for reference.
78 limit: integer
79 Maximum number of steps to analyze. For most molecular information,
80 three should be enough.
82 Returns
83 -------
85 return: scipy.sparse.csr_matrix, shape (N, N)
86 A scipy.sparse.csr_matrix. All elements that are not connected within
87 *limit* steps are set to zero.
89 This is a potential memory bottleneck, as csgraph.dijkstra produces a
90 dense output matrix. Here we replace all np.inf values with 0 and
91 transform back to csr_matrix.
92 Why not dok_matrix like the connectivity-matrix? Because row-picking
93 is most likely and this is super fast with csr.
94 """
95 mat = csgraph.dijkstra(graph, directed=False, limit=limit)
96 mat[mat == np.inf] = 0
97 return sp.csr_matrix(mat, dtype=np.int8)
100def get_distance_indices(distanceMatrix, distance):
101 """Get indices for each node that are distance or less away.
103 Parameters
104 ----------
106 distanceMatrix: any one of scipy.sparse matrices (NxN)
107 Matrix containing distance information of atoms. Get it e.g. with
108 :func:`~ase.neighborlist.get_distance_matrix`
109 distance: integer
110 Number of steps to allow.
112 Returns
113 -------
115 return: list of length N
116 List of length N. return[i] has all indices connected to item i.
118 The distance matrix only contains shortest paths, so when looking for
119 distances longer than one, we need to add the lower values for cases
120 where atoms are connected via a shorter path too.
121 """
122 shape = distanceMatrix.get_shape()
123 indices = []
124 # iterate over rows
125 for i in range(shape[0]):
126 row = distanceMatrix.getrow(i)[0]
127 # find all non-zero
128 found = sp.find(row)
129 # screen for smaller or equal distance
130 equal = np.where(found[-1] <= distance)[0]
131 # found[1] contains the indexes
132 indices.append([found[1][x] for x in equal])
133 return indices
136def mic(dr, cell, pbc=True):
137 """
138 Apply minimum image convention to an array of distance vectors.
140 Parameters
141 ----------
143 dr : array_like
144 Array of distance vectors.
145 cell : array_like
146 Simulation cell.
147 pbc : array_like, optional
148 Periodic boundary conditions in x-, y- and z-direction. Default is to
149 assume periodic boundaries in all directions.
151 Returns
152 -------
154 dr : array
155 Array of distance vectors, wrapped according to the minimum image
156 convention.
157 """
158 dr, _ = find_mic(dr, cell, pbc)
159 return dr
162def primitive_neighbor_list(
163 quantities,
164 pbc,
165 cell,
166 positions,
167 cutoff,
168 numbers=None,
169 self_interaction=False,
170 use_scaled_positions=False,
171 max_nbins=1e6,
172):
173 """Compute a neighbor list for an atomic configuration.
175 Atoms outside periodic boundaries are mapped into the box. Atoms
176 outside nonperiodic boundaries are included in the neighbor list
177 but complexity of neighbor list search for those can become n^2.
179 The neighbor list is sorted by first atom index 'i', but not by second
180 atom index 'j'.
182 Parameters
183 ----------
185 quantities: str
186 Quantities to compute by the neighbor list algorithm. Each character
187 in this string defines a quantity. They are returned in a tuple of
188 the same order. Possible quantities are
190 * 'i' : first atom index
191 * 'j' : second atom index
192 * 'd' : absolute distance
193 * 'D' : distance vector
194 * 'S' : shift vector (number of cell boundaries crossed by the bond
195 between atom i and j). With the shift vector S, the
196 distances D between atoms can be computed from:
197 D = positions[j]-positions[i]+S.dot(cell)
198 pbc: array_like
199 3-tuple indicating giving periodic boundaries in the three Cartesian
200 directions.
201 cell: 3x3 matrix
202 Unit cell vectors.
203 positions: list of xyz-positions
204 Atomic positions. Anything that can be converted to an ndarray of
205 shape (n, 3) will do: [(x1,y1,z1), (x2,y2,z2), ...]. If
206 use_scaled_positions is set to true, this must be scaled positions.
207 cutoff: float or dict
208 Cutoff for neighbor search. It can be:
210 * A single float: This is a global cutoff for all elements.
211 * A dictionary: This specifies cutoff values for element
212 pairs. Specification accepts element numbers of symbols.
213 Example: {(1, 6): 1.1, (1, 1): 1.0, ('C', 'C'): 1.85}
214 * A list/array with a per atom value: This specifies the radius of
215 an atomic sphere for each atoms. If spheres overlap, atoms are
216 within each others neighborhood. See
217 :func:`~ase.neighborlist.natural_cutoffs`
218 for an example on how to get such a list.
219 self_interaction: bool
220 Return the atom itself as its own neighbor if set to true.
221 Default: False
222 use_scaled_positions: bool
223 If set to true, positions are expected to be scaled positions.
224 max_nbins: int
225 Maximum number of bins used in neighbor search. This is used to limit
226 the maximum amount of memory required by the neighbor list.
228 Returns
229 -------
231 i, j, ... : array
232 Tuple with arrays for each quantity specified above. Indices in `i`
233 are returned in ascending order 0..len(a)-1, but the order of (i,j)
234 pairs is not guaranteed.
236 """
238 # Naming conventions: Suffixes indicate the dimension of an array. The
239 # following convention is used here:
240 # c: Cartesian index, can have values 0, 1, 2
241 # i: Global atom index, can have values 0..len(a)-1
242 # xyz: Bin index, three values identifying x-, y- and z-component of a
243 # spatial bin that is used to make neighbor search O(n)
244 # b: Linearized version of the 'xyz' bin index
245 # a: Bin-local atom index, i.e. index identifying an atom *within* a
246 # bin
247 # p: Pair index, can have value 0 or 1
248 # n: (Linear) neighbor index
250 # Return empty neighbor list if no atoms are passed here
251 if len(positions) == 0:
252 empty_types = dict(
253 i=(int, (0,)),
254 j=(int, (0,)),
255 D=(float, (0, 3)),
256 d=(float, (0,)),
257 S=(int, (0, 3)),
258 )
259 retvals = []
260 for i in quantities:
261 dtype, shape = empty_types[i]
262 retvals += [np.array([], dtype=dtype).reshape(shape)]
263 if len(retvals) == 1:
264 return retvals[0]
265 else:
266 return tuple(retvals)
268 # Compute reciprocal lattice vectors.
269 b1_c, b2_c, b3_c = np.linalg.pinv(cell).T
271 # Compute distances of cell faces.
272 l1 = np.linalg.norm(b1_c)
273 l2 = np.linalg.norm(b2_c)
274 l3 = np.linalg.norm(b3_c)
275 face_dist_c = np.array(
276 [
277 1 / l1 if l1 > 0 else 1,
278 1 / l2 if l2 > 0 else 1,
279 1 / l3 if l3 > 0 else 1,
280 ]
281 )
283 if isinstance(cutoff, dict):
284 max_cutoff = max(cutoff.values())
285 else:
286 if np.isscalar(cutoff):
287 max_cutoff = cutoff
288 else:
289 cutoff = np.asarray(cutoff)
290 max_cutoff = 2 * np.max(cutoff)
292 # We use a minimum bin size of 3 A
293 bin_size = max(max_cutoff, 3)
294 # Compute number of bins such that a sphere of radius cutoff fits into
295 # eight neighboring bins.
296 nbins_c = np.maximum((face_dist_c / bin_size).astype(int), [1, 1, 1])
297 nbins = np.prod(nbins_c)
298 # Make sure we limit the amount of memory used by the explicit bins.
299 while nbins > max_nbins:
300 nbins_c = np.maximum(nbins_c // 2, [1, 1, 1])
301 nbins = np.prod(nbins_c)
303 # Compute over how many bins we need to loop in the neighbor list search.
304 neigh_search_x, neigh_search_y, neigh_search_z = np.ceil(
305 bin_size * nbins_c / face_dist_c
306 ).astype(int)
308 # If we only have a single bin and the system is not periodic, then we
309 # do not need to search neighboring bins
310 neigh_search_x = 0 if nbins_c[0] == 1 and not pbc[0] else neigh_search_x
311 neigh_search_y = 0 if nbins_c[1] == 1 and not pbc[1] else neigh_search_y
312 neigh_search_z = 0 if nbins_c[2] == 1 and not pbc[2] else neigh_search_z
314 # Sort atoms into bins.
315 if use_scaled_positions:
316 scaled_positions_ic = positions
317 positions = np.dot(scaled_positions_ic, cell)
318 else:
319 scaled_positions_ic = np.linalg.solve(
320 complete_cell(cell).T, positions.T
321 ).T
322 bin_index_ic = np.floor(scaled_positions_ic * nbins_c).astype(int)
323 cell_shift_ic = np.zeros_like(bin_index_ic)
325 for c in range(3):
326 if pbc[c]:
327 # (Note: np.divmod does not exist in older numpies)
328 cell_shift_ic[:, c], bin_index_ic[:, c] = divmod(
329 bin_index_ic[:, c], nbins_c[c]
330 )
331 else:
332 bin_index_ic[:, c] = np.clip(bin_index_ic[:, c], 0, nbins_c[c] - 1)
334 # Convert Cartesian bin index to unique scalar bin index.
335 bin_index_i = bin_index_ic[:, 0] + nbins_c[0] * (
336 bin_index_ic[:, 1] + nbins_c[1] * bin_index_ic[:, 2]
337 )
339 # atom_i contains atom index in new sort order.
340 atom_i = np.argsort(bin_index_i)
341 bin_index_i = bin_index_i[atom_i]
343 # Find max number of atoms per bin
344 max_natoms_per_bin = np.bincount(bin_index_i).max()
346 # Sort atoms into bins: atoms_in_bin_ba contains for each bin (identified
347 # by its scalar bin index) a list of atoms inside that bin. This list is
348 # homogeneous, i.e. has the same size *max_natoms_per_bin* for all bins.
349 # The list is padded with -1 values.
350 atoms_in_bin_ba = -np.ones([nbins, max_natoms_per_bin], dtype=int)
351 for i in range(max_natoms_per_bin):
352 # Create a mask array that identifies the first atom of each bin.
353 mask = np.append([True], bin_index_i[:-1] != bin_index_i[1:])
354 # Assign all first atoms.
355 atoms_in_bin_ba[bin_index_i[mask], i] = atom_i[mask]
357 # Remove atoms that we just sorted into atoms_in_bin_ba. The next
358 # "first" atom will be the second and so on.
359 mask = np.logical_not(mask)
360 atom_i = atom_i[mask]
361 bin_index_i = bin_index_i[mask]
363 # Make sure that all atoms have been sorted into bins.
364 assert len(atom_i) == 0
365 assert len(bin_index_i) == 0
367 # Now we construct neighbor pairs by pairing up all atoms within a bin or
368 # between bin and neighboring bin. atom_pairs_pn is a helper buffer that
369 # contains all potential pairs of atoms between two bins, i.e. it is a list
370 # of length max_natoms_per_bin**2.
371 atom_pairs_pn = np.indices(
372 (max_natoms_per_bin, max_natoms_per_bin), dtype=int
373 )
374 atom_pairs_pn = atom_pairs_pn.reshape(2, -1)
376 # Initialized empty neighbor list buffers.
377 first_at_neightuple_nn = []
378 secnd_at_neightuple_nn = []
379 cell_shift_vector_x_n = []
380 cell_shift_vector_y_n = []
381 cell_shift_vector_z_n = []
383 # This is the main neighbor list search. We loop over neighboring bins and
384 # then construct all possible pairs of atoms between two bins, assuming
385 # that each bin contains exactly max_natoms_per_bin atoms. We then throw
386 # out pairs involving pad atoms with atom index -1 below.
387 binz_xyz, biny_xyz, binx_xyz = np.meshgrid(
388 np.arange(nbins_c[2]),
389 np.arange(nbins_c[1]),
390 np.arange(nbins_c[0]),
391 indexing='ij',
392 )
393 # The memory layout of binx_xyz, biny_xyz, binz_xyz is such that computing
394 # the respective bin index leads to a linearly increasing consecutive list.
395 # The following assert statement succeeds:
396 # b_b = (binx_xyz + nbins_c[0] * (biny_xyz + nbins_c[1] *
397 # binz_xyz)).ravel()
398 # assert (b_b == np.arange(np.prod(nbins_c))).all()
400 # First atoms in pair.
401 _first_at_neightuple_n = atoms_in_bin_ba[:, atom_pairs_pn[0]]
402 for dz in range(-neigh_search_z, neigh_search_z + 1):
403 for dy in range(-neigh_search_y, neigh_search_y + 1):
404 for dx in range(-neigh_search_x, neigh_search_x + 1):
405 # Bin index of neighboring bin and shift vector.
406 shiftx_xyz, neighbinx_xyz = divmod(binx_xyz + dx, nbins_c[0])
407 shifty_xyz, neighbiny_xyz = divmod(biny_xyz + dy, nbins_c[1])
408 shiftz_xyz, neighbinz_xyz = divmod(binz_xyz + dz, nbins_c[2])
409 neighbin_b = (
410 neighbinx_xyz
411 + nbins_c[0] * (neighbiny_xyz + nbins_c[1] * neighbinz_xyz)
412 ).ravel()
414 # Second atom in pair.
415 _secnd_at_neightuple_n = atoms_in_bin_ba[neighbin_b][
416 :, atom_pairs_pn[1]
417 ]
419 # Shift vectors.
420 _cell_shift_vector_x_n = np.resize(
421 shiftx_xyz.reshape(-1, 1),
422 (max_natoms_per_bin**2, shiftx_xyz.size),
423 ).T
424 _cell_shift_vector_y_n = np.resize(
425 shifty_xyz.reshape(-1, 1),
426 (max_natoms_per_bin**2, shifty_xyz.size),
427 ).T
428 _cell_shift_vector_z_n = np.resize(
429 shiftz_xyz.reshape(-1, 1),
430 (max_natoms_per_bin**2, shiftz_xyz.size),
431 ).T
433 # We have created too many pairs because we assumed each bin
434 # has exactly max_natoms_per_bin atoms. Remove all surperfluous
435 # pairs. Those are pairs that involve an atom with index -1.
436 mask = np.logical_and(
437 _first_at_neightuple_n != -1, _secnd_at_neightuple_n != -1
438 )
439 if mask.sum() > 0:
440 first_at_neightuple_nn += [_first_at_neightuple_n[mask]]
441 secnd_at_neightuple_nn += [_secnd_at_neightuple_n[mask]]
442 cell_shift_vector_x_n += [_cell_shift_vector_x_n[mask]]
443 cell_shift_vector_y_n += [_cell_shift_vector_y_n[mask]]
444 cell_shift_vector_z_n += [_cell_shift_vector_z_n[mask]]
446 # Flatten overall neighbor list.
447 first_at_neightuple_n = np.concatenate(first_at_neightuple_nn)
448 secnd_at_neightuple_n = np.concatenate(secnd_at_neightuple_nn)
449 cell_shift_vector_n = np.transpose(
450 [
451 np.concatenate(cell_shift_vector_x_n),
452 np.concatenate(cell_shift_vector_y_n),
453 np.concatenate(cell_shift_vector_z_n),
454 ]
455 )
457 # Add global cell shift to shift vectors
458 cell_shift_vector_n += (
459 cell_shift_ic[first_at_neightuple_n]
460 - cell_shift_ic[secnd_at_neightuple_n]
461 )
463 # Remove all self-pairs that do not cross the cell boundary.
464 if not self_interaction:
465 m = np.logical_not(
466 np.logical_and(
467 first_at_neightuple_n == secnd_at_neightuple_n,
468 (cell_shift_vector_n == 0).all(axis=1),
469 )
470 )
471 first_at_neightuple_n = first_at_neightuple_n[m]
472 secnd_at_neightuple_n = secnd_at_neightuple_n[m]
473 cell_shift_vector_n = cell_shift_vector_n[m]
475 # For nonperiodic directions, remove any bonds that cross the domain
476 # boundary.
477 for c in range(3):
478 if not pbc[c]:
479 m = cell_shift_vector_n[:, c] == 0
480 first_at_neightuple_n = first_at_neightuple_n[m]
481 secnd_at_neightuple_n = secnd_at_neightuple_n[m]
482 cell_shift_vector_n = cell_shift_vector_n[m]
484 # Sort neighbor list.
485 i = np.argsort(first_at_neightuple_n)
486 first_at_neightuple_n = first_at_neightuple_n[i]
487 secnd_at_neightuple_n = secnd_at_neightuple_n[i]
488 cell_shift_vector_n = cell_shift_vector_n[i]
490 # Compute distance vectors.
491 distance_vector_nc = (
492 positions[secnd_at_neightuple_n]
493 - positions[first_at_neightuple_n]
494 + cell_shift_vector_n.dot(cell)
495 )
496 abs_distance_vector_n = np.sqrt(
497 np.sum(distance_vector_nc * distance_vector_nc, axis=1)
498 )
500 # We have still created too many pairs. Only keep those with distance
501 # smaller than max_cutoff.
502 mask = abs_distance_vector_n < max_cutoff
503 first_at_neightuple_n = first_at_neightuple_n[mask]
504 secnd_at_neightuple_n = secnd_at_neightuple_n[mask]
505 cell_shift_vector_n = cell_shift_vector_n[mask]
506 distance_vector_nc = distance_vector_nc[mask]
507 abs_distance_vector_n = abs_distance_vector_n[mask]
509 if isinstance(cutoff, dict) and numbers is not None:
510 # If cutoff is a dictionary, then the cutoff radii are specified per
511 # element pair. We now have a list up to maximum cutoff.
512 per_pair_cutoff_n = np.zeros_like(abs_distance_vector_n)
513 for (atomic_number1, atomic_number2), c in cutoff.items():
514 try:
515 atomic_number1 = atomic_numbers[atomic_number1]
516 except KeyError:
517 pass
518 try:
519 atomic_number2 = atomic_numbers[atomic_number2]
520 except KeyError:
521 pass
522 if atomic_number1 == atomic_number2:
523 mask = np.logical_and(
524 numbers[first_at_neightuple_n] == atomic_number1,
525 numbers[secnd_at_neightuple_n] == atomic_number2,
526 )
527 else:
528 mask = np.logical_or(
529 np.logical_and(
530 numbers[first_at_neightuple_n] == atomic_number1,
531 numbers[secnd_at_neightuple_n] == atomic_number2,
532 ),
533 np.logical_and(
534 numbers[first_at_neightuple_n] == atomic_number2,
535 numbers[secnd_at_neightuple_n] == atomic_number1,
536 ),
537 )
538 per_pair_cutoff_n[mask] = c
539 mask = abs_distance_vector_n < per_pair_cutoff_n
540 first_at_neightuple_n = first_at_neightuple_n[mask]
541 secnd_at_neightuple_n = secnd_at_neightuple_n[mask]
542 cell_shift_vector_n = cell_shift_vector_n[mask]
543 distance_vector_nc = distance_vector_nc[mask]
544 abs_distance_vector_n = abs_distance_vector_n[mask]
545 elif not np.isscalar(cutoff):
546 # If cutoff is neither a dictionary nor a scalar, then we assume it is
547 # a list or numpy array that contains atomic radii. Atoms are neighbors
548 # if their radii overlap.
549 mask = (
550 abs_distance_vector_n
551 < cutoff[first_at_neightuple_n] + cutoff[secnd_at_neightuple_n]
552 )
553 first_at_neightuple_n = first_at_neightuple_n[mask]
554 secnd_at_neightuple_n = secnd_at_neightuple_n[mask]
555 cell_shift_vector_n = cell_shift_vector_n[mask]
556 distance_vector_nc = distance_vector_nc[mask]
557 abs_distance_vector_n = abs_distance_vector_n[mask]
559 # Assemble return tuple.
560 retvals = []
561 for q in quantities:
562 if q == 'i':
563 retvals += [first_at_neightuple_n]
564 elif q == 'j':
565 retvals += [secnd_at_neightuple_n]
566 elif q == 'D':
567 retvals += [distance_vector_nc]
568 elif q == 'd':
569 retvals += [abs_distance_vector_n]
570 elif q == 'S':
571 retvals += [cell_shift_vector_n]
572 else:
573 raise ValueError('Unsupported quantity specified.')
574 if len(retvals) == 1:
575 return retvals[0]
576 else:
577 return tuple(retvals)
580def neighbor_list(quantities, a, cutoff, self_interaction=False, max_nbins=1e6):
581 """Compute a neighbor list for an atomic configuration.
583 Atoms outside periodic boundaries are mapped into the box. Atoms
584 outside nonperiodic boundaries are included in the neighbor list
585 but complexity of neighbor list search for those can become n^2.
587 The neighbor list is sorted by first atom index 'i', but not by second
588 atom index 'j'.
590 Parameters
591 ----------
592 quantities: str
593 Quantities to compute by the neighbor list algorithm. Each character
594 in this string defines a quantity. They are returned in a tuple of
595 the same order. Possible quantities are:
597 * 'i' : first atom index
598 * 'j' : second atom index
599 * 'd' : absolute distance
600 * 'D' : distance vector
601 * 'S' : shift vector (number of cell boundaries crossed by the bond
602 between atom i and j). With the shift vector S, the
603 distances D between atoms can be computed from:
604 D = a.positions[j]-a.positions[i]+S.dot(a.cell)
605 a: :class:`ase.Atoms`
606 Atomic configuration.
607 cutoff: float or dict
608 Cutoff for neighbor search. It can be:
610 * A single float: This is a global cutoff for all elements.
611 * A dictionary: This specifies cutoff values for element
612 pairs. Specification accepts element numbers of symbols.
613 Example: {(1, 6): 1.1, (1, 1): 1.0, ('C', 'C'): 1.85}
614 * A list/array with a per atom value: This specifies the radius of
615 an atomic sphere for each atoms. If spheres overlap, atoms are
616 within each others neighborhood. See
617 :func:`~ase.neighborlist.natural_cutoffs`
618 for an example on how to get such a list.
620 self_interaction: bool
621 Return the atom itself as its own neighbor if set to true.
622 Default: False
623 max_nbins: int
624 Maximum number of bins used in neighbor search. This is used to limit
625 the maximum amount of memory required by the neighbor list.
627 Returns
628 -------
629 i, j, ...: array
630 Tuple with arrays for each quantity specified above. Indices in `i`
631 are returned in ascending order 0..len(a), but the order of (i,j)
632 pairs is not guaranteed.
634 Examples
635 --------
637 >>> import numpy as np
638 >>> from ase.build import bulk, molecule
640 1. Coordination counting
642 >>> atoms = molecule('isobutane')
643 >>> i = neighbor_list('i', atoms, 1.85)
644 >>> coord = np.bincount(i, minlength=len(atoms))
646 2. Coordination counting with different cutoffs for each pair of species
648 >>> cutoff = {('H', 'H'): 1.1, ('C', 'H'): 1.3, ('C', 'C'): 1.85}
649 >>> i = neighbor_list('i', atoms, cutoff)
650 >>> coord = np.bincount(i, minlength=len(atoms))
652 3. Pair distribution function
654 >>> atoms = bulk('Cu', cubic=True) * 3
655 >>> atoms.rattle(0.5, rng=np.random.default_rng(42))
656 >>> cutoff = 5.0
657 >>> d = neighbor_list('d', atoms, cutoff)
658 >>> hist, bin_edges = np.histogram(d, bins=100, range=(0.0, cutoff))
659 >>> hist = hist / len(atoms) # per atom
660 >>> rho_mean = len(atoms) / atoms.cell.volume
661 >>> dv = 4.0 * np.pi * (bin_edges[1:] ** 3 - bin_edges[:-1] ** 3) / 3.0
662 >>> rho = hist / dv
663 >>> pdf = rho / rho_mean
665 4. Forces of a pair potential
667 >>> natoms = len(atoms)
668 >>> i, j, d, D = neighbor_list('ijdD', atoms, 5.0)
669 >>> # Lennard-Jones potential
670 >>> eps = 1.0
671 >>> sgm = 1.0
672 >>> epairs = 4.0 * eps * ((sgm / d) ** 12 - (sgm / d) ** 6)
673 >>> energy = 0.5 * epairs.sum() # correct double-counting
674 >>> dd = -4.0 * eps * (12 * (sgm / d) ** 13 - 6 * (sgm / d) ** 7) / sgm
675 >>> dd = (dd * (D.T / d)).T
676 >>> fx = -1.0 * np.bincount(i, weights=dd[:, 0], minlength=natoms)
677 >>> fy = -1.0 * np.bincount(i, weights=dd[:, 1], minlength=natoms)
678 >>> fz = -1.0 * np.bincount(i, weights=dd[:, 2], minlength=natoms)
680 5. Force-constant matrix of a pair potential
682 >>> i, j, d, D = neighbor_list('ijdD', atoms, 5.0)
683 >>> epairs = 1.0 / d # Coulomb potential
684 >>> forces = (D.T / d**3).T # (npairs, 3)
685 >>> # second derivative
686 >>> d2 = 3.0 * D[:, :, None] * D[:, None, :] / d[:, None, None] ** 5
687 >>> for k in range(3):
688 ... d2[:, k, k] -= 1.0 / d**3
689 >>> # force-constant matrix
690 >>> fc = np.zeros((natoms, 3, natoms, 3))
691 >>> for ia in range(natoms):
692 ... for ja in range(natoms):
693 ... fc[ia, :, ja, :] -= d2[(i == ia) & (j == ja), :, :].sum(axis=0)
694 >>> for ia in range(natoms):
695 ... fc[ia, :, ia, :] -= fc[ia].sum(axis=1)
697 """
698 return primitive_neighbor_list(
699 quantities,
700 a.pbc,
701 a.get_cell(complete=True),
702 a.positions,
703 cutoff,
704 numbers=a.numbers,
705 self_interaction=self_interaction,
706 max_nbins=max_nbins,
707 )
710def first_neighbors(natoms, first_atom):
711 """
712 Compute an index array pointing to the ranges within the neighbor list that
713 contain the neighbors for a certain atom.
715 Parameters
716 ----------
718 natoms : int
719 Total number of atom.
720 first_atom : array_like
721 Array containing the first atom 'i' of the neighbor tuple returned
722 by the neighbor list.
724 Returns
725 -------
727 seed : array
728 Array containing pointers to the start and end location of the
729 neighbors of a certain atom. Neighbors of atom k have indices from s[k]
730 to s[k+1]-1.
731 """
732 if len(first_atom) == 0:
733 return np.zeros(natoms + 1, dtype=int)
734 # Create a seed array (which is returned by this function) populated with
735 # -1.
736 seed = -np.ones(natoms + 1, dtype=int)
738 first_atom = np.asarray(first_atom)
740 # Mask array contains all position where the number in the (sorted) array
741 # with first atoms (in the neighbor pair) changes.
742 mask = first_atom[:-1] != first_atom[1:]
744 # Seed array needs to start at 0
745 seed[first_atom[0]] = 0
746 # Seed array needs to stop at the length of the neighbor list
747 seed[-1] = len(first_atom)
748 # Populate all intermediate seed with the index of where the mask array is
749 # true, i.e. the index where the first_atom array changes.
750 seed[first_atom[1:][mask]] = (np.arange(len(mask)) + 1)[mask]
752 # Now fill all remaining -1 value with the value in the seed array right
753 # behind them. (There are no neighbor so seed[i] and seed[i+1] must point)
754 # to the same index.
755 mask = seed == -1
756 while mask.any():
757 seed[mask] = seed[np.arange(natoms + 1)[mask] + 1]
758 mask = seed == -1
759 return seed
762def get_connectivity_matrix(nl, sparse=True):
763 """Return connectivity matrix for a given NeighborList (dtype=numpy.int8).
765 A matrix of shape (nAtoms, nAtoms) will be returned.
766 Connected atoms i and j will have matrix[i,j] == 1, unconnected
767 matrix[i,j] == 0. If bothways=True the matrix will be symmetric,
768 otherwise not!
770 If *sparse* is True, a scipy csr matrix is returned.
771 If *sparse* is False, a numpy matrix is returned.
773 Note that the old and new neighborlists might give different results
774 for periodic systems if bothways=False.
776 Example:
778 Determine which molecule in a system atom 1 belongs to.
780 >>> from scipy import sparse
782 >>> from ase.build import molecule
783 >>> from ase.neighborlist import get_connectivity_matrix
784 >>> from ase.neighborlist import natural_cutoffs
785 >>> from ase.neighborlist import NeighborList
787 >>> mol = molecule('CH3CH2OH')
788 >>> cutoffs = natural_cutoffs(mol)
789 >>> neighbor_list = NeighborList(
790 ... cutoffs, self_interaction=False, bothways=True)
791 >>> neighbor_list.update(mol)
792 True
794 >>> matrix = neighbor_list.get_connectivity_matrix()
795 >>> # or: matrix = get_connectivity_matrix(neighbor_list.nl)
796 >>> n_components, component_list = sparse.csgraph.connected_components(
797 ... matrix)
798 >>> idx = 1
799 >>> molIdx = component_list[idx]
800 >>> print("There are {} molecules in the system".format(n_components))
801 There are 1 molecules in the system
802 >>> print("Atom {} is part of molecule {}".format(idx, molIdx))
803 Atom 1 is part of molecule 0
804 >>> molIdxs = [i for i in range(len(component_list))
805 ... if component_list[i] == molIdx]
806 >>> print("Atoms are part of molecule {}: {}".format(molIdx, molIdxs))
807 Atoms are part of molecule 0: [0, 1, 2, 3, 4, 5, 6, 7, 8]
808 """
810 nAtoms = len(nl.cutoffs)
812 if nl.nupdates <= 0:
813 raise RuntimeError(
814 'Must call update(atoms) on your neighborlist first!'
815 )
817 if sparse:
818 matrix = sp.dok_matrix((nAtoms, nAtoms), dtype=np.int8)
819 else:
820 matrix = np.zeros((nAtoms, nAtoms), dtype=np.int8)
822 for i in range(nAtoms):
823 for idx in nl.get_neighbors(i)[0]:
824 matrix[i, idx] = 1
826 return matrix
829class NewPrimitiveNeighborList:
830 """Neighbor list object. Wrapper around neighbor_list and first_neighbors.
832 cutoffs: list of float
833 List of cutoff radii - one for each atom. If the spheres (defined by
834 their cutoff radii) of two atoms overlap, they will be counted as
835 neighbors.
836 skin: float
837 If no atom has moved more than the skin-distance since the
838 last call to the
839 :meth:`~ase.neighborlist.NewPrimitiveNeighborList.update()`
840 method, then the neighbor list can be reused. This will save
841 some expensive rebuilds of the list, but extra neighbors outside
842 the cutoff will be returned.
843 sorted: bool
844 Sort neighbor list.
845 self_interaction: bool
846 Should an atom return itself as a neighbor?
847 bothways: bool
848 Return all neighbors. Default is to return only "half" of
849 the neighbors.
851 Example:
853 >>> from ase.build import bulk
854 >>> from ase.neighborlist import NewPrimitiveNeighborList
856 >>> nl = NewPrimitiveNeighborList([2.3, 1.7])
857 >>> atoms = bulk('Cu', 'fcc', a=3.6)
858 >>> nl.update(atoms.pbc, atoms.get_cell(), atoms.positions)
859 True
860 >>> indices, offsets = nl.get_neighbors(0)
861 """
863 def __init__(
864 self,
865 cutoffs,
866 skin=0.3,
867 sorted=False,
868 self_interaction=True,
869 bothways=False,
870 use_scaled_positions=False,
871 ):
872 self.cutoffs = np.asarray(cutoffs) + skin
873 self.skin = skin
874 self.sorted = sorted
875 self.self_interaction = self_interaction
876 self.bothways = bothways
877 self.nupdates = 0
878 self.use_scaled_positions = use_scaled_positions
880 def update(self, pbc, cell, positions, numbers=None):
881 """Make sure the list is up to date."""
883 if self.nupdates == 0:
884 self.build(pbc, cell, positions, numbers=numbers)
885 return True
887 if (
888 (self.pbc != pbc).any()
889 or (self.cell != cell).any()
890 or ((self.positions - positions) ** 2).sum(1).max() > self.skin**2
891 ):
892 self.build(pbc, cell, positions, numbers=numbers)
893 return True
895 return False
897 def build(self, pbc, cell, positions, numbers=None):
898 """Build the list."""
899 self.pbc = np.array(pbc, copy=True)
900 self.cell = np.array(cell, copy=True)
901 self.positions = np.array(positions, copy=True)
903 pair_first, pair_second, offset_vec = primitive_neighbor_list(
904 'ijS',
905 pbc,
906 cell,
907 positions,
908 self.cutoffs,
909 numbers=numbers,
910 self_interaction=self.self_interaction,
911 use_scaled_positions=self.use_scaled_positions,
912 )
914 if len(positions) > 0 and not self.bothways:
915 offset_x, offset_y, offset_z = offset_vec.T
917 mask = offset_z > 0
918 mask &= offset_y == 0
919 mask |= offset_y > 0
920 mask &= offset_x == 0
921 mask |= offset_x > 0
922 mask |= (pair_first <= pair_second) & (offset_vec == 0).all(axis=1)
924 pair_first = pair_first[mask]
925 pair_second = pair_second[mask]
926 offset_vec = offset_vec[mask]
928 if len(positions) > 0 and self.sorted:
929 mask = np.argsort(pair_first * len(pair_first) + pair_second)
930 pair_first = pair_first[mask]
931 pair_second = pair_second[mask]
932 offset_vec = offset_vec[mask]
934 self.pair_first = pair_first
935 self.pair_second = pair_second
936 self.offset_vec = offset_vec
938 # Compute the index array point to the first neighbor
939 self.first_neigh = first_neighbors(len(positions), pair_first)
941 self.nupdates += 1
943 def get_neighbors(self, a):
944 """Return neighbors of atom number a.
946 A list of indices and offsets to neighboring atoms is
947 returned. The positions of the neighbor atoms can be
948 calculated like this:
950 >>> from ase.build import bulk
951 >>> from ase.neighborlist import NewPrimitiveNeighborList
953 >>> nl = NewPrimitiveNeighborList([2.3, 1.7])
954 >>> atoms = bulk('Cu', 'fcc', a=3.6)
955 >>> nl.update(atoms.pbc, atoms.get_cell(), atoms.positions)
956 True
957 >>> indices, offsets = nl.get_neighbors(0)
958 >>> for i, offset in zip(indices, offsets):
959 ... print(atoms.positions[i] + offset @ atoms.get_cell())
960 ... # doctest: +SKIP
962 Notice that if get_neighbors(a) gives atom b as a neighbor,
963 then get_neighbors(b) will not return a as a neighbor - unless
964 bothways=True was used."""
966 return (
967 self.pair_second[self.first_neigh[a] : self.first_neigh[a + 1]],
968 self.offset_vec[self.first_neigh[a] : self.first_neigh[a + 1]],
969 )
972class PrimitiveNeighborList:
973 """Neighbor list that works without Atoms objects.
975 This is less fancy, but can be used to avoid conversions between
976 scaled and non-scaled coordinates which may affect cell offsets
977 through rounding errors.
979 Attributes
980 ----------
981 nupdates : int
982 Number of updated times.
983 """
985 def __init__(
986 self,
987 cutoffs,
988 skin=0.3,
989 sorted=False,
990 self_interaction=True,
991 bothways=False,
992 use_scaled_positions=False,
993 ):
994 self.cutoffs = np.asarray(cutoffs) + skin
995 self.skin = skin
996 self.sorted = sorted
997 self.self_interaction = self_interaction
998 self.bothways = bothways
999 self.nupdates = 0
1000 self.use_scaled_positions = use_scaled_positions
1002 def update(self, pbc, cell, coordinates):
1003 """Make sure the list is up to date.
1005 Returns
1006 -------
1007 bool
1008 True if the neighbor list is updated.
1009 """
1011 if self.nupdates == 0:
1012 self.build(pbc, cell, coordinates)
1013 return True
1015 if (
1016 (self.pbc != pbc).any()
1017 or (self.cell != cell).any()
1018 or ((self.coordinates - coordinates) ** 2).sum(1).max()
1019 > self.skin**2
1020 ):
1021 self.build(pbc, cell, coordinates)
1022 return True
1024 return False
1026 def build(self, pbc, cell, coordinates):
1027 """Build the list.
1029 Coordinates are taken to be scaled or not according
1030 to self.use_scaled_positions.
1031 """
1032 self.pbc = pbc = np.array(pbc, copy=True)
1033 self.cell = cell = Cell(cell)
1034 self.coordinates = coordinates = np.array(coordinates, copy=True)
1036 if len(self.cutoffs) != len(coordinates):
1037 raise ValueError(
1038 'Wrong number of cutoff radii: {} != {}'.format(
1039 len(self.cutoffs), len(coordinates)
1040 )
1041 )
1043 rcmax = self.cutoffs.max() if len(self.cutoffs) > 0 else 0.0
1045 if self.use_scaled_positions:
1046 positions0 = cell.cartesian_positions(coordinates)
1047 else:
1048 positions0 = coordinates
1050 rcell, op = minkowski_reduce(cell, pbc)
1051 positions = wrap_positions(positions0, rcell, pbc=pbc, eps=0)
1053 natoms = len(positions)
1054 self.nupdates += 1
1055 if natoms == 0:
1056 self.neighbors = []
1057 self.displacements = []
1058 return
1060 tree = cKDTree(positions, copy_data=True)
1061 offsets = cell.scaled_positions(positions - positions0)
1062 offsets = offsets.round().astype(int)
1064 N = _calc_expansion(rcell, pbc, rcmax)
1066 # Collect neighbours as flat (first, second, offset) arrays. The query
1067 # returns a Python list per atom; the per-atom distance filtering and
1068 # offset bookkeeping are then done with vectorised array operations
1069 # rather than a Python loop over atoms, which dominated the build time.
1070 arange = np.arange(natoms)
1071 first_parts = []
1072 second_parts = []
1073 offset_parts = []
1075 for n1, n2, n3 in itertools.product(
1076 range(N[0] + 1), range(-N[1], N[1] + 1), range(-N[2], N[2] + 1)
1077 ):
1078 if n1 == 0 and (n2 < 0 or n2 == 0 and n3 < 0):
1079 continue
1081 displacement = (n1, n2, n3) @ rcell
1082 shift0 = (n1, n2, n3) @ op
1083 indices_all = tree.query_ball_point(
1084 positions - displacement,
1085 r=self.cutoffs + rcmax,
1086 )
1088 counts = np.fromiter(
1089 (len(ind) for ind in indices_all), dtype=int, count=natoms
1090 )
1091 if counts.sum() == 0:
1092 continue
1094 first = np.repeat(arange, counts)
1095 second = np.concatenate(
1096 [np.asarray(ind, dtype=int) for ind in indices_all if len(ind)]
1097 )
1098 delta = positions[second] + displacement - positions[first]
1099 distances = np.sqrt(np.einsum('ij,ij->i', delta, delta))
1100 mask = distances < self.cutoffs[second] + self.cutoffs[first]
1101 if n1 == 0 and n2 == 0 and n3 == 0:
1102 if self.self_interaction:
1103 mask &= second >= first
1104 else:
1105 mask &= second > first
1106 first = first[mask]
1107 second = second[mask]
1109 first_parts.append(first)
1110 second_parts.append(second)
1111 offset_parts.append(shift0 + offsets[second] - offsets[first])
1113 if first_parts:
1114 first = np.concatenate(first_parts)
1115 second = np.concatenate(second_parts)
1116 disp = np.concatenate(offset_parts)
1117 else:
1118 first = np.zeros(0, dtype=int)
1119 second = np.zeros(0, dtype=int)
1120 disp = np.zeros((0, 3), dtype=int)
1122 if self.bothways:
1123 # Add the reverse of every pair (a -> b becomes b -> a with the
1124 # opposite offset), skipping a true self interaction at zero offset.
1125 keep = ~((first == second) & (disp == 0).all(axis=1))
1126 rev_first, rev_second = second[keep], first[keep]
1127 first = np.concatenate((first, rev_first))
1128 second = np.concatenate((second, rev_second))
1129 disp = np.concatenate((disp, -disp[keep]))
1131 # Sort by first atom (stable) to group neighbours per atom.
1132 order = np.argsort(first, kind='stable')
1133 first, second, disp = first[order], second[order], disp[order]
1135 # Regroup the flat arrays into the per-atom lists the class exposes via
1136 # get_neighbors (and that NeighborList relies on).
1137 splits = np.cumsum(np.bincount(first, minlength=natoms))[:-1]
1138 self.neighbors = [nbs.astype(int) for nbs in np.split(second, splits)]
1139 self.displacements = [
1140 d.astype(int).reshape((-1, 3)) for d in np.split(disp, splits)
1141 ]
1143 if self.sorted:
1144 _sort_neighbors(self.neighbors, self.displacements)
1146 def get_neighbors(self, a):
1147 """Return neighbors of atom number a.
1149 A list of indices and offsets to neighboring atoms is
1150 returned. The positions of the neighbor atoms can be
1151 calculated like this:
1153 >>> from ase.build import bulk
1154 >>> from ase.neighborlist import NewPrimitiveNeighborList
1156 >>> nl = NewPrimitiveNeighborList([2.3, 1.7])
1157 >>> atoms = bulk('Cu', 'fcc', a=3.6)
1158 >>> nl.update(atoms.pbc, atoms.get_cell(), atoms.positions)
1159 True
1160 >>> indices, offsets = nl.get_neighbors(0)
1161 >>> for i, offset in zip(indices, offsets):
1162 ... print(atoms.positions[i] + offset @ atoms.get_cell())
1163 ... # doctest: +SKIP
1165 Notice that if get_neighbors(a) gives atom b as a neighbor,
1166 then get_neighbors(b) will not return a as a neighbor - unless
1167 bothways=True was used."""
1169 return self.neighbors[a], self.displacements[a]
1172def _calc_expansion(rcell, pbc, rcmax):
1173 r"""Calculate expansion to contain a sphere of radius `2.0 * rcmax`.
1175 This function determines the minimum supercell (parallelepiped) that
1176 contains a sphere of radius `2.0 * rcmax`. For this, `a_1` is projected
1177 onto the unit vector perpendicular to `a_2 \times a_3` (i.e. the unit
1178 vector along the direction `b_1`) to know how many `a_1`'s the supercell
1179 takes to contain the sphere.
1180 """
1181 ircell = np.linalg.pinv(rcell)
1182 vs = np.sqrt(np.add.reduce(ircell**2, axis=0))
1183 ns = np.where(pbc, np.ceil(2.0 * rcmax * vs), 0.0)
1184 return ns.astype(int)
1187def _sort_neighbors(neighbors, offsets):
1188 """Sort neighbors first by indices and then offsets."""
1189 natoms = len(neighbors)
1190 for a in range(natoms):
1191 keys = (
1192 offsets[a][:, 2],
1193 offsets[a][:, 1],
1194 offsets[a][:, 0],
1195 neighbors[a],
1196 )
1197 mask = np.lexsort(keys)
1198 neighbors[a] = neighbors[a][mask]
1199 offsets[a] = offsets[a][mask]
1202class NeighborList:
1203 """Neighbor list object.
1205 cutoffs: list of float
1206 List of cutoff radii - one for each atom. If the spheres
1207 (defined by their cutoff radii) of two atoms overlap, they
1208 will be counted as neighbors. See
1209 :func:`~ase.neighborlist.natural_cutoffs` for an example on
1210 how to get such a list.
1212 skin: float
1213 If no atom has moved more than the skin-distance since the
1214 last call to the
1215 :meth:`~ase.neighborlist.NeighborList.update()` method, then
1216 the neighbor list can be reused. This will save some
1217 expensive rebuilds of the list, but extra neighbors outside
1218 the cutoff will be returned.
1219 self_interaction: bool
1220 Should an atom return itself as a neighbor?
1221 bothways: bool
1222 Return all neighbors. Default is to return only "half" of
1223 the neighbors.
1224 primitive: class
1225 Define which implementation to use. Older and quadratically-scaling
1226 :class:`~ase.neighborlist.PrimitiveNeighborList` or newer and
1227 linearly-scaling :class:`~ase.neighborlist.NewPrimitiveNeighborList`.
1229 Example:
1231 >>> from ase.build import molecule
1232 >>> from ase.neighborlist import NeighborList
1234 >>> atoms = molecule("CO")
1235 >>> nl = NeighborList([0.76, 0.66])
1236 >>> nl.update(atoms)
1237 True
1238 >>> indices, offsets = nl.get_neighbors(0)
1240 """
1242 def __init__(
1243 self,
1244 cutoffs,
1245 skin=0.3,
1246 sorted=False,
1247 self_interaction=True,
1248 bothways=False,
1249 primitive=PrimitiveNeighborList,
1250 ):
1251 self.nl = primitive(
1252 cutoffs,
1253 skin,
1254 sorted,
1255 self_interaction=self_interaction,
1256 bothways=bothways,
1257 )
1259 def update(self, atoms):
1260 """
1261 See :meth:`ase.neighborlist.PrimitiveNeighborList.update` or
1262 :meth:`ase.neighborlist.PrimitiveNeighborList.update`.
1263 """
1264 return self.nl.update(
1265 atoms.pbc, atoms.get_cell(complete=True), atoms.positions
1266 )
1268 def get_neighbors(self, a):
1269 """
1270 See :meth:`ase.neighborlist.PrimitiveNeighborList.get_neighbors` or
1271 :meth:`ase.neighborlist.PrimitiveNeighborList.get_neighbors`.
1272 """
1273 if self.nl.nupdates <= 0:
1274 raise RuntimeError(
1275 'Must call update(atoms) on your neighborlist first!'
1276 )
1278 return self.nl.get_neighbors(a)
1280 def get_connectivity_matrix(self, sparse=True):
1281 """
1282 See :func:`~ase.neighborlist.get_connectivity_matrix`.
1283 """
1284 return get_connectivity_matrix(self.nl, sparse)
1286 @property
1287 def nupdates(self):
1288 """Get number of updates."""
1289 return self.nl.nupdates
1291 @property
1292 @deprecated(
1293 'Use, e.g., `sum(_.size for _ in nl.neighbors)` '
1294 'for `bothways=False` and `self_interaction=False`.'
1295 )
1296 def nneighbors(self):
1297 """Get number of neighbors.
1299 .. deprecated:: 3.24.0
1300 """
1301 nneighbors = sum(indices.size for indices in self.nl.neighbors)
1302 if self.nl.self_interaction:
1303 nneighbors -= len(self.nl.neighbors)
1304 return nneighbors // 2 if self.nl.bothways else nneighbors
1306 @property
1307 @deprecated(
1308 'Use, e.g., `sum(_.any(1).sum() for _ in nl.displacements)` '
1309 'for `bothways=False` and `self_interaction=False`.'
1310 )
1311 def npbcneighbors(self):
1312 """Get number of pbc neighbors.
1314 .. deprecated:: 3.24.0
1315 """
1316 nneighbors = sum(
1317 offsets.any(axis=1).sum() for offsets in self.nl.displacements
1318 ) # sum up all neighbors that have non-zero supercell offsets
1319 return nneighbors // 2 if self.nl.bothways else nneighbors