Coverage for ase/db/row.py: 90.95%

221 statements  

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

1import uuid 

2from typing import Any 

3 

4import numpy as np 

5 

6from ase import Atoms 

7from ase.calculators.calculator import ( 

8 PropertyNotImplementedError, 

9 all_properties, 

10 kptdensity2monkhorstpack, 

11) 

12from ase.calculators.singlepoint import SinglePointCalculator 

13from ase.data import atomic_masses, chemical_symbols 

14from ase.formula import Formula 

15from ase.geometry import cell_to_cellpar 

16from ase.io.jsonio import decode 

17 

18 

19class FancyDict(dict): 

20 """Dictionary with keys available as attributes also.""" 

21 

22 def __getattr__(self, key): 

23 if key not in self: 

24 return dict.__getattribute__(self, key) 

25 value = self[key] 

26 if isinstance(value, dict): 

27 return FancyDict(value) 

28 return value 

29 

30 def __dir__(self): 

31 return self.keys() # for tab-completion 

32 

33 

34def atoms2dict(atoms): 

35 dct = { 

36 'numbers': atoms.numbers, 

37 'positions': atoms.positions, 

38 'unique_id': uuid.uuid4().hex, 

39 } 

40 if atoms.pbc.any(): 

41 dct['pbc'] = atoms.pbc 

42 if atoms.cell.any(): 

43 dct['cell'] = atoms.cell 

44 if atoms.has('initial_magmoms'): 

45 dct['initial_magmoms'] = atoms.get_initial_magnetic_moments() 

46 if atoms.has('initial_charges'): 

47 dct['initial_charges'] = atoms.get_initial_charges() 

48 if atoms.has('masses'): 

49 dct['masses'] = atoms.get_masses() 

50 if atoms.has('tags'): 

51 dct['tags'] = atoms.get_tags() 

52 if atoms.has('momenta'): 

53 dct['momenta'] = atoms.get_momenta() 

54 if atoms.constraints: 

55 dct['constraints'] = [c.todict() for c in atoms.constraints] 

56 if atoms.calc is not None: 

57 dct['calculator'] = atoms.calc.name.lower() 

58 dct['calculator_parameters'] = atoms.calc.todict() 

59 if len(atoms.calc.check_state(atoms)) == 0: 

60 for prop in all_properties: 

61 try: 

62 x = atoms.calc.get_property(prop, atoms, False) 

63 except PropertyNotImplementedError: 

64 pass 

65 else: 

66 if x is not None: 

67 dct[prop] = x 

68 return dct 

69 

70 

71class AtomsRow: 

72 mtime: float 

73 positions: np.ndarray 

74 id: int 

75 

76 def __init__(self, dct): 

77 if isinstance(dct, dict): 

78 dct = dct.copy() 

79 if 'calculator_parameters' in dct: 

80 # Earlier version of ASE would encode the calculator 

81 # parameter dict again and again and again ... 

82 while isinstance(dct['calculator_parameters'], str): 

83 dct['calculator_parameters'] = decode( 

84 dct['calculator_parameters'] 

85 ) 

86 else: 

87 dct = atoms2dict(dct) 

88 assert 'numbers' in dct 

89 self._constraints = dct.pop('constraints', []) 

90 self._constrained_forces = None 

91 self._data = dct.pop('data', {}) 

92 kvp = dct.pop('key_value_pairs', {}) 

93 self._keys = list(kvp.keys()) 

94 self.__dict__.update(kvp) 

95 self.__dict__.update(dct) 

96 if 'cell' not in dct: 

97 self.cell = np.zeros((3, 3)) 

98 if 'pbc' not in dct: 

99 self.pbc = np.zeros(3, bool) 

100 

101 def __contains__(self, key): 

102 return key in self.__dict__ 

103 

104 def __iter__(self): 

105 return (key for key in self.__dict__ if key[0] != '_') 

106 

107 def get(self, key, default=None): 

108 """Return value of key if present or default if not.""" 

109 return getattr(self, key, default) 

110 

111 @property 

112 def key_value_pairs(self): 

113 """Return dict of key-value pairs.""" 

114 return {key: self.get(key) for key in self._keys} 

115 

116 def count_atoms(self): 

117 """Count atoms. 

118 

119 Return dict mapping chemical symbol strings to number of atoms. 

120 """ 

121 count = {} 

122 for symbol in self.symbols: 

123 count[symbol] = count.get(symbol, 0) + 1 

124 return count 

125 

126 def __getitem__(self, key): 

127 return getattr(self, key) 

128 

129 def __setitem__(self, key, value): 

130 setattr(self, key, value) 

131 

132 def __str__(self): 

133 return '<AtomsRow: formula={}, keys={}>'.format( 

134 self.formula, ','.join(self._keys) 

135 ) 

136 

137 @property 

138 def constraints(self): 

139 """List of constraints.""" 

140 from ase.constraints import dict2constraint 

141 

142 if not isinstance(self._constraints, list): 

143 # Lazy decoding: 

144 cs = decode(self._constraints) 

145 self._constraints = [] 

146 for c in cs: 

147 # Convert to new format: 

148 name = c.pop('__name__', None) 

149 if name: 

150 c = {'name': name, 'kwargs': c} 

151 if c['name'].startswith('ase'): 

152 c['name'] = c['name'].rsplit('.', 1)[1] 

153 self._constraints.append(c) 

154 return [dict2constraint(d) for d in self._constraints] 

155 

156 @property 

157 def data(self): 

158 """Data dict.""" 

159 if isinstance(self._data, str): 

160 self._data = decode(self._data) # lazy decoding 

