Coverage for ase/gui/images.py: 59.06%

298 statements  

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

1import warnings 

2from math import sqrt 

3 

4import numpy as np 

5 

6from ase import Atoms 

7from ase.calculators.singlepoint import SinglePointCalculator 

8from ase.constraints import FixAtoms 

9from ase.data import atomic_numbers, covalent_radii 

10from ase.geometry import find_mic 

11from ase.gui.defaults import read_defaults 

12from ase.gui.history import History 

13from ase.gui.i18n import _ 

14from ase.io import read, string2index, write 

15 

16 

17class Images: 

18 def __init__( 

19 self, images=None, *, config=None, notify_new_images=lambda: None 

20 ): 

21 self.covalent_radii = covalent_radii.copy() 

22 self.config = read_defaults(config) 

23 self.configure_radii(self.config.getliteral('covalent_radii')) 

24 self.atom_scale = self.config.getfloat('radii_scale') 

25 if images is None: 

26 images = [Atoms()] 

27 self.notify_new_images = notify_new_images 

28 self.initialize(images) 

29 self.history = History(self) 

30 

31 # Note: This is to notify if images are added or removed. 

32 # Not for smaller changes such as editing the images or 

33 # selection or something like that. 

34 

35 def __len__(self): 

36 return len(self._images) 

37 

38 def __getitem__(self, index): 

39 return self._images[index] 

40 

41 def __iter__(self): 

42 return iter(self._images) 

43 

44 def add_image(self, image): 

45 # This might be dangerous since initialize() is normally called when 

46 # list of images changes, and that one does a lot of things which we 

47 # don't do here. 

48 self.images._images.append(self.atoms.copy()) 

49 self.images.filenames.append(None) 

50 self.notify_new_images() 

51 

52 # XXXXXXX hack 

53 # compatibility hacks while allowing variable number of atoms 

54 def get_dynamic(self, atoms: Atoms) -> np.ndarray: 

55 dynamic = np.ones(len(atoms), bool) 

56 for constraint in atoms.constraints: 

57 if isinstance(constraint, FixAtoms): 

58 dynamic[constraint.index] = False 

59 return dynamic 

60 

61 def set_dynamic(self, mask, value): 

62 # Does not make much sense if different images have different 

63 # atom counts. Attempts to apply mask to all images, 

64 # to the extent possible. 

65 for atoms in self: 

66 dynamic = self.get_dynamic(atoms) 

67 dynamic[mask[: len(atoms)]] = value 

68 atoms.constraints = [ 

69 c for c in atoms.constraints if not isinstance(c, FixAtoms) 

70 ] 

71 atoms.constraints.append(FixAtoms(mask=~dynamic)) 

72 

73 def scale_radii(self, scaling_factor): 

74 self.covalent_radii *= scaling_factor 

75 

76 def configure_radii(self, radii): 

77 """Configure the GUI atom radii with a {atom: radius, ...} 

78 dictionary or a list/tuple eg. [(atom, radius), ...]""" 

79 if not radii: 

80 return 

81 if not isinstance(radii, dict): 

82 _radii = {entry[0]: entry[1] for entry in radii} 

83 else: 

84 _radii = radii 

85 for key, value in _radii.items(): 

86 if isinstance(key, str): 

87 key = atomic_numbers[key] 

88 self.covalent_radii[key] = value 

89 

90 def get_energy(self, atoms: Atoms) -> np.float64: 

91 try: 

92 return atoms.get_potential_energy() 

93 except RuntimeError: 

94 return np.nan # type: ignore[return-value] 

95 

96 def get_forces(self, atoms: Atoms): 

97 try: 

98 return atoms.get_forces(apply_constraint=False) 

99 except RuntimeError: 

100 return None 

101 

102 def initialize(self, images, filenames=None): 

103 nimages = len(images) 

104 if filenames is None: 

105 filenames = [None] * nimages 

106 self.filenames = filenames 

107 

108 warning = False 

109 

110 self._images = [] 

111 

