Coverage for /builds/hweiske/ase/ase/gui/view.py: 63.27%
490 statements
« prev ^ index » next coverage.py v7.2.7, created at 2024-04-22 11:22 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2024-04-22 11:22 +0000
1from math import cos, sin, sqrt
2from os.path import basename
4import numpy as np
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
18GREEN = '#74DF00'
19PURPLE = '#AC58FA'
20BLACKISH = '#151515'
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)
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.shape = (-1, 3)
50 B2.shape = (-1, 3)
51 if shifted:
52 B1 -= 0.5
53 B2 -= 0.5
54 return B1, B2
57def get_bonds(atoms, covalent_radii):
58 from ase.neighborlist import NeighborList
59 nl = NeighborList(covalent_radii * 1.5,
60 skin=0, self_interaction=False)
61 nl.update(atoms)
62 nbonds = nl.nneighbors + nl.npbcneighbors
64 bonds = np.empty((nbonds, 5), int)
65 if nbonds == 0:
66 return bonds
68 n1 = 0
69 for a in range(len(atoms)):
70 indices, offsets = nl.get_neighbors(a)
71 n2 = n1 + len(indices)
72 bonds[n1:n2, 0] = a
73 bonds[n1:n2, 1] = indices
74 bonds[n1:n2, 2:] = offsets
75 n1 = n2
77 i = bonds[:n2, 2:].any(1)
78 pbcbonds = bonds[:n2][i]
79 bonds[n2:, 0] = pbcbonds[:, 1]
80 bonds[n2:, 1] = pbcbonds[:, 0]
81 bonds[n2:, 2:] = -pbcbonds[:, 2:]
82 return bonds
85class View:
86 def __init__(self, rotations):
87 self.colormode = 'jmol' # The default colors
88 self.labels = None
89 self.axes = rotate(rotations)
90 self.configured = False
91 self.frame = None
93 # XXX
94 self.colormode = 'jmol'
95 self.colors = {
96 i: ('#{:02X}{:02X}{:02X}'.format(*(int(x * 255) for x in rgb)))
97 for i, rgb in enumerate(jmol_colors)
98 }
99 # scaling factors for vectors
100 self.force_vector_scale = self.config['force_vector_scale']
101 self.velocity_vector_scale = self.config['velocity_vector_scale']
103 # buttons
104 self.b1 = 1 # left
105 self.b3 = 3 # right
106 if self.config['swap_mouse']:
107 self.b1 = 3
108 self.b3 = 1
110 @property
111 def atoms(self):
112 return self.images[self.frame]
114 def set_frame(self, frame=None, focus=False):
115 if frame is None:
116 frame = self.frame
117 assert frame < len(self.images)
118 self.frame = frame
119 self.set_atoms(self.images[frame])
121 fname = self.images.filenames[frame]
122 if fname is None:
123 header = 'ase.gui'
124 else:
125 # fname is actually not necessarily the filename but may
126 # contain indexing like filename@0
127 header = basename(fname)
129 images_loaded_text = ngettext(
130 'one image loaded',
131 '{} images loaded',
132 len(self.images)
133 ).format(len(self.images))
135 self.window.title = f'{header} — {images_loaded_text}'
137 if focus:
138 self.focus()
139 else:
140 self.draw()
142 def set_atoms(self, atoms):
143 natoms = len(atoms)
145 if self.showing_cell():
146 B1, B2 = get_cell_coordinates(atoms.cell,
147 self.config['shift_cell'])
148 else:
149 B1 = B2 = np.zeros((0, 3))
151 if self.showing_bonds():
152 atomscopy = atoms.copy()
153 atomscopy.cell *= self.images.repeat[:, np.newaxis]
154 bonds = get_bonds(atomscopy, self.get_covalent_radii(atoms))
155 else:
156 bonds = np.empty((0, 5), int)
158 # X is all atomic coordinates, and starting points of vectors
159 # like bonds and cell segments.
160 # The reason to have them all in one big list is that we like to
161 # eventually rotate/sort it by Z-order when rendering.
163 # Also B are the end points of line segments.
165 self.X = np.empty((natoms + len(B1) + len(bonds), 3))
166 self.X_pos = self.X[:natoms]
167 self.X_pos[:] = atoms.positions
168 self.X_cell = self.X[natoms:natoms + len(B1)]
169 self.X_bonds = self.X[natoms + len(B1):]
171 if 1: # if init or frame != self.frame:
172 cell = atoms.cell
173 ncellparts = len(B1)
174 nbonds = len(bonds)
176 if 1: # init or (atoms.cell != self.atoms.cell).any():
177 self.X_cell[:] = np.dot(B1, cell)
178 self.B = np.empty((ncellparts + nbonds, 3))
179 self.B[:ncellparts] = np.dot(B2, cell)
181 if nbonds > 0:
182 P = atoms.positions
183 Af = self.images.repeat[:, np.newaxis] * cell
184 a = P[bonds[:, 0]]
185 b = P[bonds[:, 1]] + np.dot(bonds[:, 2:], Af) - a
186 d = (b**2).sum(1)**0.5
187 r = 0.65 * self.get_covalent_radii()
188 x0 = (r[bonds[:, 0]] / d).reshape((-1, 1))
189 x1 = (r[bonds[:, 1]] / d).reshape((-1, 1))
190 self.X_bonds[:] = a + b * x0
191 b *= 1.0 - x0 - x1
192 b[bonds[:, 2:].any(1)] *= 0.5
193 self.B[ncellparts:] = self.X_bonds + b
195 def showing_bonds(self):
196 return self.window['toggle-show-bonds']
198 def showing_cell(self):
199 return self.window['toggle-show-unit-cell']
201 def toggle_show_unit_cell(self, key=None):
202 self.set_frame()
204 def update_labels(self):
205 index = self.window['show-labels']
206 if index == 0:
207 self.labels = None
208 elif index == 1:
209 self.labels = list(range(len(self.atoms)))
210 elif index == 2:
211 self.labels = list(get_magmoms(self.atoms))
212 elif index == 4:
213 Q = self.atoms.get_initial_charges()
214 self.labels = [f'{q:.4g}' for q in Q]
215 else:
216 self.labels = self.atoms.get_chemical_symbols()
218 def show_labels(self):
219 self.update_labels()
220 self.draw()
222 def toggle_show_axes(self, key=None):
223 self.draw()
225 def toggle_show_bonds(self, key=None):
226 self.set_frame()
228 def toggle_show_velocities(self, key=None):
229 self.draw()
231 def get_forces(self):
232 if self.atoms.calc is not None:
233 try:
234 return self.atoms.get_forces()
235 except PropertyNotImplementedError:
236 pass
237 return np.zeros((len(self.atoms), 3))
239 def toggle_show_forces(self, key=None):
240 self.draw()
242 def hide_selected(self):
243 self.images.visible[self.images.selected] = False
244 self.draw()
246 def show_selected(self):
247 self.images.visible[self.images.selected] = True
248 self.draw()
250 def repeat_window(self, key=None):
251 return Repeat(self)
253 def rotate_window(self):
254 return Rotate(self)
256 def colors_window(self, key=None):
257 win = ColorWindow(self)
258 self.register_vulnerable(win)
259 return win
261 def focus(self, x=None):
262 cell = (self.window['toggle-show-unit-cell'] and
263 self.images[0].cell.any())
264 if (len(self.atoms) == 0 and not cell):
265 self.scale = 20.0
266 self.center = np.zeros(3)
267 self.draw()
268 return
270 # Get the min and max point of the projected atom positions
271 # including the covalent_radii used for drawing the atoms
272 P = np.dot(self.X, self.axes)
273 n = len(self.atoms)
274 covalent_radii = self.get_covalent_radii()
275 P[:n] -= covalent_radii[:, None]
276 P1 = P.min(0)
277 P[:n] += 2 * covalent_radii[:, None]
278 P2 = P.max(0)
279 self.center = np.dot(self.axes, (P1 + P2) / 2)
280 self.center += self.atoms.get_celldisp().reshape((3,)) / 2
281 # Add 30% of whitespace on each side of the atoms
282 S = 1.3 * (P2 - P1)
283 w, h = self.window.size
284 if S[0] * h < S[1] * w:
285 self.scale = h / S[1]
286 elif S[0] > 0.0001:
287 self.scale = w / S[0]
288 else:
289 self.scale = 1.0
290 self.draw()
292 def reset_view(self, menuitem):
293 self.axes = rotate('0.0x,0.0y,0.0z')
294 self.set_frame()
295 self.focus(self)
297 def set_view(self, key):
298 if key == 'Z':
299 self.axes = rotate('0.0x,0.0y,0.0z')
300 elif key == 'X':
301 self.axes = rotate('-90.0x,-90.0y,0.0z')
302 elif key == 'Y':
303 self.axes = rotate('90.0x,0.0y,90.0z')
304 elif key == 'Alt+Z':
305 self.axes = rotate('180.0x,0.0y,90.0z')
306 elif key == 'Alt+X':
307 self.axes = rotate('0.0x,90.0y,0.0z')
308 elif key == 'Alt+Y':
309 self.axes = rotate('-90.0x,0.0y,0.0z')
310 else:
311 if key == '3':
312 i, j = 0, 1
313 elif key == '1':
314 i, j = 1, 2
315 elif key == '2':
316 i, j = 2, 0
317 elif key == 'Alt+3':
318 i, j = 1, 0
319 elif key == 'Alt+1':
320 i, j = 2, 1
321 elif key == 'Alt+2':
322 i, j = 0, 2
324 A = complete_cell(self.atoms.cell)
325 x1 = A[i]
326 x2 = A[j]
328 norm = np.linalg.norm
330 x1 = x1 / norm(x1)
331 x2 = x2 - x1 * np.dot(x1, x2)
332 x2 /= norm(x2)
333 x3 = np.cross(x1, x2)
335 self.axes = np.array([x1, x2, x3]).T
337 self.set_frame()
339 def get_colors(self, rgb=False):
340 if rgb:
341 return [tuple(int(_rgb[i:i + 2], 16) / 255 for i in range(1, 7, 2))
342 for _rgb in self.get_colors()]
344 if self.colormode == 'jmol':
345 return [self.colors.get(Z, BLACKISH) for Z in self.atoms.numbers]
347 if self.colormode == 'neighbors':
348 return [self.colors.get(Z, BLACKISH)
349 for Z in self.get_color_scalars()]
351 colorscale, cmin, cmax = self.colormode_data
352 N = len(colorscale)
353 colorswhite = colorscale + ['#ffffff']
354 if cmin == cmax:
355 indices = [N // 2] * len(self.atoms)
356 else:
357 scalars = np.ma.array(self.get_color_scalars())
358 indices = np.clip(((scalars - cmin) / (cmax - cmin) * N +
359 0.5).astype(int),
360 0, N - 1).filled(N)
361 return [colorswhite[i] for i in indices]
363 def get_color_scalars(self, frame=None):
364 if self.colormode == 'tag':
365 return self.atoms.get_tags()
366 if self.colormode == 'force':
367 f = (self.get_forces()**2).sum(1)**0.5
368 return f * self.images.get_dynamic(self.atoms)
369 elif self.colormode == 'velocity':
370 return (self.atoms.get_velocities()**2).sum(1)**0.5
371 elif self.colormode == 'initial charge':
372 return self.atoms.get_initial_charges()
373 elif self.colormode == 'magmom':
374 return get_magmoms(self.atoms)
375 elif self.colormode == 'neighbors':
376 from ase.neighborlist import NeighborList
377 n = len(self.atoms)
378 nl = NeighborList(self.get_covalent_radii(self.atoms) * 1.5,
379 skin=0, self_interaction=False, bothways=True)
380 nl.update(self.atoms)
381 return [len(nl.get_neighbors(i)[0]) for i in range(n)]
382 else:
383 scalars = np.array(self.atoms.get_array(self.colormode),
384 dtype=float)
385 return np.ma.array(scalars, mask=np.isnan(scalars))
387 def get_covalent_radii(self, atoms=None):
388 if atoms is None:
389 atoms = self.atoms
390 return self.images.get_radii(atoms)
392 def draw(self, status=True):
393 self.window.clear()
394 axes = self.scale * self.axes * (1, -1, 1)
395 offset = np.dot(self.center, axes)
396 offset[:2] -= 0.5 * self.window.size
397 X = np.dot(self.X, axes) - offset
398 n = len(self.atoms)
400 # The indices enumerate drawable objects in z order:
401 self.indices = X[:, 2].argsort()
402 r = self.get_covalent_radii() * self.scale
403 if self.window['toggle-show-bonds']:
404 r *= 0.65
405 P = self.P = X[:n, :2]
406 A = (P - r[:, None]).round().astype(int)
407 X1 = X[n:, :2].round().astype(int)
408 X2 = (np.dot(self.B, axes) - offset).round().astype(int)
409 disp = (np.dot(self.atoms.get_celldisp().reshape((3,)),
410 axes)).round().astype(int)
411 d = (2 * r).round().astype(int)
413 vector_arrays = []
414 if self.window['toggle-show-velocities']:
415 # Scale ugly?
416 v = self.atoms.get_velocities()
417 if v is not None:
418 vector_arrays.append(v * 10.0 * self.velocity_vector_scale)
419 if self.window['toggle-show-forces']:
420 f = self.get_forces()
421 vector_arrays.append(f * self.force_vector_scale)
423 for array in vector_arrays:
424 array[:] = np.dot(array, axes) + X[:n]
426 colors = self.get_colors()
427 circle = self.window.circle
428 arc = self.window.arc
429 line = self.window.line
430 constrained = ~self.images.get_dynamic(self.atoms)
432 selected = self.images.selected
433 visible = self.images.visible
434 ncell = len(self.X_cell)
435 bond_linewidth = self.scale * 0.15
437 self.update_labels()
439 if self.arrowkey_mode == self.ARROWKEY_MOVE:
440 movecolor = GREEN
441 elif self.arrowkey_mode == self.ARROWKEY_ROTATE:
442 movecolor = PURPLE
444 for a in self.indices:
445 if a < n:
446 ra = d[a]
447 if visible[a]:
448 try:
449 kinds = self.atoms.arrays['spacegroup_kinds']
450 site_occ = self.atoms.info['occupancy'][str(kinds[a])]
451 # first an empty circle if a site is not fully occupied
452 if (np.sum([v for v in site_occ.values()])) < 1.0:
453 fill = '#ffffff'
454 circle(fill, selected[a],
455 A[a, 0], A[a, 1],
456 A[a, 0] + ra, A[a, 1] + ra)
457 start = 0
458 # start with the dominant species
459 for sym, occ in sorted(site_occ.items(),
460 key=lambda x: x[1],
461 reverse=True):
462 if np.round(occ, decimals=4) == 1.0:
463 circle(colors[a], selected[a],
464 A[a, 0], A[a, 1],
465 A[a, 0] + ra, A[a, 1] + ra)
466 else:
467 # jmol colors for the moment
468 extent = 360. * occ
469 arc(self.colors[atomic_numbers[sym]],
470 selected[a],
471 start, extent,
472 A[a, 0], A[a, 1],
473 A[a, 0] + ra, A[a, 1] + ra)
474 start += extent
475 except KeyError:
476 # legacy behavior
477 # Draw the atoms
478 if (self.moving and a < len(self.move_atoms_mask)
479 and self.move_atoms_mask[a]):
480 circle(movecolor, False,
481 A[a, 0] - 4, A[a, 1] - 4,
482 A[a, 0] + ra + 4, A[a, 1] + ra + 4)
484 circle(colors[a], selected[a],
485 A[a, 0], A[a, 1], A[a, 0] + ra, A[a, 1] + ra)
487 # Draw labels on the atoms
488 if self.labels is not None:
489 self.window.text(A[a, 0] + ra / 2,
490 A[a, 1] + ra / 2,
491 str(self.labels[a]))
493 # Draw cross on constrained atoms
494 if constrained[a]:
495 R1 = int(0.14644 * ra)
496 R2 = int(0.85355 * ra)
497 line((A[a, 0] + R1, A[a, 1] + R1,
498 A[a, 0] + R2, A[a, 1] + R2))
499 line((A[a, 0] + R2, A[a, 1] + R1,
500 A[a, 0] + R1, A[a, 1] + R2))
502 # Draw velocities and/or forces
503 for v in vector_arrays:
504 assert not np.isnan(v).any()
505 self.arrow((X[a, 0], X[a, 1], v[a, 0], v[a, 1]),
506 width=2)
507 else:
508 # Draw unit cell and/or bonds:
509 a -= n
510 if a < ncell:
511 line((X1[a, 0] + disp[0], X1[a, 1] + disp[1],
512 X2[a, 0] + disp[0], X2[a, 1] + disp[1]))
513 else:
514 line((X1[a, 0], X1[a, 1],
515 X2[a, 0], X2[a, 1]),
516 width=bond_linewidth)
518 if self.window['toggle-show-axes']:
519 self.draw_axes()
521 if len(self.images) > 1:
522 self.draw_frame_number()
524 self.window.update()
526 if status:
527 self.status(self.atoms)
529 def arrow(self, coords, width):
530 line = self.window.line
531 begin = np.array((coords[0], coords[1]))
532 end = np.array((coords[2], coords[3]))
533 line(coords, width)
535 vec = end - begin
536 length = np.sqrt((vec[:2]**2).sum())
537 length = min(length, 0.3 * self.scale)
539 angle = np.arctan2(end[1] - begin[1], end[0] - begin[0]) + np.pi
540 x1 = (end[0] + length * np.cos(angle - 0.3)).round().astype(int)
541 y1 = (end[1] + length * np.sin(angle - 0.3)).round().astype(int)
542 x2 = (end[0] + length * np.cos(angle + 0.3)).round().astype(int)
543 y2 = (end[1] + length * np.sin(angle + 0.3)).round().astype(int)
544 line((x1, y1, end[0], end[1]), width)
545 line((x2, y2, end[0], end[1]), width)
547 def draw_axes(self):
548 axes_length = 15
550 rgb = ['red', 'green', 'blue']
552 for i in self.axes[:, 2].argsort():
553 a = 20
554 b = self.window.size[1] - 20
555 c = int(self.axes[i][0] * axes_length + a)
556 d = int(-self.axes[i][1] * axes_length + b)
557 self.window.line((a, b, c, d))
558 self.window.text(c, d, 'XYZ'[i], color=rgb[i])
560 def draw_frame_number(self):
561 x, y = self.window.size
562 self.window.text(x, y, '{}'.format(self.frame),
563 anchor='SE')
565 def release(self, event):
566 if event.button in [4, 5]:
567 self.scroll_event(event)
568 return
570 if event.button != self.b1:
571 return
573 selected = self.images.selected
574 selected_ordered = self.images.selected_ordered
576 if event.time < self.t0 + 200: # 200 ms
577 d = self.P - self.xy
578 r = self.get_covalent_radii()
579 hit = np.less((d**2).sum(1), (self.scale * r)**2)
580 for a in self.indices[::-1]:
581 if a < len(self.atoms) and hit[a]:
582 if event.modifier == 'ctrl':
583 selected[a] = not selected[a]
584 if selected[a]:
585 selected_ordered += [a]
586 elif len(selected_ordered) > 0:
587 if selected_ordered[-1] == a:
588 selected_ordered = selected_ordered[:-1]
589 else:
590 selected_ordered = []
591 else:
592 selected[:] = False
593 selected[a] = True
594 selected_ordered = [a]
595 break
596 else:
597 selected[:] = False
598 selected_ordered = []
599 self.draw()
600 else:
601 A = (event.x, event.y)
602 C1 = np.minimum(A, self.xy)
603 C2 = np.maximum(A, self.xy)
604 hit = np.logical_and(self.P > C1, self.P < C2)
605 indices = np.compress(hit.prod(1), np.arange(len(hit)))
606 if event.modifier != 'ctrl':
607 selected[:] = False
608 selected[indices] = True
609 if (len(indices) == 1 and
610 indices[0] not in self.images.selected_ordered):
611 selected_ordered += [indices[0]]
612 elif len(indices) > 1:
613 selected_ordered = []
614 self.draw()
616 # XXX check bounds
617 natoms = len(self.atoms)
618 indices = np.arange(natoms)[self.images.selected[:natoms]]
619 if len(indices) != len(selected_ordered):
620 selected_ordered = []
621 self.images.selected_ordered = selected_ordered
623 def press(self, event):
624 self.button = event.button
625 self.xy = (event.x, event.y)
626 self.t0 = event.time
627 self.axes0 = self.axes
628 self.center0 = self.center
630 def move(self, event):
631 x = event.x
632 y = event.y
633 x0, y0 = self.xy
634 if self.button == self.b1:
635 x0 = int(round(x0))
636 y0 = int(round(y0))
637 self.draw()
638 self.window.canvas.create_rectangle((x, y, x0, y0))
639 return
641 if event.modifier == 'shift':
642 self.center = (self.center0 -
643 np.dot(self.axes, (x - x0, y0 - y, 0)) / self.scale)
644 else:
645 # Snap mode: the a-b angle and t should multipla of 15 degrees ???
646 a = x - x0
647 b = y0 - y
648 t = sqrt(a * a + b * b)
649 if t > 0:
650 a /= t
651 b /= t
652 else:
653 a = 1.0
654 b = 0.0
655 c = cos(0.01 * t)
656 s = -sin(0.01 * t)
657 rotation = np.array([(c * a * a + b * b, (c - 1) * b * a, s * a),
658 ((c - 1) * a * b, c * b * b + a * a, s * b),
659 (-s * a, -s * b, c)])
660 self.axes = np.dot(self.axes0, rotation)
661 if len(self.atoms) > 0:
662 com = self.X_pos.mean(0)
663 else:
664 com = self.atoms.cell.mean(0)
665 self.center = com - np.dot(com - self.center0,
666 np.dot(self.axes0, self.axes.T))
667 self.draw(status=False)
669 def render_window(self):
670 return Render(self)
672 def resize(self, event):
673 w, h = self.window.size
674 self.scale *= (event.width * event.height / (w * h))**0.5
675 self.window.size[:] = [event.width, event.height]
676 self.draw()