Coverage for ase/gui/view.py: 82.02%

595 statements  

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

1from math import cos, sin, sqrt 

2from os.path import basename 

3 

4import numpy as np 

5 

6from ase.calculators.calculator import PropertyNotImplementedError 

7from ase.data import atomic_numbers 

8from ase.data.colors import jmol_colors 

9from ase.geometry import complete_cell 

10from ase.gui.colors import ColorWindow 

11from ase.gui.i18n import _, ngettext 

12from ase.gui.render import Render 

13from ase.gui.repeat import Repeat 

14from ase.gui.rotate import Rotate 

15from ase.gui.utils import get_magmoms 

16from ase.utils import rotate 

17 

18GREEN = '#74DF00' 

19PURPLE = '#AC58FA' 

20BLACKISH = '#151515' 

21 

22 

23def get_cell_coordinates(cell, shifted=False): 

24 """Get start and end points of lines segments used to draw cell.""" 

25 nn = [] 

26 for c in range(3): 

27 v = cell[c] 

28 d = sqrt(np.dot(v, v)) 

29 if d < 1e-12: 

30 n = 0 

31 else: 

32 n = max(2, int(d / 0.3)) 

33 nn.append(n) 

34 B1 = np.zeros((2, 2, sum(nn), 3)) 

35 B2 = np.zeros((2, 2, sum(nn), 3)) 

36 n1 = 0 

37 for c, n in enumerate(nn): 

38 n2 = n1 + n 

39 h = 1.0 / (2 * n - 1) 

40 R = np.arange(n) * (2 * h) 

41 

42 for i, j in [(0, 0), (0, 1), (1, 0), (1, 1)]: 

43 B1[i, j, n1:n2, c] = R 

44 B1[i, j, n1:n2, (c + 1) % 3] = i 

45 B1[i, j, n1:n2, (c + 2) % 3] = j 

46 B2[:, :, n1:n2] = B1[:, :, n1:n2] 

47 B2[:, :, n1:n2, c] += h 

48 n1 = n2 

49 B1 = B1.reshape((-1, 3)) 

50 B2 = B2.reshape((-1, 3)) 

51 if shifted: 

52 B1 -= 0.5 

53 B2 -= 0.5 

54 return B1, B2 

55 

56 

57def get_bonds(atoms, covalent_radii): 

58 from ase.neighborlist import PrimitiveNeighborList 

59 

60 nl = PrimitiveNeighborList( 

61 covalent_radii * 1.5, 

62 skin=0.0, 

63 self_interaction=False, 

64 bothways=False, 

65 ) 

66 nl.update(atoms.pbc, atoms.get_cell(complete=True), atoms.positions) 

67 number_of_neighbors = sum(indices.size for indices in nl.neighbors) 

68 number_of_pbc_neighbors = sum( 

69 offsets.any(axis=1).sum() for offsets in nl.displacements 

70 ) # sum up all neighbors that have non-zero supercell offsets 

71 nbonds = number_of_neighbors + number_of_pbc_neighbors 

72 

73 bonds = np.empty((nbonds, 5), int) 

74 if nbonds == 0: 

75 return bonds 

76 

77 n1 = 0 

78 for a in range(len(atoms)): 

79 indices, offsets = nl.get_neighbors(a) 

80 n2 = n1 + len(indices) 

81 bonds[n1:n2, 0] = a 

82 bonds[n1:n2, 1] = indices 

83 bonds[n1:n2, 2:] = offsets 

84 n1 = n2 

85 

86 i = bonds[:n2, 2:].any(1) 

87 pbcbonds = bonds[:n2][i] 

88 bonds[n2:, 0] = pbcbonds[:, 1] 

89 bonds[n2:, 1] = pbcbonds[:, 0] 

90 bonds[n2:, 2:] = -pbcbonds[:, 2:] 

91 return bonds 

92 

93 

94class View: 

95 def __init__(self, rotations): 

96 self.colormode = 'jmol' # The default colors 

97 self.axes = rotate(rotations) 

98 self.configured = False 

99 self.frame = None 

100 

101 # XXX 

102 self.colormode = 'jmol' 

103 self.colors = { 

104 i: ('#{:02X}{:02X}{:02X}'.format(*(int(x * 255) for x in rgb))) 

105 for i, rgb in enumerate(jmol_colors) 

106 } 

107 # scaling factors for vectors 

108 self.force_vector_scale = self.config.getfloat('force_vector_scale') 

109 self.velocity_vector_scale = self.config.getfloat( 

110 'velocity_vector_scale' 

111 ) 

112 self.magmom_vector_scale = self.config.getfloat('magmom_vector_scale') 

113 

114 # Performance options, see _draw_indices(). "Level of detail" is 

115 # the usual computer-graphics term for drawing a cheaper version of 