112 # Whether length or chemical composition changes: 

113 self.have_varying_species = False 

114 for i, atoms in enumerate(images): 

115 # copy atoms or not? Not copying allows back-editing, 

116 # but copying actually forgets things like the attached 

117 # calculator (might have forces/energies 

118 self._images.append(atoms) 

119 self.have_varying_species |= not np.array_equal( 

120 self[0].numbers, atoms.numbers 

121 ) 

122 if (atoms.pbc != self[0].pbc).any(): 

123 warning = True 

124 

125 if warning: 

126 import warnings 

127 

128 warnings.warn('Not all images have the same boundary conditions!') 

129 

130 self.maxnatoms = max(len(atoms) for atoms in self) 

131 self.selected = np.zeros(self.maxnatoms, bool) 

132 self.selected_ordered = [] 

133 self.visible = np.ones(self.maxnatoms, bool) 

134 self.repeat = np.ones(3, int) 

135 self.notify_new_images() 

136 

137 def get_radii(self, atoms: Atoms) -> np.ndarray: 

138 radii = np.array([self.covalent_radii[z] for z in atoms.numbers]) 

139 radii *= self.atom_scale 

140 return radii 

141 

142 def read(self, filenames, default_index=':', filetype=None): 

143 if isinstance(default_index, str): 

144 default_index = string2index(default_index) 

145 

146 images = [] 

147 names = [] 

148 for filename in filenames: 

149 from ase.io.formats import parse_filename 

150 

151 if ( 

152 '@' in filename 

153 and 'postgres' not in filename 

154 or 'postgres' in filename 

155 and filename.count('@') == 2 

156 ): 

157 actual_filename, index = parse_filename(filename, None) 

158 else: 

159 actual_filename, index = parse_filename(filename, default_index) 

160 

161 # Read from stdin: 

162 if filename == '-': 

163 import sys 

164 from io import BytesIO 

165 

166 buf = BytesIO(sys.stdin.buffer.read()) 

167 buf.seek(0) 

168 filename = buf 

169 filetype = 'traj' 

170 

171 imgs = read(filename, index, filetype) 

172 if hasattr(imgs, 'iterimages'): 

173 imgs = list(imgs.iterimages()) 

174 

175 images.extend(imgs) 

176 

177 # Name each file as filename@index: 

178 if isinstance(index, slice): 

179 start = index.start or 0 

180 step = index.step or 1 

181 else: 

182 start = index 

183 step = 1 

184 for i, img in enumerate(imgs): 

185 if isinstance(start, int): 

186 names.append( 

187 '{}@{}'.format(actual_filename, start + i * step) 

188 ) 

189 else: 

190 names.append(f'{actual_filename}@{start}') 

191 

192 self.initialize(images, names) 

193 

194 def repeat_results(self, atoms: Atoms, repeat=None, oldprod=None): 

195 """Return a dictionary which updates the magmoms, energy and forces 

196 to the repeated amount of atoms. 

197 """ 

198 

199 def getresult(name, get_quantity): 

200 # ase/io/trajectory.py line 170 does this by using 

201 # the get_property(prop, atoms, allow_calculation=False) 

202 # so that is an alternative option. 

203 try: 

204 if not atoms.calc or atoms.calc.calculation_required( 

205 atoms, [name] 

206 ): 

207 quantity = None 

208 else: 

209 quantity = get_quantity() 

210 except Exception as err: 

211 quantity = None 

212 errmsg = ( 

213 'An error occurred while retrieving {} ' 

214 'from the calculator: {}'.format(name, err) 

215 ) 

216 warnings.warn(errmsg) 

217 return quantity 

218 

219 if repeat is None: 

220 repeat = self.repeat.prod() 

221 if oldprod is None: 

222 oldprod = self.repeat.prod() 

223 

224 results = {} 

225 

226 original_length = len(atoms) // oldprod 

227 newprod = repeat.prod() 

228 

229 # Read the old properties 

230 magmoms = getresult('magmoms', atoms.get_magnetic_moments) 

