Coverage for ase/_4/optimize/_symopt/atommap.py: 100.00%

31 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-27 15:21 +0000

1import numpy as np 

2 

3from ase import Atoms 

4 

5 

6def build_one_atommap( 

7 atoms1: Atoms, 

8 atoms2: Atoms, 

9 maxerr: float = 1e-12, 

10 min_atomdist: float = 0.5, 

11) -> list[int]: 

12 from ase.geometry import find_mic 

13 

14 atommap_a = [] 

15 assert len(atoms1) == len(atoms2) 

16 

17 for a in range(len(atoms1)): 

18 _, distances = find_mic( 

19 atoms2.positions[a] - atoms1.positions, 

20 cell=atoms1.cell, 

21 pbc=atoms1.pbc, 

22 ) 

23 dist_indices = np.argsort(distances) 

24 atommap_a.append(dist_indices[0]) 

25 sorted_distances = distances[dist_indices] 

26 mindist = sorted_distances[0] 

27 assert mindist < maxerr, f'Symmetry-mapped position off by {mindist}' 

28 assert atoms1.symbols[dist_indices[0]] == atoms1.symbols[a] 

29 # assert atoms1.symbols[ 

30 if len(sorted_distances) > 1: 

31 # (This assertion may trigger if input structure is bad) 

32 assert sorted_distances[1] > min_atomdist, ( 

33 'atoms suspiciously close' 

34 ) 

35 

36 assert atoms2.symbols[a] == atoms1.symbols[dist_indices[0]] 

37 return atommap_a 

38 

39 

40def transform(scaled_positions, rotation, translation): 

41 # (Vectorize this for multiple ops some day) 

42 return scaled_positions @ rotation.T + translation[None, :] 

43 

44 

45def build_atommaps( 

46 atoms, 

47 rotations: np.ndarray, 

48 translations: np.ndarray, 

49 maxerr: float = 1e-12, 

50 min_atomdist: float = 0.5, 

51) -> np.ndarray: 

52 assert len(rotations) == len(translations) 

53 atommap_sa = [] 

54 

55 orig_spos = atoms.get_scaled_positions() % 1.0 % 1.0 

56 mapped_atoms = atoms.copy() 

57 

58 for rot, trans in zip(rotations, translations): 

59 newspos = transform(orig_spos, rot, trans) % 1.0 % 1.0 

60 mapped_atoms.positions[:] = atoms.cell.cartesian_positions(newspos) 

61 atommap = build_one_atommap(atoms, mapped_atoms, maxerr, min_atomdist) 

62 atommap_sa.append(atommap) 

63 return np.array(atommap_sa, int)