Coverage for /builds/ase/ase/ase/gui/view.py: 68.18%

506 statements  

« prev     ^ index     » next       coverage.py v7.5.3, created at 2025-08-02 00:12 +0000

1# fmt: off 

2 

3from math import cos, sin, sqrt 

4from os.path import basename 

5 

6import numpy as np 

7 

8from ase.calculators.calculator import PropertyNotImplementedError 

9from ase.data import atomic_numbers 

10from ase.data.colors import jmol_colors 

11from ase.geometry import complete_cell 

12from ase.gui.colors import ColorWindow 

13from ase.gui.i18n import ngettext 

14from ase.gui.render import Render 

15from ase.gui.repeat import Repeat 

16from ase.gui.rotate import Rotate 

17from ase.gui.utils import get_magmoms 

18from ase.utils import rotate 

19 

20GREEN = '#74DF00' 

21PURPLE = '#AC58FA' 

22BLACKISH = '#151515' 

23 

24 

25def get_cell_coordinates(cell, shifted=False): 

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

27 nn = [] 

28 for c in range(3): 

29 v = cell[c] 

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

31 if d < 1e-12: 

32 n = 0 

33 else: 

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

35 nn.append(n) 

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

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

38 n1 = 0 

39 for c, n in enumerate(nn): 

40 n2 = n1 + n 

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

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

43 

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

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

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

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

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

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

50 n1 = n2 

51 B1.shape = (-1, 3) 

52 B2.shape = (-1, 3) 

53 if shifted: 

54 B1 -= 0.5 

55 B2 -= 0.5 

56 return B1, B2 

57 

58 

59def get_bonds(atoms, covalent_radii): 

60 from ase.neighborlist import PrimitiveNeighborList 

61 

62 nl = PrimitiveNeighborList( 

63 covalent_radii * 1.5, 

64 skin=0.0, 

65 self_interaction=False, 

66 bothways=False, 

67 ) 

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

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

