Coverage for ase/symbols.py: 96.08%

102 statements  

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

1import collections.abc 

2import numbers 

3import warnings 

4from collections.abc import Iterator, Sequence 

5 

6import numpy as np 

7 

8from ase.data import atomic_numbers, chemical_symbols 

9from ase.formula import Formula 

10 

11Integers = Sequence[int] | np.ndarray 

12 

13 

14def string2symbols(s: str) -> list[str]: 

15 """Convert string to list of chemical symbols.""" 

16 return list(Formula(s)) 

17 

18 

19def symbols2numbers(symbols) -> list[int]: 

20 if isinstance(symbols, str): 

21 symbols = string2symbols(symbols) 

22 numbers = [] 

23 for s in symbols: 

24 if isinstance(s, str): 

25 numbers.append(atomic_numbers[s]) 

26 else: 

27 numbers.append(int(s)) 

28 return numbers 

29 

30 

31class Symbols(collections.abc.Sequence): 

32 """A sequence of chemical symbols. 

33 

34 ``atoms.symbols`` is a :class:`ase.symbols.Symbols` object. This 

35 object works like an editable view of ``atoms.numbers``, except 

36 its elements are manipulated as strings. 

37 

38 Examples 

39 -------- 

40 

41 >>> from ase.build import molecule 

42 >>> atoms = molecule('CH3CH2OH') 

43 >>> atoms.symbols 

44 Symbols('C2OH6') 

45 >>> atoms.symbols[:3] 

46 Symbols('C2O') 

47 >>> atoms.symbols == 'H' # doctest: +ELLIPSIS 

48 array([False, False, False, True, True, True, True, True, True]...) 

49 >>> atoms.symbols[-3:] = 'Pu' 

50 >>> atoms.symbols 

51 Symbols('C2OH3Pu3') 

52 >>> atoms.symbols[3:6] = 'Mo2U' 

53 >>> atoms.symbols 

54 Symbols('C2OMo2UPu3') 

55 >>> atoms.symbols.formula 

56 Formula('C2OMo2UPu3') 

57 

58 The :class:`ase.formula.Formula` object is useful for extended 

59 formatting options and analysis. 

60 

61 """ 

62 

63 def __init__(self, numbers) -> None: 

64 self.numbers = np.asarray(numbers, int) 

65 

66 @classmethod 

67 def fromsymbols(cls, symbols) -> 'Symbols': 

68 numbers = symbols2numbers(symbols) 

69 return cls(np.array(numbers)) 

70 

71 @property 

72 def formula(self) -> Formula: 

73 """Formula object.""" 

74 string = Formula.from_list(self).format('reduce') 

75 return Formula(string) 

76 

77 def __getitem__(self, key) -> 'Symbols | str': 

78 num = self.numbers[key] 

79 if isinstance(num, numbers.Integral): 

80 return chemical_symbols[num] 

81 return Symbols(num) 

82 

83 def __iter__(self) -> Iterator[str]: 

84 for num in self.numbers: 

85 yield chemical_symbols[num] 

86 

87 def __setitem__(self, key, value) -> None: 

88 numbers = symbols2numbers(value) 

89 if len(numbers) == 1: 

90 self.numbers[key] = numbers[0] 

91 else: 

92 self.numbers[key] = numbers 

93 

94 def __len__(self) -> int: 

95 return len(self.numbers) 

96 

97 def __str__(self) -> str: 

98 return self.get_chemical_formula('reduce') 

99 

100 def __repr__(self) -> str: 

101 return f"Symbols('{self}')" 

102 

103 def __eq__(self, obj) -> bool: 

104 if not hasattr(obj, '__len__'): 

105 return False 

106 

107 try: 

108 symbols = Symbols.fromsymbols(obj) 

109 except Exception: 

110 # Typically this would happen if obj cannot be converged to 

111 # atomic numbers. 

112 return False 

113 return self.numbers == symbols.numbers 

114 

115 def get_chemical_formula( 

116 self, 

117 mode: str = 'hill', 

118 empirical: bool = False, 

119 ) -> str: 

120 """Get chemical formula. 

121 

122 See documentation of ase.atoms.Atoms.get_chemical_formula().""" 

123 # XXX Delegate the work to the Formula object! 

124 if mode in ('reduce', 'all') and empirical: 

125 warnings.warn( 

126 "Empirical chemical formula not available for mode '{}'".format( 

127 mode 

128 ) 

129 ) 

130 

131 if len(self) == 0: 

132 return '' 

133 

134 numbers = self.numbers 

135 

136 if mode == 'reduce': 

137 n = len(numbers) 

138 changes = np.concatenate( 

139 ([0], np.arange(1, n)[numbers[1:] != numbers[:-1]]) 

140 ) 

141 symbols = [chemical_symbols[e] for e in numbers[changes]] 

142 counts = np.append(changes[1:], n) - changes 

143 

144 tokens = [] 

145 for s, c in zip(symbols, counts): 

146 tokens.append(s) 

147 if c > 1: 

148 tokens.append(str(c)) 

149 formula = ''.join(tokens) 

150 elif mode == 'all': 

151 formula = ''.join([chemical_symbols[n] for n in numbers]) 

152 else: 

153 symbols = [chemical_symbols[Z] for Z in numbers] 

154 f = Formula('', _tree=[(symbols, 1)]) 

155 if empirical: 

156 f, _ = f.reduce() 

157 if mode in {'hill', 'metal'}: 

158 formula = f.format(mode) 

159 else: 

160 raise ValueError( 

161 "Use mode = 'all', 'reduce', 'hill' or 'metal'." 

162 ) 

163 

164 return formula 

165 

166 def search(self, symbols) -> Integers: 

167 """Return the indices of elements with given symbol or symbols.""" 

168 numbers = set(symbols2numbers(symbols)) 

169 indices = [ 

170 i for i, number in enumerate(self.numbers) if number in numbers 

171 ] 

172 return np.array(indices, int) 

173 

174 def species(self) -> set[str]: 

175 """Return unique symbols as a set.""" 

176 return set(self) 

177 

178 def indices(self) -> dict[str, Integers]: 

179 """Return dictionary mapping each unique symbol to indices. 

180 

181 >>> from ase.build import molecule 

182 >>> atoms = molecule('CH3CH2OH') 

183 >>> atoms.symbols.indices() 

184 {'C': array([0, 1]), 'O': array([2]), 'H': array([3, 4, 5, 6, 7, 8])} 

185 

186 """ 

187 dct: dict[str, list[int]] = {} 

188 for i, symbol in enumerate(self): 

189 dct.setdefault(symbol, []).append(i) 

190 return {key: np.array(value, int) for key, value in dct.items()} 

191 

192 def species_indices(self) -> Sequence[int]: 

193 """Return the indices of each atom within their individual species. 

194 

195 >>> from ase import Atoms 

196 >>> atoms = Atoms('CH3CH2OH') 

197 >>> atoms.symbols.species_indices() 

198 [0, 0, 1, 2, 1, 3, 4, 0, 5] 

199 

200 The indices correspond to the atoms as follows:: 

201 

202 [0, 0, 1, 2, 1, 3, 4, 0, 5] 

203 ^ ^ ^ ^ ^ ^ ^ ^ ^ 

204 C H H H C H H O H 

205 """ 

206 

207 counts: dict[str, int] = {} 

208 result = [] 

209 for i, n in enumerate(self.numbers): 

210 counts[n] = counts.get(n, -1) + 1 

211 result.append(counts[n]) 

212 

213 return result