Coverage for ase/atom.py: 95.24%

126 statements  

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

1"""This module defines the Atom object.""" 

2 

3import numpy as np 

4 

5from ase.data import atomic_masses, atomic_numbers, chemical_symbols 

6 

7# Singular, plural, default value: 

8names = { 

9 'position': ('positions', np.zeros(3)), 

10 'number': ('numbers', 0), 

11 'tag': ('tags', 0), 

12 'momentum': ('momenta', np.zeros(3)), 

13 'mass': ('masses', None), 

14 'magmom': ('initial_magmoms', 0.0), 

15 'charge': ('initial_charges', 0.0), 

16} 

17 

18 

19def atomproperty(name, doc): 

20 """Helper function to easily create Atom attribute property.""" 

21 

22 def getter(self): 

23 return self.get(name) 

24 

25 def setter(self, value): 

26 self.set(name, value) 

27 

28 def deleter(self): 

29 self.delete(name) 

30 

31 return property(getter, setter, deleter, doc) 

32 

33 

34def abcproperty(index): 

35 """Helper function to easily create Atom ABC-property.""" 

36 

37 def getter(self): 

38 return self.scaled_position[index] 

39 

40 def setter(self, value): 

41 # We can't just do self.scaled_position[i] = value 

42 # because scaled_position is a new buffer, not a view into 

43 # something we can write back to. 

44 # This is a clear bug! 

45 spos = self.scaled_position 

46 spos[index] = value 

47 self.scaled_position = spos 

48 

49 return property(getter, setter, doc='ABC'[index] + '-coordinate') 

50 

51 

52def xyzproperty(index): 

53 """Helper function to easily create Atom XYZ-property.""" 

54 

55 def getter(self): 

56 return self.position[index] 

57 

58 def setter(self, value): 

59 self.position[index] = value 

60 

61 return property(getter, setter, doc='XYZ'[index] + '-coordinate') 

62 

63 

64class Atom: 

65 """Class for representing a single atom. 

66 

67 Parameters 

68 ---------- 

69 

70 symbol: str or int 

71 Can be a chemical symbol (str) or an atomic number (int). 

72 position: sequence of 3 floats 

73 Atomic position. 

74 tag: int 

75 Special purpose tag. 

76 momentum: sequence of 3 floats 

77 Momentum for atom. 

78 mass: float 

79 Atomic mass in atomic units. 

80 magmom: float or 3 floats 

81 Magnetic moment. 

82 charge: float 

83 Atomic charge. 

84 

85 Examples 

86 -------- 

87 The first argument to the constructor of an Atom object is the 

88 chemical symbol, and the second argument is the position in Å units 

89 (see :class:`~ase.units`). 

90 The position can be any numerical sequence of length three. 

91 The properties of an atom can also be set using keywords like 

92 it is done in the a, b, and c examples below. 

93 

94 >>> from ase import Atom 

95 >>> a = Atom('O', charge=-2) 

96 >>> b = Atom(8, charge=-2) 

97 >>> c = Atom('H', (1, 2, 3), magmom=1) 

98 >>> print(a.charge, a.position) 

99 -2 [0. 0. 0.] 

100 >>> c.x = 0.0 

101 >>> c.position 

102 array([0., 2., 3.]) 

103 >>> b.symbol 

104 'O' 

105 >>> c.tag = 42 

106 >>> c.number 

107 1 

108 >>> c.symbol = 'Li' 

109 >>> c.number 

110 3 

111 

112 If the atom object belongs to an Atoms object, then assigning 

113 values to the atom attributes will change the corresponding 

114 arrays of the atoms object: 

115 

116 >>> from ase import Atoms 

117 >>> OH = Atoms('OH') 

118 >>> OH[0].charge = -1 

119 >>> OH.get_initial_charges() 

120 array([-1., 0.]) 

121 

122 Another example: 

123 

124 >>> from ase.build import bulk 

125 >>> bulk = bulk('Ni', 'fcc', a=3.5) 

126 >>> for atom in bulk: 

127 ... if atom.symbol == 'Ni': 

128 ... atom.magmom = 0.7 # set initial magnetic moment 

129 

130 The different properties of an atom can be obtained and changed via 

131 attributes (``position``, ``number``, ``tag``, ``momentum``, ``mass``, 

132 ``magmom``, ``charge``, ``x``, ``y``, ``z``): 

133 

134 >>> from ase import Atom 

135 >>> a.position = [1, 0, 0] 

136 >>> a.position 

137 [1, 0, 0] 

138 >>> a.z = 2.5 

139 >>> a.position 

140 [1, 0, 2.5] 

141 >>> a.magmom = 1.0 

142 >>> bulk[0].magmom = 2.0 

143 

144 That last line will set the initial magnetic moment that some 

145 calculators use (similar to the 

146 :meth:`~ase.Atoms.set_initial_magnetic_moments` method). 

147 

148 

149 .. note:: 

150 

151 The ``position`` and ``momentum`` attributes refer to mutable 

152 objects, so in some cases, you may want to use 

153 ``a.position.copy()`` in order to avoid changing the position of 

154 ``a`` by accident. 

155 

156 """ 