70 number_of_pbc_neighbors = sum( 

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

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

73 nbonds = number_of_neighbors + number_of_pbc_neighbors 

74 

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

76 if nbonds == 0: 

77 return bonds 

78 

79 n1 = 0 

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

81 indices, offsets = nl.get_neighbors(a) 

82 n2 = n1 + len(indices) 

83 bonds[n1:n2, 0] = a 

84 bonds[n1:n2, 1] = indices 

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

86 n1 = n2 

87 

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

89 pbcbonds = bonds[:n2][i] 

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

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

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

93 return bonds 

94 

95 

96class View: 

97 def __init__(self, rotations): 

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

99 self.axes = rotate(rotations) 

100 self.configured = False 

101 self.frame = None 

102 

103 # XXX 

104 self.colormode = 'jmol' 

105 self.colors = { 

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

107 for i, rgb in enumerate(jmol_colors) 

108 } 

109 # scaling factors for vectors 

110 self.force_vector_scale = self.config['force_vector_scale'] 

111 self.velocity_vector_scale = self.config['velocity_vector_scale'] 

112 self.magmom_vector_scale = self.config['magmom_vector_scale'] 

113 

114 # buttons 

115 self.b1 = 1 # left 

116 self.b3 = 3 # right 

117 if self.config['swap_mouse']: 

118 self.b1 = 3 

119 self.b3 = 1 

120 

121 @property 

122 def atoms(self): 

123 return self.images[self.frame] 

124 

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

126 if frame is None: 

127 frame = self.frame 

128 assert frame < len(self.images) 

129 self.frame = frame 

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

131 

132 fname = self.images.filenames[frame] 

133 if fname is None: 

134 header = 'ase.gui' 

135 else: 

136 # fname is actually not necessarily the filename but may 

137 # contain indexing like filename@0 

138 header = basename(fname) 

139 

140 images_loaded_text = ngettext( 

141 'one image loaded', 

142 '{} images loaded', 

143 len(self.images) 

144 ).format(len(self.images)) 

145 

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

147 

148 if focus: 

149 self.focus() 

150 else: 

151 self.draw() 

152 

153 def get_bonds(self, atoms): 

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

155 # so that it can be overridden by external libraries 

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

157 

158 def set_atoms(self, atoms): 

159 natoms = len(atoms) 

160 

161 if self.showing_cell(): 

162 B1, B2 = get_cell_coordinates(atoms.cell, 

163 self.config['shift_cell']) 

164 else: 

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

166 

167 if self.showing_bonds(): 

168 atomscopy = atoms.copy() 

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

170 bonds = self.get_bonds(atomscopy) 

171 else: 

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

173 

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

175 # like bonds and cell segments. 

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

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

178 

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

180 

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

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

183 self.X_pos[:] = atoms.positions 

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

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

186 

187 cell = atoms.cell 

188 ncellparts = len(B1) 

189 nbonds = len(bonds) 

190 

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

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

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

194 

195 if nbonds > 0: 

196 P = atoms.positions 

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

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

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

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

201 r = 0.65 * self.get_covalent_radii() 

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

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

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

205 b *= 1.0 - x0 - x1 

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

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

208 

209 self.obs.set_atoms.notify() 

210 

211 def showing_bonds(self): 

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

213 

214 def showing_cell(self): 

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

216 

217 def toggle_show_unit_cell(self, key=None): 

218 self.set_frame() 

219 

220 def get_labels(self): 

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

222 if index == 0: 

223 return None 

224 

225 if index == 1: 

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

227 

228 if index == 2: 

229 return list(get_magmoms(self.atoms)) 

230 

231 if index == 4: 

232 Q = self.atoms.get_initial_charges() 

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

234 

235 return self.atoms.symbols 

236 

237 def show_labels(self): 

238 self.draw() 

239 

240 def toggle_show_axes(self, key=None): 

241 self.draw() 

242 

243 def toggle_show_bonds(self, key=None): 

244 self.set_frame() 

245 

246 def toggle_show_velocities(self, key=None): 

247 self.draw() 

248 

249 def get_forces(self): 

250 if self.atoms.calc is not None: 

251 try: 

252 return self.atoms.get_forces() 

253 except PropertyNotImplementedError: 

254 pass 

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

256 

257 def toggle_show_forces(self, key=None): 

258 self.draw() 

259 

260 def toggle_show_magmoms(self, key=None): 

261 self.draw() 

262 

263 def hide_selected(self): 

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

265 self.draw() 

266 

267 def show_selected(self): 

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

269 self.draw() 

270 

271 def repeat_window(self, key=None): 

272 return Repeat(self) 

273 

274 def rotate_window(self): 

275 return Rotate(self) 

276 

277 def colors_window(self, key=None): 

278 win = ColorWindow(self) 

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

280 return win 

281 

282 def focus(self, x=None): 

283 cell = (self.window['toggle-show-unit-cell'] and 

284 self.images[0].cell.any()) 

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

286 self.scale = 20.0 

287 self.center = np.zeros(3) 

288 self.draw() 

289 return 

290 

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

292 # including the covalent_radii used for drawing the atoms 

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

294 n = len(self.atoms) 

295 covalent_radii = self.get_covalent_radii() 

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

297 P1 = P.min(0) 

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

299 P2 = P.max(0) 

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

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

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

303 S = 1.3 * (P2 - P1) 

304 w, h = self.window.size 

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

306 self.scale = h / S[1] 

307 elif S[0] > 0.0001: 

308 self.scale = w / S[0] 

309 else: 

310 self.scale = 1.0 

311 self.draw() 

312 

313 def reset_view(self, menuitem): 

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

315 self.set_frame() 

316 self.focus(self) 

317 

318 def set_view(self, key): 

319 if key == 'Z': 

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

321 elif key == 'X': 

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

323 elif key == 'Y': 

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

325 elif key == 'Shift+Z': 

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

327 elif key == 'Shift+X': 

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

329 elif key == 'Shift+Y': 

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

331 else: 

332 if key == 'I': 

333 i, j = 1, 2 

334 elif key == 'J': 

335 i, j = 2, 0 

336 elif key == 'K': 

337 i, j = 0, 1 

338 elif key == 'Shift+I': 

339 i, j = 2, 1 

340 elif key == 'Shift+J': 

341 i, j = 0, 2 

342 elif key == 'Shift+K': 

343 i, j = 1, 0 

344 

345 A = complete_cell(self.atoms.cell) 

346 x1 = A[i] 

347 x2 = A[j] 

348 

349 norm = np.linalg.norm 

350 

351 x1 = x1 / norm(x1) 

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

353 x2 /= norm(x2) 

354 x3 = np.cross(x1, x2) 

355 

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

357 

358 self.set_frame() 

359 

360 def get_colors(self, rgb=False): 

361 if rgb: 

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

363 for _rgb in self.get_colors()] 

364 

365 if self.colormode == 'jmol': 

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

367 

368 if self.colormode == 'neighbors': 

369 return [self.colors.get(Z, BLACKISH) 

370 for Z in self.get_color_scalars()] 

371 

372 colorscale, cmin, cmax = self.colormode_data 

373 N = len(colorscale) 

374 colorswhite = colorscale + ['#ffffff'] 

375 if cmin == cmax: 

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

377 else: 

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

379 indices = np.clip(((scalars - cmin) / (cmax - cmin) * N + 

380 0.5).astype(int), 

381 0, N - 1).filled(N) 

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