116 # the scene when full detail would be too slow: here, while the user 

117 # is dragging/zooming (self.interactive is True). _settle_timer 

118 # restores full detail once interaction stops. 

119 self.interactive_level_of_detail = self.config.get( 

120 'interactive_level_of_detail', True 

121 ) 

122 self.occlusion_culling = self.config.get('occlusion_culling', True) 

123 self.interactive = False 

124 self._settle_timer = None 

125 self.bonds = np.empty((0, 5), int) 

126 

127 # buttons 

128 self.b1 = 1 # left 

129 self.b3 = 3 # right 

130 if self.config.getboolean('swap_mouse'): 

131 self.b1 = 3 

132 self.b3 = 1 

133 

134 self.t0 = 0 

135 

136 @property 

137 def atoms(self): 

138 return self.images[self.frame] 

139 

140 def set_frame(self, frame=None, focus=False): 

141 if frame is None: 

142 frame = self.frame 

143 assert frame < len(self.images) 

144 self.frame = frame 

145 self.set_atoms(self.images[frame]) 

146 

147 fname = self.images.filenames[frame] 

148 if fname is None: 

149 header = 'ase.gui' 

150 else: 

151 # fname is actually not necessarily the filename but may 

152 # contain indexing like filename@0 

153 header = basename(fname) 

154 

155 images_loaded_text = ngettext( 

156 'one image loaded', '{} images loaded', len(self.images) 

157 ).format(len(self.images)) 

158 

159 self.window.title = f'{header} — {images_loaded_text}' 

160 

161 if self.movie_window is not None: 

162 self.movie_window.frame_number.value = frame 

163 

164 if focus: 

165 self.focus() 

166 else: 

167 self.draw() 

168 

169 def get_bonds(self, atoms): 

170 # this method exists rather than just using the standalone function 

171 # so that it can be overridden by external libraries 

172 return get_bonds(atoms, self.get_covalent_radii(atoms)) 

173 

174 def set_atoms(self, atoms): 

175 natoms = len(atoms) 

176 

177 if self.showing_cell(): 

178 B1, B2 = get_cell_coordinates( 

179 atoms.cell, self.config.getboolean('shift_cell') 

180 ) 

181 else: 

182 B1 = B2 = np.zeros((0, 3)) 

183 

184 if self.showing_bonds(): 

185 atomscopy = atoms.copy() 

186 atomscopy.cell *= self.images.repeat[:, np.newaxis] 

187 bonds = self.get_bonds(atomscopy) 

188 else: 

189 bonds = np.empty((0, 5), int) 

190 

191 # Columns 0 and 1 are the atom indices each bond connects. Keep 

192 # them so draw() can tell which bonds belong to culled atoms; the 

193 # shortened endpoints in X_bonds/B no longer carry that information. 

194 self.bonds = bonds 

195 

196 # X is all atomic coordinates, and starting points of vectors 

197 # like bonds and cell segments. 

198 # The reason to have them all in one big list is that we like to 

199 # eventually rotate/sort it by Z-order when rendering. 

200 

201 # Also B are the end points of line segments. 

202 

203 self.X = np.empty((natoms + len(B1) + len(bonds), 3)) 

204 self.X_pos = self.X[:natoms] 

205 self.X_pos[:] = atoms.positions 

206 self.X_cell = self.X[natoms : natoms + len(B1)] 

207 self.X_bonds = self.X[natoms + len(B1) :] 

208 

209 cell = atoms.cell 

210 ncellparts = len(B1) 

211 nbonds = len(bonds) 

212 

213 self.X_cell[:] = np.dot(B1, cell) 

214 self.B = np.empty((ncellparts + nbonds, 3)) 

215 self.B[:ncellparts] = np.dot(B2, cell) 

216 

217 if nbonds > 0: 

218 P = atoms.positions 

219 Af = self.images.repeat[:, np.newaxis] * cell 

220 a = P[bonds[:, 0]] 

221 b = P[bonds[:, 1]] + np.dot(bonds[:, 2:], Af) - a 

222 d = (b**2).sum(1) ** 0.5 

223 r = 0.65 * self.get_covalent_radii() 

224 x0 = (r[bonds[:, 0]] / d).reshape((-1, 1)) 

225 x1 = (r[bonds[:, 1]] / d).reshape((-1, 1)) 

226 self.X_bonds[:] = a + b * x0 

227 b *= 1.0 - x0 - x1 

228 b[bonds[:, 2:].any(1)] *= 0.5 

229 self.B[ncellparts:] = self.X_bonds + b 

230 

231 self.obs.set_atoms.notify() 

232 

233 def showing_bonds(self): 

234 return self.window['toggle-show-bonds'] 

235 

236 def showing_cell(self): 

237 return self.window['toggle-show-unit-cell'] 

238 