161 elif isinstance(self._data, bytes): 

162 from ase.db.core import bytes_to_object 

163 

164 self._data = bytes_to_object(self._data) # lazy decoding 

165 return FancyDict(self._data) 

166 

167 @property 

168 def natoms(self): 

169 """Number of atoms.""" 

170 return len(self.numbers) 

171 

172 @property 

173 def formula(self): 

174 """Chemical formula string.""" 

175 return Formula('', _tree=[(self.symbols, 1)]).format('metal') 

176 

177 @property 

178 def symbols(self): 

179 """List of chemical symbols.""" 

180 return [chemical_symbols[Z] for Z in self.numbers] 

181 

182 @property 

183 def fmax(self): 

184 """Maximum atomic force.""" 

185 forces = self.constrained_forces 

186 return (forces**2).sum(1).max() ** 0.5 

187 

188 @property 

189 def constrained_forces(self): 

190 """Forces after applying constraints.""" 

191 if self._constrained_forces is not None: 

192 return self._constrained_forces 

193 forces = self.forces 

194 constraints = self.constraints 

195 if constraints: 

196 forces = forces.copy() 

197 atoms = self.toatoms() 

198 for constraint in constraints: 

199 constraint.adjust_forces(atoms, forces) 

200 

201 self._constrained_forces = forces 

202 return forces 

203 

204 @property 

205 def smax(self): 

206 """Maximum stress tensor component.""" 

207 return (self.stress**2).max() ** 0.5 

208 

209 @property 

210 def mass(self): 

211 """Total mass.""" 

212 if 'masses' in self: 

213 return self.masses.sum() 

214 return atomic_masses[self.numbers].sum() 

215 

216 @property 

217 def volume(self): 

218 """Volume of unit cell.""" 

219 if self.cell is None: 

220 return None 

221 vol = abs(np.linalg.det(self.cell)) 

222 if vol == 0.0: 

223 raise AttributeError 

224 return vol 

225 

226 @property 

227 def charge(self): 

228 """Total charge.""" 

229 charges = self.get('initial_charges') 

230 if charges is None: 

231 return 0.0 

232 return charges.sum() 

233 

234 def toatoms(self, add_additional_information=False): 

235 """Create Atoms object.""" 

236 atoms = Atoms( 

237 self.numbers, 

238 self.positions, 

239 cell=self.cell, 

240 pbc=self.pbc, 

241 magmoms=self.get('initial_magmoms'), 

242 charges=self.get('initial_charges'), 

243 tags=self.get('tags'), 

244 masses=self.get('masses'), 

245 momenta=self.get('momenta'), 

246 constraint=self.constraints, 

247 ) 

248 

249 results = {prop: self[prop] for prop in all_properties if prop in self} 

250 if results: 

251 atoms.calc = SinglePointCalculator(atoms, **results) 

252 atoms.calc.name = self.get('calculator', 'unknown') 

253 

254 if add_additional_information: 

255 atoms.info = {} 

256 atoms.info['unique_id'] = self.unique_id 

257 if self._keys: 

258 atoms.info['key_value_pairs'] = self.key_value_pairs 

259 data = self.get('data') 

260 if data: 

261 atoms.info['data'] = data 

262 

263 return atoms 

264 

265 

266def row2dct(row, key_descriptions) -> dict[str, Any]: 

267 """Convert row to dict of things for printing or a web-page.""" 

268 

269 from ase.db.core import float_to_time_string, now 

270 

271 dct = {} 

272 

273 atoms = Atoms(cell=row.cell, pbc=row.pbc) 

274 dct['size'] = kptdensity2monkhorstpack(atoms, kptdensity=1.8, even=False) 

275 

276 dct['cell'] = [[f'{a:.3f}' for a in axis] for axis in row.cell] 

277 par = [f'{x:.3f}' for x in cell_to_cellpar(row.cell)] 

278 dct['lengths'] = par[:3] 

279 dct['angles'] = par[3:] 

280 

281 stress = row.get('stress') 

282 if stress is not None: 

283 dct['stress'] = ', '.join(f'{s:.3f}' for s in stress) 

284 

285 dct['formula'] = Formula(row.formula).format('abc') 

286 

287 dipole = row.get('dipole') 

288 if dipole is not None: 

289 dct['dipole'] = ', '.join(f'{d:.3f}' for d in dipole) 

290 

291 data = row.get('data') 

292 if data: 

293 dct['data'] = ', '.join(data.keys()) 

294 

295 constraints = row.get('constraints') 

296 if constraints: 

297 dct['constraints'] = ', '.join( 

298 c.__class__.__name__ for c in constraints 

299 ) 

300 

301 keys = ( 

302 {'id', 'energy', 'fmax', 'smax', 'mass', 'age'} 

303 | set(key_descriptions) 

304 | set(row.key_value_pairs) 

305 ) 

306 dct['table'] = [] 

307 

308 from ase.db.project import KeyDescription 

309 

310 for key in keys: 

311 if key == 'age': 

312 age = float_to_time_string(now() - row.ctime, True) 

313 dct['table'].append(('ctime', 'Age', age)) 

314 continue 

315 value = row.get(key) 

316 if value is not None: 

317 if isinstance(value, float): 

318 value = f'{value:.3f}' 

319 elif not isinstance(value, str): 

320 value = str(value) 

321 

322 nokeydesc = KeyDescription(key, '', '', '') 

323 keydesc = key_descriptions.get(key, nokeydesc) 

324 unit = keydesc.unit 

325 if unit: 

326 value += ' ' + unit 

327 dct['table'].append((key, keydesc.longdesc, value)) 

328 

329 return dct