383 

384 def get_color_scalars(self, frame=None): 

385 if self.colormode == 'tag': 

386 return self.atoms.get_tags() 

387 if self.colormode == 'force': 

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

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

390 elif self.colormode == 'velocity': 

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

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

393 return self.atoms.get_initial_charges() 

394 elif self.colormode == 'magmom': 

395 return get_magmoms(self.atoms) 

396 elif self.colormode == 'neighbors': 

397 from ase.neighborlist import NeighborList 

398 n = len(self.atoms) 

399 nl = NeighborList(self.get_covalent_radii(self.atoms) * 1.5, 

400 skin=0, self_interaction=False, bothways=True) 

401 nl.update(self.atoms) 

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

403 else: 

404 scalars = np.array(self.atoms.get_array(self.colormode), 

405 dtype=float) 

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

407 

408 def get_covalent_radii(self, atoms=None): 

409 if atoms is None: 

410 atoms = self.atoms 

411 return self.images.get_radii(atoms) 

412 

413 def draw(self, status=True): 

414 self.window.clear() 

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

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

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

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

419 n = len(self.atoms) 

420 

421 # The indices enumerate drawable objects in z order: 

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

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

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

425 r *= 0.65 

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

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

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

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

430 disp = (np.dot(self.atoms.get_celldisp().reshape((3,)), 

431 axes)).round().astype(int) 

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

433 

434 vector_arrays = [] 

435 if self.window['toggle-show-velocities']: 

436 # Scale ugly? 

437 v = self.atoms.get_velocities() 

438 if v is not None: 

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

440 if self.window['toggle-show-forces']: 

441 f = self.get_forces() 

442 vector_arrays.append(f * self.force_vector_scale) 

443 

444 if self.window['toggle-show-magmoms']: 

445 magmom = get_magmoms(self.atoms) 

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

447 magmom_vecs = [] 

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

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

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

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

452 magmom_vecs.append(magmom[i]) 

453 else: 

454 raise TypeError('Magmom is not a 3-component vector ' 

455 'or a scalar') 

456 magmom_vecs = np.array(magmom_vecs) 

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

458 

459 for array in vector_arrays: 

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

461 

462 colors = self.get_colors() 

463 circle = self.window.circle 

464 arc = self.window.arc 

465 line = self.window.line 

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

467 

468 selected = self.images.selected 

469 visible = self.images.visible 

470 ncell = len(self.X_cell) 

471 bond_linewidth = self.scale * 0.15 

472 

473 labels = self.get_labels() 

474 

475 if self.arrowkey_mode == self.ARROWKEY_MOVE: 

476 movecolor = GREEN 

477 elif self.arrowkey_mode == self.ARROWKEY_ROTATE: 

478 movecolor = PURPLE 

479 

480 for a in self.indices: 

481 if a < n: 

482 ra = d[a] 

483 if visible[a]: 

484 try: 

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

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

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

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

489 fill = '#ffffff' 

490 circle(fill, selected[a], 

491 A[a, 0], A[a, 1], 

492 A[a, 0] + ra, A[a, 1] + ra) 

493 start = 0 

494 # start with the dominant species 

495 for sym, occ in sorted(site_occ.items(), 

496 key=lambda x: x[1], 

497 reverse=True): 

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

499 circle(colors[a], selected[a], 

500 A[a, 0], A[a, 1], 

501 A[a, 0] + ra, A[a, 1] + ra) 

502 else: 

503 # jmol colors for the moment 

504 extent = 360. * occ 

505 arc(self.colors[atomic_numbers[sym]], 

506 selected[a], 

507 start, extent, 

508 A[a, 0], A[a, 1], 

509 A[a, 0] + ra, A[a, 1] + ra) 

510 start += extent 

511 except KeyError: 

512 # legacy behavior 

513 # Draw the atoms 

514 if (self.moving and a < len(self.move_atoms_mask) 

515 and self.move_atoms_mask[a]): 

516 circle(movecolor, False, 

517 A[a, 0] - 4, A[a, 1] - 4, 

518 A[a, 0] + ra + 4, A[a, 1] + ra + 4) 

519 

520 circle(colors[a], selected[a], 

521 A[a, 0], A[a, 1], A[a, 0] + ra, A[a, 1] + ra) 

522 

523 # Draw labels on the atoms 

524 if labels is not None: 

525 self.window.text(A[a, 0] + ra / 2, 

526 A[a, 1] + ra / 2, 

527 str(labels[a])) 

528 

529 # Draw cross on constrained atoms 

530 if constrained[a]: 

531 R1 = int(0.14644 * ra) 

532 R2 = int(0.85355 * ra) 

