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