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