239 def toggle_show_unit_cell(self, key=None): 

240 self.set_frame() 

241 

242 def get_labels(self): 

243 index = self.window['show-labels'] 

244 if index == 0: 

245 return None 

246 

247 if index == 1: 

248 return list(range(len(self.atoms))) 

249 

250 if index == 2: 

251 return list(get_magmoms(self.atoms)) 

252 

253 if index == 4: 

254 Q = self.atoms.get_initial_charges() 

255 return [f'{q:.4g}' for q in Q] 

256 

257 return self.atoms.symbols 

258 

259 def show_labels(self): 

260 self.draw() 

261 

262 def toggle_show_axes(self, key=None): 

263 self.draw() 

264 

265 def toggle_show_bonds(self, key=None): 

266 self.set_frame() 

267 

268 def toggle_show_velocities(self, key=None): 

269 self.draw() 

270 

271 def get_forces(self): 

272 if self.atoms.calc is not None: 

273 try: 

274 return self.atoms.get_forces() 

275 except PropertyNotImplementedError: 

276 pass 

277 return np.zeros((len(self.atoms), 3)) 

278 

279 def toggle_show_forces(self, key=None): 

280 self.draw() 

281 

282 def toggle_show_magmoms(self, key=None): 

283 self.draw() 

284 

285 def hide_selected(self): 

286 self.images.visible[self.images.selected] = False 

287 self.draw() 

288 

289 def show_selected(self): 

290 self.images.visible[self.images.selected] = True 

291 self.draw() 

292 

293 def repeat_window(self, key=None): 

294 return Repeat(self) 

295 

296 def rotate_window(self): 

297 return Rotate(self) 

298 

299 def colors_window(self, key=None): 

300 win = ColorWindow(self) 

301 self.obs.new_atoms.register(win.notify_atoms_changed) 

302 return win 

303 

304 def focus(self, x=None): 

305 cell = ( 

306 self.window['toggle-show-unit-cell'] and self.images[0].cell.any() 

307 ) 

308 if len(self.atoms) == 0 and not cell: 

309 self.scale = 20.0 

310 self.center = np.zeros(3) 

311 self.draw() 

312 return 

313 

314 # Get the min and max point of the projected atom positions 

315 # including the covalent_radii used for drawing the atoms 

316 P = np.dot(self.X, self.axes) 

317 n = len(self.atoms) 

318 covalent_radii = self.get_covalent_radii() 

319 P[:n] -= covalent_radii[:, None] 

320 P1 = P.min(0) 

321 P[:n] += 2 * covalent_radii[:, None] 

322 P2 = P.max(0) 

323 self.center = np.dot(self.axes, (P1 + P2) / 2) 

324 self.center += self.atoms.get_celldisp().reshape((3,)) / 2 

325 # Add 30% of whitespace on each side of the atoms 

326 S = 1.3 * (P2 - P1) 

327 w, h = self.window.size 

328 if S[0] * h < S[1] * w: 

329 self.scale = h / S[1] 

330 elif S[0] > 0.0001: 

331 self.scale = w / S[0] 

332 else: 

333 self.scale = 1.0 

334 self.draw() 

335 

336 def reset_view(self, menuitem): 

337 self.axes = rotate('0.0x,0.0y,0.0z') 

338 self.set_frame() 

339 self.focus(self) 

340 

341 def set_view(self, key): 

342 if key == 'Z': 

343 self.axes = rotate('0.0x,0.0y,0.0z') 

344 elif key == 'X': 

345 self.axes = rotate('-90.0x,-90.0y,0.0z') 

346 elif key == 'Y': 

347 self.axes = rotate('90.0x,0.0y,90.0z') 

348 elif key == 'Shift+Z': 

349 self.axes = rotate('180.0x,0.0y,90.0z') 

350 elif key == 'Shift+X': 

351 self.axes = rotate('0.0x,90.0y,0.0z') 

352 elif key == 'Shift+Y': 

353 self.axes = rotate('-90.0x,0.0y,0.0z') 

354 else: 

355 if key == 'I': 

356 i, j = 1, 2 

357 elif key == 'J': 

358 i, j = 2, 0 

359 elif key == 'K': 

360 i, j = 0, 1 

361 elif key == 'Shift+I': 

362 i, j = 2, 1 

363 elif key == 'Shift+J': 

364 i, j = 0, 2 

365 elif key == 'Shift+K': 

366 i, j = 1, 0 

367 

368 A = complete_cell(self.atoms.cell) 

369 x1 = A[i] 

370 x2 = A[j] 

371 

372 norm = np.linalg.norm 

373 

374 x1 = x1 / norm(x1) 

375 x2 = x2 - x1 * np.dot(x1, x2) 

376 x2 /= norm(x2) 

377 x3 = np.cross(x1, x2) 

378 