231 magmom = getresult('magmom', atoms.get_magnetic_moment) 

232 energy = getresult('energy', atoms.get_potential_energy) 

233 forces = getresult('forces', atoms.get_forces) 

234 

235 # Update old properties to the repeated image 

236 if magmoms is not None: 

237 magmoms = np.tile(magmoms[:original_length], newprod) 

238 results['magmoms'] = magmoms 

239 

240 if magmom is not None: 

241 magmom = magmom * newprod / oldprod 

242 results['magmom'] = magmom 

243 

244 if forces is not None: 

245 forces = np.tile(forces[:original_length].T, newprod).T 

246 results['forces'] = forces 

247 

248 if energy is not None: 

249 energy = energy * newprod / oldprod 

250 results['energy'] = energy 

251 

252 return results 

253 

254 def repeat_unit_cell(self): 

255 for atoms in self: 

256 # Get quantities taking into account current repeat():' 

257 results = self.repeat_results( 

258 atoms, self.repeat.prod(), oldprod=self.repeat.prod() 

259 ) 

260 

261 atoms.cell *= self.repeat.reshape((3, 1)) 

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

263 self.repeat = np.ones(3, int) 

264 

265 def repeat_images(self, repeat): 

266 from ase.constraints import FixAtoms 

267 

268 repeat = np.array(repeat) 

269 oldprod = self.repeat.prod() 

270 images = [] 

271 constraints_removed = False 

272 

273 for i, atoms in enumerate(self): 

274 refcell = atoms.get_cell() 

275 fa = [] 

276 for c in atoms._constraints: 

277 if isinstance(c, FixAtoms): 

278 fa.append(c) 

279 else: 

280 constraints_removed = True 

281 atoms.set_constraint(fa) 

282 

283 # Update results dictionary to repeated atoms 

284 results = self.repeat_results(atoms, repeat, oldprod) 

285 

