Coverage for ase/geometry/analysis.py: 64.15%
265 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"""Tools for analyzing instances of :class:`~ase.Atoms`"""
3import numpy as np
5from ase import Atoms
6from ase.geometry.rdf import get_containing_cell_length, get_rdf
7from ase.neighborlist import (
8 build_neighbor_list,
9 get_distance_indices,
10 get_distance_matrix,
11)
12from ase.utils import deprecated
14__all__ = ['Analysis']
17def get_max_containing_cell_length(images: list[Atoms]):
18 i2diff = np.zeros(3)
19 for image in images:
20 np.maximum(get_containing_cell_length(image), i2diff, out=i2diff)
21 return i2diff
24def get_max_volume_estimate(images: list[Atoms]) -> float:
25 return np.prod(get_max_containing_cell_length(images))
28class Analysis:
29 """Analysis class
31 Parameters for initialization:
33 images: :class:`~ase.Atoms` object or list of such
34 Images to analyze.
36 nl: None, :class:`~ase.neighborlist.NeighborList` object or list
37 of such Neighborlist(s) for the given images. One or nImages,
38 depending if bonding pattern changes or is constant. Using one
39 Neigborlist greatly improves speed. kwargs: options, dict
40 Arguments for constructing
41 :class:`~ase.neighborlist.NeighborList` object if :data:`nl`
42 is None.
44 The choice of ``bothways=True`` for the
45 :class:`~ase.neighborlist.NeighborList` object will not influence
46 the amount of bonds/angles/dihedrals you get, all are reported in
47 both directions. Use the *unique*-labeled properties to get lists
48 without duplicates.
49 """
51 def __init__(self, images, nl=None, **kwargs):
52 self.images = images
54 if isinstance(nl, list):
55 assert len(nl) == self.nImages
56 self._nl = nl
57 elif nl is not None:
58 self._nl = [nl]
59 else:
60 self._nl = [build_neighbor_list(self.images[0], **kwargs)]
62 self._cache = {}
64 def _get_slice(self, imageIdx):
65 """Return a slice from user input.
67 Using *imageIdx* (can be integer or slice) the analyzed frames can
68 be specified. If *imageIdx* is None, all frames will be analyzed.
69 """
70 # get slice from imageIdx
71 if isinstance(imageIdx, int):
72 sl = slice(imageIdx, imageIdx + 1)
73 elif isinstance(imageIdx, slice):
74 sl = imageIdx
75 elif imageIdx is None:
76 sl = slice(0, None)
77 else:
78 raise ValueError(
79 'Unsupported type for imageIdx in '
80 'ase.geometry.analysis.Analysis._get_slice'
81 )
82 return sl
84 @property
85 def images(self):
86 """Images.
88 Set during initialization but can also be set later.
89 """
90 return self._images
92 @images.setter
93 def images(self, images):
94 """Set images"""
95 if isinstance(images, list):
96 self._images = images
97 else:
98 self._images = [images]
100 @images.deleter
101 def images(self):
102 """Delete images"""
103 self._images = None
105 @property
106 def nImages(self):
107 """Number of Images in this instance.
109 Cannot be set, is determined automatically.
110 """
111 return len(self.images)
113 @property
114 def nl(self):
115 """Neighbor Lists in this instance.
117 Set during initialization.
119 **No setter or deleter, only getter**
120 """
121 return self._nl
123 def _get_all_x(self, distance):
124 """Helper function to get bonds, angles, dihedrals"""
125 maxIter = self.nImages
126 if len(self.nl) == 1:
127 maxIter = 1
129 xList = []
130 for i in range(maxIter):
131 xList.append(
132 get_distance_indices(self.distance_matrix[i], distance)
133 )
135 return xList
137 @property
138 def all_bonds(self):
139 """All Bonds.
141 A list with indices of bonded atoms for each neighborlist in
142 *self*. Atom i is connected to all atoms inside
143 result[i]. Duplicates from PBCs are removed. See also
144 :data:`unique_bonds`.
146 **No setter or deleter, only getter**
148 """
149 if 'allBonds' not in self._cache:
150 self._cache['allBonds'] = self._get_all_x(1)
152 return self._cache['allBonds']
154 @property
155 def all_angles(self):
156 """All angles
158 A list with indices of atoms in angles for each neighborlist in *self*.
159 Atom i forms an angle to the atoms inside the tuples in result[i]:
161 i -- result[i][x][0] -- result[i][x][1]
163 where x is in range(number of angles from i). See also
164 :data:`unique_angles`.
166 **No setter or deleter, only getter**
168 """
169 if 'allAngles' not in self._cache:
170 self._cache['allAngles'] = []
171 distList = self._get_all_x(2)
173 for imI in range(len(distList)):
174 self._cache['allAngles'].append([])
175 # iterate over second neighbors of all atoms
176 for iAtom, secNeighs in enumerate(distList[imI]):
177 self._cache['allAngles'][-1].append([])
178 if len(secNeighs) == 0:
179 continue
180 firstNeighs = self.all_bonds[imI][iAtom]
181 # iterate over second neighbors of iAtom
182 for kAtom in secNeighs:
183 relevantFirstNeighs = [
184 idx
185 for idx in firstNeighs
186 if kAtom in self.all_bonds[imI][idx]
187 ]
188 # iterate over all atoms that are connected to
189 # iAtom and kAtom
190 for jAtom in relevantFirstNeighs:
191 self._cache['allAngles'][-1][-1].append(
192 (jAtom, kAtom)
193 )
195 return self._cache['allAngles']
197 @property
198 def all_dihedrals(self):
199 """All dihedrals.
201 Returns a list with indices of atoms in dihedrals for each
202 neighborlist in this instance.
204 Atom i forms a dihedral to the atoms inside the tuples in result[i]:
206 i -- result[i][x][0] -- result[i][x][1] -- result[i][x][2]
208 where x is in range(number of dihedrals from i). See also
209 :data:`unique_dihedrals`.
211 **No setter or deleter, only getter**
213 """
214 if 'allDihedrals' not in self._cache:
215 self._cache['allDihedrals'] = []
216 distList = self._get_all_x(3)
218 for imI in range(len(distList)):
219 self._cache['allDihedrals'].append([])
220 for iAtom, thirdNeighs in enumerate(distList[imI]):
221 self._cache['allDihedrals'][-1].append([])
222 if len(thirdNeighs) == 0:
223 continue
224 anglesI = self.all_angles[imI][iAtom]
225 # iterate over third neighbors of iAtom
226 for lAtom in thirdNeighs:
227 secondNeighs = [angle[-1] for angle in anglesI]
228 firstNeighs = [angle[0] for angle in anglesI]
229 relevantSecondNeighs = [
230 idx
231 for idx in secondNeighs
232 if lAtom in self.all_bonds[imI][idx]
233 ]
234 relevantFirstNeighs = [
235 firstNeighs[secondNeighs.index(idx)]
236 for idx in relevantSecondNeighs
237 ]
238 # iterate over all atoms that are connected to
239 # iAtom and lAtom
240 for jAtom, kAtom in zip(
241 relevantFirstNeighs, relevantSecondNeighs
242 ):
243 # remove dihedrals in circles
244 tupl = (jAtom, kAtom, lAtom)
245 if len(set((iAtom,) + tupl)) != 4:
246 continue
247 # avoid duplicates
248 elif tupl in self._cache['allDihedrals'][-1][-1]:
249 continue
250 elif iAtom in tupl:
251 raise RuntimeError(
252 'Something is wrong in '
253 'analysis.all_dihedrals!'
254 )
255 self._cache['allDihedrals'][-1][-1].append(
256 (jAtom, kAtom, lAtom)
257 )
259 return self._cache['allDihedrals']
261 @property
262 def adjacency_matrix(self):
263 """The adjacency/connectivity matrix.
265 If not already done, build a list of adjacency matrices for
266 all :data:`nl`.
268 **No setter or deleter, only getter**
270 """
272 if 'adjacencyMatrix' not in self._cache:
273 self._cache['adjacencyMatrix'] = []
274 for i in range(len(self.nl)):
275 self._cache['adjacencyMatrix'].append(
276 self.nl[i].get_connectivity_matrix()
277 )
279 return self._cache['adjacencyMatrix']
281 @property
282 def distance_matrix(self):
283 """The distance matrix.
285 If not already done, build a list of distance matrices for all
286 :data:`nl`. See :meth:`ase.neighborlist.get_distance_matrix`.
288 **No setter or deleter, only getter**
289 """
291 if 'distanceMatrix' not in self._cache:
292 self._cache['distanceMatrix'] = []
293 for i in range(len(self.nl)):
294 self._cache['distanceMatrix'].append(
295 get_distance_matrix(self.adjacency_matrix[i])
296 )
298 return self._cache['distanceMatrix']
300 @property
301 def unique_bonds(self):
302 """Get Unique Bonds.
304 :data:`all_bonds` i-j without j-i. This is the upper triangle of the
305 connectivity matrix (i,j), `i < j`
307 """
308 bonds = []
309 for imI in range(len(self.all_bonds)):
310 bonds.append([])
311 for iAtom, bonded in enumerate(self.all_bonds[imI]):
312 bonds[-1].append([jAtom for jAtom in bonded if jAtom > iAtom])
314 return bonds
316 def _filter_unique(self, l):
317 """Helper function to filter for unique lists in a list
318 that also contains the reversed items.
319 """
320 r = []
321 # iterate over images
322 for imI in range(len(l)):
323 r.append([])
324 # iterate over atoms
325 for i, tuples in enumerate(l[imI]):
326 # add the ones where i is smaller than the last element
327 r[-1].append([x for x in tuples if i < x[-1]])
328 return r
330 def clear_cache(self):
331 """Delete all cached information."""
332 self._cache = {}
334 @property
335 def unique_angles(self):
336 """Get Unique Angles.
338 :data:`all_angles` i-j-k without k-j-i.
340 """
341 return self._filter_unique(self.all_angles)
343 @property
344 def unique_dihedrals(self):
345 """Get Unique Dihedrals.
347 :data:`all_dihedrals` i-j-k-l without l-k-j-i.
349 """
350 return self._filter_unique(self.all_dihedrals)
352 def _get_symbol_idxs(self, imI, sym):
353 """Get list of indices of element *sym*"""
354 if isinstance(imI, int):
355 return [
356 idx
357 for idx in range(len(self.images[imI]))
358 if self.images[imI][idx].symbol == sym
359 ]
360 else:
361 return [idx for idx in range(len(imI)) if imI[idx].symbol == sym]
363 def _idxTuple2SymbolTuple(self, imI, tup):
364 """Converts a tuple of indices to their symbols"""
365 return (self.images[imI][idx].symbol for idx in tup)
367 def get_bonds(self, A, B, unique=True):
368 """Get bonds from element A to element B.
370 Parameters
371 ----------
373 A, B: str
374 Get Bonds between elements A and B
375 unique: bool
376 Return the bonds both ways or just one way (A-B and B-A or only A-B)
378 Returns
379 -------
381 return: list of lists of tuples
382 return[imageIdx][atomIdx][bondI], each tuple starts with atomIdx.
384 Use :func:`get_values` to convert the returned list to values.
385 """
386 r = []
387 for imI in range(len(self.all_bonds)):
388 r.append([])
389 aIdxs = self._get_symbol_idxs(imI, A)
390 if A != B:
391 bIdxs = self._get_symbol_idxs(imI, B)
392 for idx in aIdxs:
393 bonded = self.all_bonds[imI][idx]
394 if A == B:
395 r[-1].extend(
396 [(idx, x) for x in bonded if (x in aIdxs) and (x > idx)]
397 )
398 else:
399 r[-1].extend([(idx, x) for x in bonded if x in bIdxs])
401 if not unique:
402 r[-1] += [x[::-1] for x in r[-1]]
404 return r
406 def get_angles(self, A, B, C, unique=True):
407 """Get angles from given elements A-B-C.
409 Parameters
410 ----------
412 A, B, C: str
413 Get Angles between elements A, B and C. **B will be the central
414 atom**.
416 unique: bool
417 Return the angles both ways or just one way
418 (A-B-C and C-B-A or only A-B-C)
420 Returns
421 -------
423 return: list of lists of tuples
424 return[imageIdx][atomIdx][angleI], each tuple starts with atomIdx.
426 Use :func:`get_values` to convert the returned list to values.
427 """
428 from itertools import combinations, product
430 r = []
431 for imI in range(len(self.all_angles)):
432 r.append([])
433 # Middle Atom is fixed
434 bIdxs = self._get_symbol_idxs(imI, B)
435 for bIdx in bIdxs:
436 bondedA = [
437 idx
438 for idx in self.all_bonds[imI][bIdx]
439 if self.images[imI][idx].symbol == A
440 ]
441 if len(bondedA) == 0:
442 continue
444 if A != C:
445 bondedC = [
446 idx
447 for idx in self.all_bonds[imI][bIdx]
448 if self.images[imI][idx].symbol == C
449 ]
450 if len(bondedC) == 0:
451 continue
453 if A == C:
454 extend = [
455 (x[0], bIdx, x[1])
456 for x in list(combinations(bondedA, 2))
457 ]
458 else:
459 extend = list(product(bondedA, [bIdx], bondedC))
461 if not unique:
462 extend += [x[::-1] for x in extend]
464 r[-1].extend(extend)
465 return r
467 def get_dihedrals(self, A, B, C, D, unique=True):
468 """Get dihedrals A-B-C-D.
470 Parameters
471 ----------
473 A, B, C, D: str
474 Get Dihedralss between elements A, B, C and D. **B-C will be
475 the central axis**.
476 unique: bool
477 Return the dihedrals both ways or just one way
478 (A-B-C-D and D-C-B-A or only A-B-C-D)
480 Returns
481 -------
483 return: list of lists of tuples
484 return[imageIdx][atomIdx][dihedralI], each tuple starts
485 with atomIdx.
487 Use :func:`get_values` to convert the returned list to values.
488 """
489 r = []
490 for imI in range(len(self.all_dihedrals)):
491 r.append([])
492 # get indices of elements
493 aIdxs = self._get_symbol_idxs(imI, A)
494 bIdxs = self._get_symbol_idxs(imI, B)
495 cIdxs = self._get_symbol_idxs(imI, C)
496 dIdxs = self._get_symbol_idxs(imI, D)
497 for aIdx in aIdxs:
498 dihedrals = [
499 (aIdx,) + d
500 for d in self.all_dihedrals[imI][aIdx]
501 if (d[0] in bIdxs) and (d[1] in cIdxs) and (d[2] in dIdxs)
502 ]
503 if not unique:
504 dihedrals += [d[::-1] for d in dihedrals]
505 r[-1].extend(dihedrals)
507 return r
509 def get_bond_value(self, imIdx, idxs, mic=True, **kwargs):
510 """Get bond length.
512 Parameters
513 ----------
515 imIdx: int
516 Index of Image to get value from.
517 idxs: tuple or list of integers
518 Get distance between atoms idxs[0]-idxs[1].
519 mic: bool
520 Passed on to :func:`ase.Atoms.get_distance` for retrieving the
521 value, defaults to True.
522 If the cell of the image is correctly set, there should be no
523 reason to change this.
524 kwargs: options or dict
525 Passed on to :func:`ase.Atoms.get_distance`.
527 Returns
528 -------
530 return: float
531 Value returned by image.get_distance.
532 """
533 return self.images[imIdx].get_distance(
534 idxs[0], idxs[1], mic=mic, **kwargs
535 )
537 def get_angle_value(self, imIdx, idxs, mic=True, **kwargs):
538 """Get angle.
540 Parameters
541 ----------
543 imIdx: int
544 Index of Image to get value from.
545 idxs: tuple or list of integers
546 Get angle between atoms idxs[0]-idxs[1]-idxs[2].
547 mic: bool
548 Passed on to :func:`ase.Atoms.get_angle` for retrieving the value,
549 defaults to True.
550 If the cell of the image is correctly set, there should be no
551 reason to change this.
552 kwargs: options or dict
553 Passed on to :func:`ase.Atoms.get_angle`.
555 Returns
556 -------
558 return: float
559 Value returned by image.get_angle.
560 """
561 return self.images[imIdx].get_angle(
562 idxs[0], idxs[1], idxs[2], mic=True, **kwargs
563 )
565 def get_dihedral_value(self, imIdx, idxs, mic=True, **kwargs):
566 """Get dihedral.
568 Parameters
569 ----------
571 imIdx: int
572 Index of Image to get value from.
573 idxs: tuple or list of integers
574 Get angle between atoms idxs[0]-idxs[1]-idxs[2]-idxs[3].
575 mic: bool
576 Passed on to :func:`ase.Atoms.get_dihedral` for retrieving the
577 value, defaults to True.
578 If the cell of the image is correctly set, there should be no
579 reason to change this.
580 kwargs: options or dict
581 Passed on to :func:`ase.Atoms.get_dihedral`.
583 Returns
584 -------
586 return: float
587 Value returned by image.get_dihedral.
588 """
589 return self.images[imIdx].get_dihedral(
590 idxs[0], idxs[1], idxs[2], idxs[3], mic=mic, **kwargs
591 )
593 def get_values(self, inputList, imageIdx=None, mic=True, **kwargs):
594 """Get Bond/Angle/Dihedral values.
596 Parameters
597 ----------
599 inputList: list of lists of tuples
600 Can be any list provided by
601 :meth:`~ase.geometry.analysis.Analysis.get_bonds`,
602 :meth:`~ase.geometry.analysis.Analysis.get_angles` or
603 :meth:`~ase.geometry.analysis.Analysis.get_dihedrals`.
604 imageIdx: integer or slice
605 The images from :data:`images` to be analyzed. If None,
606 all frames will be analyzed.
607 See :func:`~ase.geometry.analysis.Analysis._get_slice` for details.
608 mic: bool
609 Passed on to :class:`~ase.Atoms` for retrieving the values,
610 defaults to True.
611 If the cells of the images are correctly set, there should be
612 no reason to change this.
613 kwargs: options or dict
614 Passed on to the :class:`~ase.Atoms` classes functions for
615 retrieving the values.
617 Returns
618 -------
620 return: list of lists of floats
621 return[imageIdx][valueIdx]. Has the same shape as the *inputList*,
622 instead of each
623 tuple there is a float with the value this tuple yields.
625 The type of value requested is determined from the length of the
626 tuple inputList[0][0].
627 The methods from the :class:`~ase.Atoms` class are used.
628 """
630 sl = self._get_slice(imageIdx)
632 # get method to call from length of inputList
633 if len(inputList[0][0]) == 2:
634 get = self.get_bond_value
635 elif len(inputList[0][0]) == 3:
636 get = self.get_angle_value
637 elif len(inputList[0][0]) == 4:
638 get = self.get_dihedral_value
639 else:
640 raise ValueError(
641 'inputList in ase.geometry.analysis.Analysis.get_values '
642 'has a bad shape.'
643 )
645 # check if length of slice and inputList match
646 singleNL = False
647 if len(inputList) != len(self.images[sl]):
648 # only one nl for all images
649 if len(inputList) == 1 and len(self.nl) == 1:
650 singleNL = True
651 else:
652 raise RuntimeError(
653 'Length of inputList does not match length of images '
654 'requested, but it also is not one item long.'
655 )
657 r = []
658 for inputIdx, image in enumerate(self.images[sl]):
659 imageIdx = self.images.index(image)
660 r.append([])
661 # always use first list from input if only a single
662 # neighborlist was used
663 if singleNL:
664 inputIdx = 0
665 for tupl in inputList[inputIdx]:
666 r[-1].append(get(imageIdx, tupl, mic=mic, **kwargs))
668 return r
670 def get_max_volume_estimate(self):
671 return get_max_volume_estimate(self.images)
673 @deprecated('Use `ase.geometry.rdf.get_rdf` instead.')
674 def get_rdf(
675 self,
676 rmax,
677 nbins,
678 imageIdx=None,
679 elements=None,
680 return_dists=False,
681 volume: float | None = None,
682 ):
683 """Get RDF.
685 Wrapper for :func:`ase.geometry.rdf.get_rdf` with more selection
686 possibilities.
688 .. deprecated:: 3.28.0
689 This method has bugs when ``elements`` is not ``None`` and will be
690 removed soon. Use :func:`ase.geometry.rdf.get_rdf` instead.
692 Parameters
693 ----------
695 rmax: float
696 Maximum distance of RDF.
697 nbins: int
698 Number of bins to divide RDF.
699 imageIdx: int/slice/None
700 Images to analyze, see :func:`_get_slice` for details.
701 elements: str/int/list/tuple
702 Make partial RDFs.
704 If elements is *None*, a full RDF is calculated. If elements
705 is an *integer* or a *list/tuple of integers*, only those
706 atoms will contribute to the RDF (like a mask). If elements is
707 a *string* or a *list/tuple of strings*, only Atoms of those
708 elements will contribute.
710 Returns
711 -------
713 return: list of lists / list of tuples of lists
714 If return_dists is True, the returned tuples
715 contain (rdf, distances). Otherwise
716 only rdfs for each image are returned.
718 """
720 if elements is not None:
721 raise RuntimeError(
722 'There are bugs for `elements` is not `None`. '
723 'Use `ase.geometry.rdf.get_rdf` instead.'
724 )
726 sl = self._get_slice(imageIdx)
728 ls_rdf = []
729 el = None
731 for image in self.images[sl]:
732 if elements is None:
733 tmp_image = image
734 # integers
735 elif isinstance(elements, int):
736 tmp_image = Atoms(cell=image.get_cell(), pbc=image.get_pbc())
737 tmp_image.append(image[elements])
738 # strings
739 elif isinstance(elements, str):
740 tmp_image = Atoms(cell=image.get_cell(), pbc=image.get_pbc())
741 for idx in self._get_symbol_idxs(image, elements):
742 tmp_image.append(image[idx])
743 # lists
744 elif isinstance(elements, (list, tuple)):
745 # list of ints
746 if all(isinstance(x, int) for x in elements):
747 if len(elements) == 2:
748 # use builtin get_rdf mask
749 el = elements
750 tmp_image = image
751 else:
752 # create dummy image
753 tmp_image = Atoms(
754 cell=image.get_cell(), pbc=image.get_pbc()
755 )
756 for idx in elements:
757 tmp_image.append(image[idx])
758 # list of strings
759 elif all(isinstance(x, str) for x in elements):
760 tmp_image = Atoms(
761 cell=image.get_cell(), pbc=image.get_pbc()
762 )
763 for element in elements:
764 for idx in self._get_symbol_idxs(image, element):
765 tmp_image.append(image[idx])
766 else:
767 raise ValueError(
768 'Unsupported type of elements given in '
769 'ase.geometry.analysis.Analysis.get_rdf!'
770 )
771 else:
772 raise ValueError(
773 'Unsupported type of elements given in '
774 'ase.geometry.analysis.Analysis.get_rdf!'
775 )
777 rdf = get_rdf(
778 tmp_image,
779 rmax,
780 nbins,
781 elements=el,
782 no_dists=(not return_dists),
783 volume=volume,
784 )
785 ls_rdf.append(rdf)
787 return ls_rdf