379 self.axes = np.array([x1, x2, x3]).T 

380 

381 self.set_frame() 

382 

383 def get_colors(self, rgb=False): 

384 if rgb: 

385 return [ 

386 tuple(int(_rgb[i : i + 2], 16) / 255 for i in range(1, 7, 2)) 

387 for _rgb in self.get_colors() 

388 ] 

389 

390 if self.colormode == 'jmol': 

391 return [self.colors.get(Z, BLACKISH) for Z in self.atoms.numbers] 

392 

393 if self.colormode == 'neighbors': 

394 return [ 

395 self.colors.get(Z, BLACKISH) for Z in self.get_color_scalars() 

396 ] 

397 

398 colorscale, cmin, cmax = self.colormode_data 

399 N = len(colorscale) 

400 colorswhite = colorscale + ['#ffffff'] 

401 if cmin == cmax: 

402 indices = [N // 2] * len(self.atoms) 

403 else: 

404 scalars = np.ma.array(self.get_color_scalars()) 

405 indices = np.clip( 

406 ((scalars - cmin) / (cmax - cmin) * N + 0.5).astype(int), 

407 0, 

408 N - 1, 

409 ).filled(N) 

410 return [colorswhite[i] for i in indices] 

411 

412 def get_color_scalars(self, frame=None): 

413 if self.colormode == 'tag': 

414 return self.atoms.get_tags() 

415 if self.colormode == 'force': 

416 f = (self.get_forces() ** 2).sum(1) ** 0.5 

417 return f * self.images.get_dynamic(self.atoms) 

418 elif self.colormode == 'velocity': 

419 return (self.atoms.get_velocities() ** 2).sum(1) ** 0.5 

420 elif self.colormode == 'initial charge': 

421 return self.atoms.get_initial_charges() 

422 elif self.colormode == 'magmom': 

423 return get_magmoms(self.atoms) 

424 elif self.colormode == 'neighbors': 

425 from ase.neighborlist import NeighborList 

426 

427 n = len(self.atoms) 

428 nl = NeighborList( 

429 self.get_covalent_radii(self.atoms) * 1.5, 

430 skin=0, 

431 self_interaction=False, 

432 bothways=True, 

433 ) 

434 nl.update(self.atoms) 

435 return [len(nl.get_neighbors(i)[0]) for i in range(n)] 

436 else: 

437 scalars = np.array( 

438 self.atoms.get_array(self.colormode), dtype=float 

439 ) 

440 return np.ma.array(scalars, mask=np.isnan(scalars)) 

441 

442 def get_covalent_radii(self, atoms=None): 

443 if atoms is None: 

444 atoms = self.atoms 

445 return self.images.get_radii(atoms) 

446 

447 # Redraw cost is close to linear in the number of drawable objects, at 

448 # roughly 5 µs each. Below ~10000 objects a frame still takes under 

449 # ~50 ms, which is smooth enough that dropping detail would only be 

450 # visible as bonds flickering on and off for no gain. 

451 LEVEL_OF_DETAIL_MIN_OBJECTS = 10000 

452 

453 def begin_interaction(self): 

454 """Enter reduced-detail mode and arm the full-quality redraw. 

455 

456 Dragging emits far more motion events than we can draw frames, and 

457 zooming has no release event at all, so detail is restored by a 

458 timer once interaction stops. Re-arming cancels the pending timer, 

459 so during a continuous drag it only fires after the user lets go. 

460 """ 

461 self.interactive = True 

462 if self._settle_timer is not None: 

463 self._settle_timer.cancel() 

464 self._settle_timer = self.window.after(0.15, self.end_interaction) 

465 

466 def end_interaction(self): 

467 """Leave reduced-detail mode and redraw at full quality.""" 

468 if self._settle_timer is not None: 

469 self._settle_timer.cancel() 

470 self._settle_timer = None 

471 if self.interactive: 

472 self.interactive = False 

473 self.draw() 

474 

475 def _reducing_detail(self): 

476 return ( 

477 self.interactive 

478 and self.interactive_level_of_detail 

479 and len(self.X) > self.LEVEL_OF_DETAIL_MIN_OBJECTS 

480 ) 

481 

482 def _visible_atoms(self, P, z, r, keep=3): 

483 """Indices of atoms that are not hidden behind nearer atoms. 

484 

485 Screen space is bucketed into cells roughly one atom across, and 

486 only the ``keep`` frontmost atoms of each cell are kept. Atoms 

487 behind those are covered by opaque circles and cannot contribute a 

488 pixel. ``keep=3`` was chosen by pixel-diffing culled against 

489 unculled renders over bulk, slab, nanoparticle and molecule 

490 geometries at several orientations: the worst case differed in 

491 0.06% of non-background pixels, while keep=1 reached 4%. 

492 

493 Sparse structures put at most a few atoms in any cell, so small 

494 molecules keep every atom and are unaffected. 

495 

496 The single cell size assumes all atoms are drawn at roughly the 

497 same screen radius. That holds under orthographic projection, 

498 where radius depends only on the element; callers must not use 

499 this where it does not. See _draw_indices(). 

500 """ 

501 natoms = len(P) 

502 if natoms == 0: 

503 return np.empty(0, int) 

504 c = max(int(r.mean()), 1) 

505 ix = np.floor(P[:, 0] / c).astype(np.int64) 

506 iy = np.floor(P[:, 1] / c).astype(np.int64) 

507 # Group by cell, and within a cell sort front-most first. 

508 order = np.lexsort((-z, iy, ix)) 

509 ix = ix[order] 

510 iy = iy[order] 

511 first = np.empty(natoms, bool) 

512 first[0] = True 

513 first[1:] = (ix[1:] != ix[:-1]) | (iy[1:] != iy[:-1]) 

514 arange = np.arange(natoms) 

515 rank = arange - np.maximum.accumulate(np.where(first, arange, 0)) 

516 return order[rank < keep] 

517 

518 def _draw_indices(self, X, n, r, vector_arrays, labels): 

519 """Which drawable objects to actually render this frame. 

520 

521 ``self.indices`` deliberately stays the complete z-order: it is 

522 also what release() walks for click hit-testing, so filtering it 

523 would silently make atoms unselectable rather than merely undrawn. 

524 """ 

525 indices = self.indices 

526 ncell = len(self.X_cell) 

527 reducing = self._reducing_detail() 

528 

529 if reducing: 

530 # Bonds are ~87% of the objects in a dense periodic system. 

531 indices = indices[indices < n + ncell] 

532 

533 if ( 

534 not self.occlusion_culling 

535 or len(self.X) <= self.LEVEL_OF_DETAIL_MIN_OBJECTS 

536 ): 

537 return indices 

538 

539 # Labels and vectors are drawn outside the atom's own circle, so a 

540 # hidden atom can still contribute ink. Don't cull in that case. 

541 # While interacting they are suppressed anyway, so culling applies. 

542 if labels is not None or vector_arrays: 

543 return indices 

544 

545 # Statically, keep enough atoms per cell that the result is 

546 # indistinguishable from drawing all of them. While the view is 

547 # moving, one per cell is plenty: it is a transient frame, and with 

548 # bonds hidden this is the only thing that reduces the atom count 

549 # at all. 

550 keep = np.zeros(n, bool) 

551 keep[ 

552 self._visible_atoms( 

553 X[:n, :2], X[:n, 2], r, keep=1 if reducing else 3 

554 ) 

555 ] = True 

556 # Selected atoms get a heavier outline and moving atoms a halo that 

557 # extends beyond the circle; keep them whether or not they show. 

558 keep |= self.images.selected[:n] 

559 if self.moving: 

560 mask = np.asarray(self.move_atoms_mask[:n], bool) 

561 keep[: len(mask)] |= mask 

562 

563 drawable = np.ones(len(self.X), bool) 

564 drawable[:n] = keep 

565 nbonds = len(self.X) - n - ncell 

566 if nbonds > 0 and len(self.bonds) == nbonds: 

567 # A bond is visible if either atom it connects is. 

568 drawable[n + ncell :] = ( 

569 keep[self.bonds[:, 0]] | keep[self.bonds[:, 1]] 

570 ) 

571 return indices[drawable[indices]] 

572 

573 def draw(self, status=True): 

574 self.window.clear() 

575 axes = self.scale * self.axes * (1, -1, 1) 

576 offset = np.dot(self.center, axes) 

577 offset[:2] -= 0.5 * self.window.size 

578 X = np.dot(self.X, axes) - offset 

579 n = len(self.atoms) 

580 

581 # The indices enumerate drawable objects in z order. This stays 

582 # complete even when only a subset is drawn: release() uses it to 

583 # hit-test clicks. 

584 self.indices = X[:, 2].argsort() 

585 reduce_detail = self._reducing_detail() 

586 r = self.get_covalent_radii() * self.scale 

587 if self.window['toggle-show-bonds']: 

588 r *= 0.65 

589 P = self.P = X[:n, :2] 

590 A = (P - r[:, None]).round().astype(int) 

591 X1 = X[n:, :2].round().astype(int) 

592 X2 = (np.dot(self.B, axes) - offset).round().astype(int) 

593 disp = ( 

594 (np.dot(self.atoms.get_celldisp().reshape((3,)), axes)) 

595 .round() 

596 .astype(int) 

597 ) 

598 d = (2 * r).round().astype(int) 

599 

600 vector_arrays = [] 

601 if not reduce_detail and self.window['toggle-show-velocities']: 

602 # Scale ugly? 

603 v = self.atoms.get_velocities() 

604 if v is not None: 

605 vector_arrays.append(v * 10.0 * self.velocity_vector_scale) 

606 if not reduce_detail and self.window['toggle-show-forces']: 

607 f = self.get_forces() 

608 vector_arrays.append(f * self.force_vector_scale) 

609 

610 if not reduce_detail and self.window['toggle-show-magmoms']: 

611 magmom = get_magmoms(self.atoms) 

612 # Turn this into a 3D vector if it is a scalar 

613 magmom_vecs = [] 

614 for i in range(len(magmom)): 

615 if isinstance(magmom[i], (int, float)): 

616 magmom_vecs.append(np.array([0, 0, magmom[i]])) 

617 elif isinstance(magmom[i], np.ndarray) and len(magmom[i]) == 3: 

618 magmom_vecs.append(magmom[i]) 

619 else: 

620 raise TypeError( 

621 'Magmom is not a 3-component vector or a scalar' 

622 ) 

623 magmom_vecs = np.array(magmom_vecs) 

624 vector_arrays.append(magmom_vecs * 0.5 * self.magmom_vector_scale) 

625 

626 for array in vector_arrays: 

627 array[:] = np.dot(array, axes) + X[:n] 

628 

629 colors = self.get_colors() 

630 circle = self.window.circle 

631 arc = self.window.arc 

632 line = self.window.line 

633 constrained = ~self.images.get_dynamic(self.atoms) 

634 

635 selected = self.images.selected 

636 visible = self.images.visible 

637 ncell = len(self.X_cell) 

638 bond_linewidth = self.scale * 0.15 

639 

640 labels = None if reduce_detail else self.get_labels() 

641 

642 if self.arrowkey_mode == self.ARROWKEY_MOVE: 

643 movecolor = GREEN 

644 elif self.arrowkey_mode == self.ARROWKEY_ROTATE: 

645 movecolor = PURPLE 

646 

647 for a in self._draw_indices(X, n, r, vector_arrays, labels): 

648 if a < n: 

649 ra = d[a] 

650 if visible[a]: 

651 try: 

652 kinds = self.atoms.arrays['spacegroup_kinds'] 

653 site_occ = self.atoms.info['occupancy'][str(kinds[a])] 

654 # first an empty circle if a site is not fully occupied 

655 if (np.sum([v for v in site_occ.values()])) < 1.0: 

656 fill = '#ffffff' 

657 circle( 

658 fill, 

659 selected[a], 

660 A[a, 0], 

661 A[a, 1], 

662 A[a, 0] + ra, 

663 A[a, 1] + ra, 

664 ) 

665 start = 0 

666 # start with the dominant species 

667 for sym, occ in sorted( 

668 site_occ.items(), key=lambda x: x[1], reverse=True 

669 ): 

670 if np.round(occ, decimals=4) == 1.0: 

671 circle( 

672 colors[a], 

673 selected[a], 

674 A[a, 0], 

675 A[a, 1], 

676 A[a, 0] + ra, 

677 A[a, 1] + ra, 

678 ) 

679 else: 

680 # jmol colors for the moment 

681 extent = 360.0 * occ 

682 arc( 

683 self.colors[atomic_numbers[sym]], 

684 selected[a], 

685 start, 

686 extent, 

687 A[a, 0], 

688 A[a, 1], 

689 A[a, 0] + ra, 

690 A[a, 1] + ra, 

691 ) 

692 start += extent 

693 except KeyError: 

694 # legacy behavior 

695 # Draw the atoms 

696 if ( 

697 self.moving 

698 and a < len(self.move_atoms_mask) 

699 and self.move_atoms_mask[a] 

700 ): 

701 circle( 

702 movecolor, 

703 False, 

704 A[a, 0] - 4, 

705 A[a, 1] - 4, 

706 A[a, 0] + ra + 4, 

707 A[a, 1] + ra + 4, 

708 ) 

709 

710 circle( 

711 colors[a], 

712 selected[a], 

713 A[a, 0], 

714 A[a, 1], 

715 A[a, 0] + ra, 

716 A[a, 1] + ra, 

717 ) 

718 

719 # Draw labels on the atoms 

720 if labels is not None: 

721 self.window.text( 

722 A[a, 0] + ra / 2, A[a, 1] + ra / 2, str(labels[a]) 

723 ) 

724 

725 # Draw cross on constrained atoms 

726 if constrained[a]: 

727 R1 = int(0.14644 * ra) 

728 R2 = int(0.85355 * ra) 

729 line( 

730 ( 

731 A[a, 0] + R1, 

732 A[a, 1] + R1, 

733 A[a, 0] + R2, 

734 A[a, 1] + R2, 

735 ) 

736 ) 

737 line( 

738 ( 

739 A[a, 0] + R2, 

740 A[a, 1] + R1, 

741 A[a, 0] + R1, 

742 A[a, 1] + R2, 

743 ) 

744 ) 

745 

746 # Draw velocities and/or forces 

747 for v in vector_arrays: 

748 assert not np.isnan(v).any() 

749 self.arrow( 

750 (X[a, 0], X[a, 1], v[a, 0], v[a, 1]), width=2 

751 ) 

752 else: 

753 # Draw unit cell and/or bonds: 

754 a -= n 

755 if a < ncell: 

756 line( 

757 ( 

758 X1[a, 0] + disp[0], 

759 X1[a, 1] + disp[1], 

760 X2[a, 0] + disp[0], 

761 X2[a, 1] + disp[1], 

762 ) 

763 ) 

764 else: 

765 line( 

766 (X1[a, 0], X1[a, 1], X2[a, 0], X2[a, 1]), 

767 width=bond_linewidth, 

768 ) 

769 

770 if self.window['toggle-show-axes']: 

771 self.draw_axes() 

772 

773 if self.arrowkey_mode != self.ARROWKEY_SCAN: 

774 self.draw_arrowkey_hint() 

775 else: 

776 self.hide_arrowkey_hint() 

777 if len(self.images) > 1: 

778 self.draw_frame_number() 

779 

780 self.window.update() 

781 

782 if status: 

783 self.status.status(self.atoms) 

784 

785 # Currently we change the atoms all over the place willy-nilly 

786 # and then call draw(). For which reason we abuse draw() to notify 

787 # the observers about general changes. 

788 # 

789 # We should refactor so change_atoms is only emitted 

790 # when when atoms actually change, and maybe have a separate signal 

791 # to listen to e.g. changes of view. 

792 self.obs.change_atoms.notify() 

793 

794 def arrow(self, coords, width): 

795 line = self.window.line 

796 begin = np.array((coords[0], coords[1])) 

797 end = np.array((coords[2], coords[3])) 

798 line(coords, width) 

799 

800 vec = end - begin 

801 length = np.sqrt((vec[:2] ** 2).sum()) 

802 length = min(length, 0.3 * self.scale) 

803 

804 angle = np.arctan2(end[1] - begin[1], end[0] - begin[0]) + np.pi 

805 x1 = (end[0] + length * np.cos(angle - 0.3)).round().astype(int) 

806 y1 = (end[1] + length * np.sin(angle - 0.3)).round().astype(int) 

807 x2 = (end[0] + length * np.cos(angle + 0.3)).round().astype(int) 

808 y2 = (end[1] + length * np.sin(angle + 0.3)).round().astype(int) 

809 line((x1, y1, end[0], end[1]), width) 

810 line((x2, y2, end[0], end[1]), width) 

811 

812 def draw_axes(self): 

813 axes_length = 15 

814 

815 rgb = ['red', 'green', 'blue'] 

816 

817 for i in self.axes[:, 2].argsort(): 

818 a = 20 

819 b = self.window.size[1] - 20 

820 c = int(self.axes[i][0] * axes_length + a) 

821 d = int(-self.axes[i][1] * axes_length + b) 

822 self.window.line((a, b, c, d)) 

823 self.window.text(c, d, 'XYZ'[i], color=rgb[i]) 

824 

825 def draw_arrowkey_hint(self): 

826 if self.arrowkey_mode == self.ARROWKEY_ROTATE: 

827 hint = _('ROTATING') 

828 bg = PURPLE 

829 tip_text = _( 

830 'Ctrl + Up/Down: rotate around the view axis\n' 

831 'Shift + Arrow keys: rotate in smaller increments' 

832 ) 

833 else: 

834 hint = _('MOVING') 

835 bg = GREEN 

836 tip_text = _( 

837 'Ctrl + Up/Down: move along the view axis\n' 

838 'Shift + Arrow keys: move in smaller increments' 

839 ) 

840 self.arrowkey_hint.label.configure( 

841 text=hint, 

842 padx=3, 

843 bg=bg, 

844 ) 

845 self.arrowkey_hint.tooltip.configure( 

846 text=tip_text, 

847 justify='right', 

848 font='TkTooltipFont', 

849 ) 

850 self.arrowkey_hint.place(relx=1.0, rely=1.0, anchor='se') 

851 self.arrowkey_hint.exists = True 

852 

853 def hide_arrowkey_hint(self): 

854 if self.arrowkey_hint.exists: 

855 self.arrowkey_hint.place_forget() 

856 self.arrowkey_hint.exists = False 

857 

858 def draw_frame_number(self): 

859 x, y = self.window.size 

860 self.window.text(x, y, '{}'.format(self.frame), anchor='SE') 

861 

862 def release(self, event): 

863 if event.button in [4, 5]: 

864 self.scroll_event(event) 

865 return 

866 

867 # Interaction is over: restore full detail before hit-testing below, 

868 # so self.P and self.indices describe the final frame. 

869 self.interactive = False 

870 if self._settle_timer is not None: 

871 self._settle_timer.cancel() 

872 self._settle_timer = None 

873 

874 if event.button != self.b1: 

875 self.draw() 

876 return 

877 

878 selected = self.images.selected 

879 selected_ordered = self.images.selected_ordered 

880 

881 if event.time < self.t0 + 200: # 200 ms 

882 d = self.P - self.xy 

883 r = self.get_covalent_radii() 

884 hit = np.less((d**2).sum(1), (self.scale * r) ** 2) 

885 for a in self.indices[::-1]: 

886 if a < len(self.atoms) and hit[a]: 

887 if event.modifier == 'ctrl': 

888 selected[a] = not selected[a] 

889 if selected[a]: 

890 selected_ordered += [a] 

891 elif len(selected_ordered) > 0: 

892 if selected_ordered[-1] == a: 

893 selected_ordered = selected_ordered[:-1] 

894 else: 

895 selected_ordered = [] 

896 else: 

897 selected[:] = False 

898 selected[a] = True 

899 selected_ordered = [a] 

900 break 

901 else: 

902 selected[:] = False 

903 selected_ordered = [] 

904 self.draw() 

905 else: 

906 A = (event.x, event.y) 

907 C1 = np.minimum(A, self.xy) 

908 C2 = np.maximum(A, self.xy) 

909 hit = np.logical_and(self.P > C1, self.P < C2) 

910 indices = np.compress(hit.prod(1), np.arange(len(hit))) 

911 if event.modifier != 'ctrl': 

912 selected[:] = False 

913 selected[indices] = True 

914 if ( 

915 len(indices) == 1 

916 and indices[0] not in self.images.selected_ordered 

917 ): 

918 selected_ordered += [indices[0]] 

919 elif len(indices) > 1: 

920 selected_ordered = [] 

921 self.draw() 

922 

923 # XXX check bounds 

924 natoms = len(self.atoms) 

925 indices = np.arange(natoms)[self.images.selected[:natoms]] 

926 if len(indices) != len(selected_ordered): 

927 selected_ordered = [] 

928 self.images.selected_ordered = selected_ordered 

929 

930 def press(self, event): 

931 self.button = event.button 

932 self.xy = (event.x, event.y) 

933 self.t0 = event.time 

934 self.axes0 = self.axes 

935 self.center0 = self.center 

936 

937 def move(self, event): 

938 from ase.gui.ui import UNCACHED_PRIMITIVES_TAG 

939 

940 x = event.x 

941 y = event.y 

942 x0, y0 = self.xy 

943 if self.button == self.b1: 

944 x0 = int(round(x0)) 

945 y0 = int(round(y0)) 

946 # The scene does not change while rubber-band selecting, so 

947 # replace just the rectangle instead of redrawing everything. 

948 self.window.canvas.delete(UNCACHED_PRIMITIVES_TAG) 

949 self.window.canvas.create_rectangle( 

950 (x, y, x0, y0), tags=UNCACHED_PRIMITIVES_TAG 

951 ) 

952 return 

953 

954 self.begin_interaction() 

955 

956 if event.modifier == 'shift': 

957 self.center = ( 

958 self.center0 

959 - np.dot(self.axes, (x - x0, y0 - y, 0)) / self.scale 

960 ) 

961 else: 

962 # Snap mode: the a-b angle and t should multipla of 15 degrees ??? 

963 a = x - x0 

964 b = y0 - y 

965 t = sqrt(a * a + b * b) 

966 if t > 0: 

967 a /= t 

968 b /= t 

969 else: 

970 a = 1.0 

971 b = 0.0 

972 c = cos(0.01 * t) 

973 s = -sin(0.01 * t) 

974 rotation = np.array( 

975 [ 

976 (c * a * a + b * b, (c - 1) * b * a, s * a), 

977 ((c - 1) * a * b, c * b * b + a * a, s * b), 

978 (-s * a, -s * b, c), 

979 ] 

980 ) 

981 self.axes = np.dot(self.axes0, rotation) 

982 if len(self.atoms) > 0: 

983 com = self.X_pos.mean(0) 

984 else: 

985 com = self.atoms.cell.mean(0) 

986 self.center = com - np.dot( 

987 com - self.center0, np.dot(self.axes0, self.axes.T) 

988 ) 

989 self.draw(status=False) 

990 

991 def render_window(self): 

992 return Render(self) 

993 

994 def resize(self, event): 

995 w, h = self.window.size 

996 self.scale *= (event.width * event.height / (w * h)) ** 0.5 

997 self.window.size[:] = [event.width, event.height] 

998 self.draw()