286 del atoms[len(atoms) // oldprod :] # Original atoms 

287 

288 atoms *= repeat 

289 atoms.cell = refcell 

290 

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

292 

293 images.append(atoms) 

294 

295 if constraints_removed: 

296 from ase.gui.ui import showwarning, tk 

297 

298 # We must be able to show warning before the main GUI 

299 # has been created. So we create a new window, 

300 # then show the warning, then destroy the window. 

301 tmpwindow = tk.Tk() 

302 tmpwindow.withdraw() # Host window will never be shown 

303 showwarning( 

304 _('Constraints discarded'), 

305 _('Constraints other than FixAtoms have been discarded.'), 

306 ) 

307 tmpwindow.destroy() 

308 

309 self.initialize(images, filenames=self.filenames) 

310 self.repeat = repeat 

311 

312 def center(self): 

313 """Center each image in the existing unit cell, keeping the 

314 cell constant.""" 

315 for atoms in self: 

316 atoms.center() 

317 

318 def graph(self, expr: str) -> np.ndarray: 

319 """Routine to create the data in graphs, defined by the 

320 string expr.""" 

321 import ase.units as units 

322 

323 code = compile(expr + ',', '<input>', 'eval') 

324 

325 nimages = len(self) 

326 

327 def d(n1, n2): 

328 return sqrt(((R[n1] - R[n2]) ** 2).sum()) 

329 

330 def a(n1, n2, n3): 

331 v1 = R[n1] - R[n2] 

332 v2 = R[n3] - R[n2] 

333 arg = np.vdot(v1, v2) / (sqrt((v1**2).sum() * (v2**2).sum())) 

334 if arg > 1.0: 

335 arg = 1.0 

336 if arg < -1.0: 

337 arg = -1.0 

338 return 180.0 * np.arccos(arg) / np.pi 

339 

340 def dih(n1, n2, n3, n4): 

341 # vector 0->1, 1->2, 2->3 and their normalized cross products: 

342 a = R[n2] - R[n1] 

343 b = R[n3] - R[n2] 

344 c = R[n4] - R[n3] 

345 bxa = np.cross(b, a) 

346 bxa /= np.sqrt(np.vdot(bxa, bxa)) 

347 cxb = np.cross(c, b) 

348 cxb /= np.sqrt(np.vdot(cxb, cxb)) 

349 angle = np.vdot(bxa, cxb) 

350 # check for numerical trouble due to finite precision: 

351 if angle < -1: 

352 angle = -1 

353 if angle > 1: 

354 angle = 1 

355 angle = np.arccos(angle) 

356 if np.vdot(bxa, c) > 0: 

357 angle = 2 * np.pi - angle 

358 return angle * 180.0 / np.pi 

359 

360 # get number of mobile atoms for temperature calculation 

361 E = np.array([self.get_energy(atoms) for atoms in self]) 

362 

363 s = 0.0 

364 

365 # Namespace for eval: 

366 ns = {'E': E, 'd': d, 'a': a, 'dih': dih} 

367 

368 data = [] 

369 for i in range(nimages): 

370 ns['i'] = i 

371 ns['s'] = s 

372 ns['R'] = R = self[i].get_positions() 

373 ns['V'] = self[i].get_velocities() 

374 F = self.get_forces(self[i]) 

375 if F is not None: 

376 ns['F'] = F 

377 ns['A'] = self[i].get_cell() 

378 ns['M'] = self[i].get_masses() 

379 # XXX askhl verify: 

380 dynamic = self.get_dynamic(self[i]) 

381 if F is not None: 

382 ns['f'] = f = ((F * dynamic[:, None]) ** 2).sum(1) ** 0.5 

383 ns['fmax'] = max(f) 

384 ns['fave'] = f.mean() 

385 ns['epot'] = epot = E[i] 

386 ns['ekin'] = ekin = self[i].get_kinetic_energy() 

387 ns['e'] = epot + ekin 

388 ndynamic = dynamic.sum() 

389 if ndynamic > 0: 

390 ns['T'] = 2.0 * ekin / (3.0 * ndynamic * units.kB) 

391 data = eval(code, ns) 

392 if i == 0: 

393 nvariables = len(data) 

394 xy = np.empty((nvariables, nimages)) 

395 xy[:, i] = data 

396 if i + 1 < nimages and not self.have_varying_species: 

397 dR = find_mic( 

398 self[i + 1].positions - R, 

399 self[i].get_cell(), 

400 self[i].get_pbc(), 

401 )[0] 

402 s += sqrt((dR**2).sum()) 

403 return xy 

404 

405 def write(self, filename, rotations='', bbox=None, **kwargs): 

406 # XXX We should show the unit cell whenever there is one 

407 indices = range(len(self)) 

408 p = filename.rfind('@') 

409 if p != -1: 

410 try: 

411 slice = string2index(filename[p + 1 :]) 

412 except ValueError: 

413 pass 

414 else: 

415 indices = indices[slice] 

416 filename = filename[:p] 

417 if isinstance(indices, int): 

418 indices = [indices] 

419 

420 images = [self.get_atoms(i) for i in indices] 

421 if len(filename) > 4 and filename[-4:] in ['.eps', '.png', '.pov']: 

422 write(filename, images, rotation=rotations, bbox=bbox, **kwargs) 

423 else: 

424 write(filename, images, **kwargs) 

425 

426 def get_atoms(self, frame, remove_hidden=False): 

427 atoms = self[frame] 

428 try: 

429 E = atoms.get_potential_energy() 

430 except RuntimeError: 

431 E = None 

432 try: 

433 F = atoms.get_forces() 

434 except RuntimeError: 

435 F = None 

436 

437 # Remove hidden atoms if applicable 

438 if remove_hidden: 

439 atoms = atoms[self.visible] 

440 if F is not None: 

441 F = F[self.visible] 

442 atoms.calc = SinglePointCalculator(atoms, energy=E, forces=F) 

443 return atoms 

444 

445 def delete(self, i): 

446 self._images.pop(i) 

447 self.filenames.pop(i) 

448 self.initialize(self._images, self.filenames)