533 line((A[a, 0] + R1, A[a, 1] + R1, 

534 A[a, 0] + R2, A[a, 1] + R2)) 

535 line((A[a, 0] + R2, A[a, 1] + R1, 

536 A[a, 0] + R1, A[a, 1] + R2)) 

537 

538 # Draw velocities and/or forces 

539 for v in vector_arrays: 

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

541 self.arrow((X[a, 0], X[a, 1], v[a, 0], v[a, 1]), 

542 width=2) 

543 else: 

544 # Draw unit cell and/or bonds: 

545 a -= n 

546 if a < ncell: 

547 line((X1[a, 0] + disp[0], X1[a, 1] + disp[1], 

548 X2[a, 0] + disp[0], X2[a, 1] + disp[1])) 

549 else: 

550 line((X1[a, 0], X1[a, 1], 

551 X2[a, 0], X2[a, 1]), 

552 width=bond_linewidth) 

553 

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

555 self.draw_axes() 

556 

557 if len(self.images) > 1: 

558 self.draw_frame_number() 

559 

560 self.window.update() 

561 

562 if status: 

563 self.status.status(self.atoms) 

564 

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

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

567 # the observers about general changes. 

568 # 

569 # We should refactor so change_atoms is only emitted 

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

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

572 self.obs.change_atoms.notify() 

573 

574 def arrow(self, coords, width): 

575 line = self.window.line 

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

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

578 line(coords, width) 

579 

580 vec = end - begin 

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

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

583 

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

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

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

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

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

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

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

591 

592 def draw_axes(self): 

593 axes_length = 15 

594 

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

596 

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

598 a = 20 

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

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

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

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

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

604 

605 def draw_frame_number(self): 

606 x, y = self.window.size 

607 self.window.text(x, y, '{}'.format(self.frame), 

608 anchor='SE') 

609 

610 def release(self, event): 

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

612 self.scroll_event(event) 

613 return 

614 

615 if event.button != self.b1: 

616 return 

617 

618 selected = self.images.selected 

619 selected_ordered = self.images.selected_ordered 

620 

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

622 d = self.P - self.xy 

623 r = self.get_covalent_radii() 

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

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

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

627 if event.modifier == 'ctrl': 

628 selected[a] = not selected[a] 

629 if selected[a]: 

630 selected_ordered += [a] 

631 elif len(selected_ordered) > 0: 

632 if selected_ordered[-1] == a: 

633 selected_ordered = selected_ordered[:-1] 

634 else: 

635 selected_ordered = [] 

636 else: 

637 selected[:] = False 

638 selected[a] = True 

639 selected_ordered = [a] 

640 break 

641 else: 

642 selected[:] = False 

643 selected_ordered = [] 

644 self.draw() 

645 else: 

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

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

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

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

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

651 if event.modifier != 'ctrl': 

652 selected[:] = False 

653 selected[indices] = True 

654 if (len(indices) == 1 and 

655 indices[0] not in self.images.selected_ordered): 

656 selected_ordered += [indices[0]] 

657 elif len(indices) > 1: 

658 selected_ordered = [] 

659 self.draw() 

660 

661 # XXX check bounds 

662 natoms = len(self.atoms) 

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

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

665 selected_ordered = [] 

666 self.images.selected_ordered = selected_ordered 

667 

668 def press(self, event): 

669 self.button = event.button 

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

671 self.t0 = event.time 

672 self.axes0 = self.axes 

673 self.center0 = self.center 

674 

675 def move(self, event): 

676 x = event.x 

677 y = event.y 

678 x0, y0 = self.xy 

679 if self.button == self.b1: 

680 x0 = int(round(x0)) 

681 y0 = int(round(y0)) 

682 self.draw() 

683 self.window.canvas.create_rectangle((x, y, x0, y0)) 

684 return 

685 

686 if event.modifier == 'shift': 

687 self.center = (self.center0 - 

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

689 else: 

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

691 a = x - x0 

692 b = y0 - y 

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

694 if t > 0: 

695 a /= t 

696 b /= t 

697 else: 

698 a = 1.0 

699 b = 0.0 

700 c = cos(0.01 * t) 

701 s = -sin(0.01 * t) 

702 rotation = np.array([(c * a * a + b * b, (c - 1) * b * a, s * a), 

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

704 (-s * a, -s * b, c)]) 

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

706 if len(self.atoms) > 0: 

707 com = self.X_pos.mean(0) 

708 else: 

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

710 self.center = com - np.dot(com - self.center0, 

711 np.dot(self.axes0, self.axes.T)) 

712 self.draw(status=False) 

713 

714 def render_window(self): 

715 return Render(self) 

716 

717 def resize(self, event): 

718 w, h = self.window.size 

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

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

721 self.draw()