157 

158 __slots__ = ['data', 'atoms', 'index'] 

159 

160 def __init__( 

161 self, 

162 symbol='X', 

163 position=(0, 0, 0), 

164 tag=None, 

165 momentum=None, 

166 mass=None, 

167 magmom=None, 

168 charge=None, 

169 atoms=None, 

170 index=None, 

171 ): 

172 self.data = d = {} 

173 

174 if atoms is None: 

175 # This atom is not part of any Atoms object: 

176 if isinstance(symbol, str): 

177 d['number'] = atomic_numbers[symbol] 

178 else: 

179 d['number'] = symbol 

180 d['position'] = np.array(position, float) 

181 d['tag'] = tag 

182 if momentum is not None: 

183 momentum = np.array(momentum, float) 

184 d['momentum'] = momentum 

185 d['mass'] = mass 

186 if magmom is not None: 

187 magmom = np.array(magmom, float) 

188 d['magmom'] = magmom 

189 d['charge'] = charge 

190 

191 self.index = index 

192 self.atoms = atoms 

193 

194 @property 

195 def scaled_position(self): 

196 pos = self.position 

197 spos = self.atoms.cell.scaled_positions(pos[np.newaxis]) 

198 return spos[0] 

199 

200 @scaled_position.setter 

201 def scaled_position(self, value): 

202 pos = self.atoms.cell.cartesian_positions(value) 

203 self.position = pos 

204 

205 def __repr__(self): 

206 s = f"Atom('{self.symbol}', {list(self.position)}" 

207 for name in ['tag', 'momentum', 'mass', 'magmom', 'charge']: 

208 value = self.get_raw(name) 

209 if value is not None: 

210 if isinstance(value, np.ndarray): 

211 value = value.tolist() 

212 s += f', {name}={value}' 

213 if self.atoms is None: 

214 s += ')' 

215 else: 

216 s += ', index=%d)' % self.index 

217 return s 

218 

219 def cut_reference_to_atoms(self): 

220 """Cut reference to atoms object.""" 

221 for name in names: 

222 self.data[name] = self.get_raw(name) 

223 self.index = None 

224 self.atoms = None 

225 

226 def get_raw(self, name): 

227 """Get name attribute, return None if not explicitly set.""" 

228 if name == 'symbol': 

229 return chemical_symbols[self.get_raw('number')] 

230 

231 if self.atoms is None: 

232 return self.data[name] 

233 

234 plural = names[name][0] 

235 if plural in self.atoms.arrays: 

236 return self.atoms.arrays[plural][self.index] 

237 else: 

238 return None 

239 

240 def get(self, name): 

241 """Get name attribute, return default if not explicitly set.""" 

242 

243 value = self.get_raw(name) 

244 if value is None: 

245 if name == 'mass': 

246 value = atomic_masses[self.number] 

247 else: 

248 value = names[name][1] 

249 return value 

250 

251 def set(self, name, value): 

252 """Set name attribute to value.""" 

253 if name == 'symbol': 

254 name = 'number' 

255 value = atomic_numbers[value] 

256 

257 if self.atoms is None: 

258 assert name in names 

259 self.data[name] = value 

260 else: 

261 plural, default = names[name] 

262 if plural in self.atoms.arrays: 

263 array = self.atoms.arrays[plural] 

264 if name == 'magmom' and array.ndim == 2: 

265 assert len(value) == 3 

266 array[self.index] = value 

267 else: 

268 if name == 'magmom' and np.asarray(value).ndim == 1: 

269 array = np.zeros((len(self.atoms), 3)) 

270 elif name == 'mass': 

271 array = self.atoms.get_masses() 

272 else: 

273 default = np.asarray(default) 

274 array = np.zeros( 

275 (len(self.atoms),) + default.shape, default.dtype 

276 ) 

277 array[self.index] = value 

278 self.atoms.new_array(plural, array) 

279 

280 def delete(self, name): 

281 """Delete name attribute.""" 

282 assert self.atoms is None 

283 assert name not in ['number', 'symbol', 'position'] 

284 self.data[name] = None 

285 

286 symbol = atomproperty('symbol', 'Chemical symbol') 

287 number = atomproperty('number', 'Atomic number') 

288 position = atomproperty('position', 'XYZ-coordinates') 

289 tag = atomproperty('tag', 'Integer tag') 

290 momentum = atomproperty('momentum', 'XYZ-momentum') 

291 mass = atomproperty('mass', 'Atomic mass') 

292 magmom = atomproperty('magmom', 'Initial magnetic moment') 

293 charge = atomproperty('charge', 'Initial atomic charge') 

294 x = xyzproperty(0) 

295 y = xyzproperty(1) 

296 z = xyzproperty(2) 

297 

298 a = abcproperty(0) 

299 b = abcproperty(1) 

300 c = abcproperty(2)