Coverage for ase/io/utils.py: 89.15%
341 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
1from abc import ABC, abstractmethod
2from collections.abc import Callable, Iterator
3from itertools import islice
4from typing import IO
6import numpy as np
8from ase import Atoms
9from ase.data import atomic_numbers, covalent_radii
10from ase.data.colors import jmol_colors as default_colors
11from ase.io.formats import index2range, string2index
12from ase.utils import irotate, rotate
15def normalize(a):
16 return np.array(a) / np.linalg.norm(a)
19def complete_camera_vectors(look=None, up=None, right=None):
20 """Creates the camera (or look) basis vectors from user input and
21 will autocomplete missing vector or non-orthogonal vectors using dot
22 products. The look direction will be maintained, up direction has higher
23 priority than right direction"""
25 # ensure good input
26 if look is not None:
27 assert len(look) == 3
28 l = np.array(look)
30 if up is not None:
31 assert len(up) == 3
32 u = np.array(up)
34 if right is not None:
35 assert len(right) == 3
36 r = np.array(right)
38 if look is not None and up is not None:
39 r = normalize(np.cross(l, u))
40 u = normalize(np.cross(r, l)) # ensures complete perpendicularity
41 l = normalize(np.cross(u, r))
42 elif look is not None and right is not None:
43 u = normalize(np.cross(r, l))
44 r = normalize(np.cross(l, u)) # ensures complete perpendicularity
45 l = normalize(np.cross(u, r))
46 elif up is not None and right is not None:
47 l = normalize(np.cross(u, r))
48 r = normalize(np.cross(l, u)) # ensures complete perpendicularity
49 u = normalize(np.cross(r, u))
50 else:
51 raise ValueError("""At least two camera vectors of <look>, <up>,
52 or <right> must be specified""")
53 return l, u, r
56def get_cell_vertex_points(cell, disp=(0.0, 0.0, 0.0)):
57 """Returns 8x3 list of the cell vertex coordinates"""
58 cell_vertices = np.empty((2, 2, 2, 3))
59 displacement = np.array(disp)
61 for c1 in range(2):
62 for c2 in range(2):
63 for c3 in range(2):
64 cell_vertices[c1, c2, c3] = [c1, c2, c3] @ cell + displacement
66 return cell_vertices.reshape((8, 3))
69def update_line_order_for_atoms(L, T, D, atoms, radii):
70 # why/how does this happen before the camera rotation???
71 R = atoms.get_positions()
72 r2 = radii**2
73 for n in range(len(L)):
74 d = D[T[n]]
75 if (
76 (((R - L[n] - d) ** 2).sum(1) < r2)
77 & (((R - L[n] + d) ** 2).sum(1) < r2)
78 ).any():
79 T[n] = -1
80 return T
83def combine_bboxes(bbox_a, bbox_b):
84 """Combines bboxes using their extrema"""
85 bbox_low = np.minimum(bbox_a[0], bbox_b[0])
86 bbox_high = np.maximum(bbox_a[1], bbox_b[1])
87 return np.array([bbox_low, bbox_high])
90def has_cell(atoms):
91 return atoms.cell.rank > 0
94HIDE = 0
95SHOW_CELL = 1
96SHOW_CELL_AND_FIT_TO_ALL = 2
97SHOW_CELL_AND_FIT_TO_CELL = 3
100class PlottingVariables:
101 # removed writer - self
102 def __init__(
103 self,
104 atoms,
105 rotation='',
106 show_unit_cell=2,
107 radii=None,
108 bbox=None,
109 colors=None,
110 scale=20,
111 maxwidth=500,
112 extra_offset=(0.0, 0.0),
113 auto_bbox_size=1.05,
114 auto_image_plane_z='front_all',
115 ):
117 assert show_unit_cell in (0, 1, 2, 3)
118 """Handles camera/paper space transformations used for rendering, 2D
119 plots, ...and a few legacy features. after camera rotations, the image
120 plane is set to the front of structure.
122 atoms: Atoms object
123 The Atoms object to render/plot.
125 rotation: string or 3x3 matrix
126 Controls camera rotation. Can be a string with euler angles in
127 degrees like '45x, 90y, 0z' or a rotation matrix.
128 (defaults to '0x, 0y, 0z')
130 show_unit_cell: int 0, 1, 2, or 3
131 0 cell is not shown, 1 cell is shown, 2 cell is shown and bounding
132 box is computed to fit atoms and cell, 3 bounding box is fixed to
133 cell only. (default 2)
135 radii: list of floats
136 a list of atomic radii for the atoms. (default None)
138 bbox: list of four floats
139 Allows explicit control of the image plane bounding box in the form
140 (xlo, ylo, xhi, yhi) where x and y are the horizontal and vertical
141 axes of the image plane. The units are in atomic coordinates without
142 the paperspace scale factor. (defaults to None the automatic
143 bounding box is used)
145 colors : a list of RGB color triples
146 a list of the RGB color triples for each atom. (default None, uses
147 Jmol colors)
149 scale: float
150 The ratio between the image plane units and atomic units, e.g.
151 Angstroms per cm. (default 20.0)
153 maxwidth: float
154 Limits the width of the image plane. (why?) Uses paperspace units.
155 (default 500)
157 extra_offset: (float, float)
158 Translates the image center in the image plane by (x,y) where x and
159 y are the horizontal and vertical shift distances, respectively.
160 (default (0.0, 0.0)) should only be used for small tweaks to the
161 automatically fit image plane
163 auto_bbox_size: float
164 Controls the padding given to the bounding box in the image plane.
165 With auto_bbox_size=1.0 the structure touches the edges of the
166 image. auto_bbox_size>1.0 gives whitespace padding. (default 1.05)
168 auto_image_plane_z: string ('front_all', 'front_auto', 'legacy')
169 After a camera rotation, controls where to put camera image plane
170 relative to the atoms and cell. 'front_all' puts everything in front
171 of the camera. 'front_auto' sets the image plane location to
172 respect the show_unit_cell option so that the atoms or cell can be
173 ignored when setting the image plane. 'legacy' leaves the image
174 plane passing through the origin for backwards compatibility.
175 (default: 'front_all')
176 """
178 self.show_unit_cell = show_unit_cell
179 self.numbers = atoms.get_atomic_numbers()
180 self.maxwidth = maxwidth
181 self.atoms = atoms
182 # not used in PlottingVariables, keeping for legacy
183 self.natoms = len(atoms)
185 self.auto_bbox_size = auto_bbox_size
186 self.auto_image_plane_z = auto_image_plane_z
187 self.offset = np.zeros(3)
188 self.extra_offset = np.array(extra_offset)
190 self.constraints = atoms.constraints
191 # extension for partial occupancies
192 self.frac_occ = False
193 self.tags = None
194 self.occs = None
196 if 'occupancy' in atoms.info:
197 self.occs = atoms.info['occupancy']
198 self.tags = atoms.get_tags()
199 self.frac_occ = True
201 # colors
202 self.colors = colors
203 if colors is None:
204 ncolors = len(default_colors)
205 self.colors = default_colors[self.numbers.clip(max=ncolors - 1)]
207 # radius
208 if radii is None:
209 radii = covalent_radii[self.numbers]
210 elif isinstance(radii, float):
211 radii = covalent_radii[self.numbers] * radii
212 else:
213 radii = np.array(radii)
215 self.radii = radii # radius in Angstroms
216 self.scale = scale # Angstroms per cm
218 self.set_rotation(rotation)
219 self.update_image_plane_offset_and_size_from_structure(bbox=bbox)
221 def to_dict(self):
222 out = {
223 'bbox': self.get_bbox(),
224 'rotation': self.rotation,
225 'scale': self.scale,
226 'colors': self.colors,
227 }
228 return out
230 @property
231 def d(self):
232 # XXX hopefully this can be deprecated someday.
233 """Returns paperspace diameters for scale and radii lists"""
234 return 2 * self.scale * self.radii
236 def set_rotation(self, rotation):
237 if rotation is not None:
238 if isinstance(rotation, str):
239 rotation = rotate(rotation)
240 self.rotation = rotation
241 self.update_patch_and_line_vars()
243 def update_image_plane_offset_and_size_from_structure(self, bbox=None):
244 """Updates image size to fit structure according to show_unit_cell
245 if bbox=None. Otherwise, sets the image size from bbox. bbox is in the
246 image plane. Note that bbox format is (xlo, ylo, xhi, yhi) for
247 compatibility reasons the internal functions use (2,3)"""
249 # zero out the offset so it's not involved in the
250 # to_image_plane_positions() calculations which are used to calcucate
251 # the offset
252 self.offset = np.zeros(3)
254 # computing the bboxes in self.atoms here makes it easier to follow the
255 # various options selection/choices later
256 bbox_atoms = self.get_bbox_from_atoms(self.atoms, self.d / 2)
257 if has_cell(self.atoms):
258 cell = self.atoms.get_cell()
259 disp = self.atoms.get_celldisp().flatten()
260 bbox_cell = self.get_bbox_from_cell(cell, disp)
261 bbox_combined = combine_bboxes(bbox_atoms, bbox_cell)
262 else:
263 bbox_combined = bbox_atoms
265 # bbox_auto is the bbox that matches the show_unit_cell option
266 if has_cell(self.atoms) and self.show_unit_cell in (
267 SHOW_CELL_AND_FIT_TO_ALL,
268 SHOW_CELL_AND_FIT_TO_CELL,
269 ):
270 if self.show_unit_cell == SHOW_CELL_AND_FIT_TO_ALL:
271 bbox_auto = bbox_combined
272 else:
273 bbox_auto = bbox_cell
274 else:
275 bbox_auto = bbox_atoms
277 #
278 if bbox is None:
279 middle = (bbox_auto[0] + bbox_auto[1]) / 2
280 im_size = self.auto_bbox_size * (bbox_auto[1] - bbox_auto[0])
281 # should auto_bbox_size pad the z_heght via offset?
283 if im_size[0] > self.maxwidth:
284 rescale_factor = self.maxwidth / im_size[0]
285 im_size *= rescale_factor
286 self.scale *= rescale_factor
287 middle *= rescale_factor # center should be rescaled too
288 offset = middle - im_size / 2
289 else:
290 width = (bbox[2] - bbox[0]) * self.scale
291 height = (bbox[3] - bbox[1]) * self.scale
293 im_size = np.array([width, height, 0])
294 offset = np.array([bbox[0], bbox[1], 0]) * self.scale
296 # this section shifts the image plane up and down parallel to the look
297 # direction to match the legacy option, or to force it allways touch the
298 # front most objects regardless of the show_unit_cell setting
299 if self.auto_image_plane_z == 'front_all':
300 offset[2] = bbox_combined[1, 2] # highest z in image orientation
301 elif self.auto_image_plane_z == 'legacy':
302 offset[2] = 0
303 elif self.auto_image_plane_z == 'front_auto':
304 offset[2] = bbox_auto[1, 2]
305 else:
306 raise ValueError(
307 f'bad image plane setting {self.auto_image_plane_z!r}'
308 )
310 # since we are moving the origin in the image plane (camera coordinates)
311 self.offset += offset
313 # Previously, the picture size changed with extra_offset, This is very
314 # counter intuitive and seems like a bug. Leaving it commented out in
315 # case someone relying on this likely bug needs to revert it.
316 self.w = im_size[0] # + self.extra_offset[0]
317 self.h = im_size[1] # + self.extra_offset[1]
319 # allows extra_offset to be 2D or 3D
320 for i in range(len(self.extra_offset)):
321 self.offset[i] -= self.extra_offset[i]
323 # we have to update the arcane stuff after every camera update.
324 self.update_patch_and_line_vars()
326 def center_camera_on_position(self, pos, scaled_position=False):
327 if scaled_position:
328 pos = pos @ self.atoms.cell
329 im_pos = self.to_image_plane_positions(pos)
330 cam_pos = self.to_image_plane_positions(self.get_image_plane_center())
331 in_plane_shift = im_pos - cam_pos
332 self.offset[0:2] += in_plane_shift[0:2]
333 self.update_patch_and_line_vars()
335 def get_bbox(self):
336 xlo = self.offset[0]
337 ylo = self.offset[1]
338 xhi = xlo + self.w
339 yhi = ylo + self.h
340 return np.array([xlo, ylo, xhi, yhi]) / self.scale
342 def set_rotation_from_camera_directions(
343 self, look=None, up=None, right=None, scaled_position=False
344 ):
346 if scaled_position:
347 if look is not None:
348 look = look @ self.atoms.cell
349 if right is not None:
350 right = right @ self.atoms.cell
351 if up is not None:
352 up = up @ self.atoms.cell
354 look, up, right = complete_camera_vectors(look, up, right)
356 rotation = np.zeros((3, 3))
357 rotation[:, 0] = right
358 rotation[:, 1] = up
359 rotation[:, 2] = -look
360 self.rotation = rotation
361 self.update_patch_and_line_vars()
363 def get_rotation_angles(self):
364 """Gets the rotation angles from the rotation matrix in the current
365 PlottingVariables object"""
366 return irotate(self.rotation)
368 def get_rotation_angles_string(self, digits=5):
369 fmt = '%.{:d}f'.format(digits)
370 angles = self.get_rotation_angles()
371 outstring = (fmt + 'x, ' + fmt + 'y, ' + fmt + 'z') % (angles)
372 return outstring
374 def update_patch_and_line_vars(self):
375 """Updates all the line and path stuff that is still inobvious, this
376 function should be deprecated if nobody can understand why it's features
377 exist."""
378 cell = self.atoms.get_cell()
379 disp = self.atoms.get_celldisp().flatten()
380 positions = self.atoms.get_positions()
382 if self.show_unit_cell in (
383 SHOW_CELL,
384 SHOW_CELL_AND_FIT_TO_ALL,
385 SHOW_CELL_AND_FIT_TO_CELL,
386 ):
387 L, T, D = cell_to_lines(self, cell)
388 cell_verts_in_atom_coords = get_cell_vertex_points(cell, disp)
389 cell_vertices = self.to_image_plane_positions(
390 cell_verts_in_atom_coords
391 )
392 T = update_line_order_for_atoms(L, T, D, self.atoms, self.radii)
393 # D are a positions in the image plane,
394 # not sure why it's setup like this
395 D = (self.to_image_plane_positions(D) + self.offset)[:, :2]
396 positions = np.concatenate((positions, L), axis=0)
397 else:
398 L = np.empty((0, 3))
399 T = None
400 D = None
401 cell_vertices = None
402 # just a rotations and scaling since offset is currently [0,0,0]
403 image_plane_positions = self.to_image_plane_positions(positions)
404 self.positions = image_plane_positions
405 # list of 2D cell points in the imageplane without the offset
406 self.D = D
407 # integers, probably z-order for lines?
408 self.T = T
409 self.cell_vertices = cell_vertices
411 # no displacement since it's a vector
412 cell_vec_im = self.scale * self.atoms.get_cell() @ self.rotation
413 self.cell = cell_vec_im
415 def to_image_plane_positions(self, positions):
416 """Converts atomic coordinates to image plane positions. The third
417 coordinate is distance above/below the image plane"""
418 im_positions = (positions @ self.rotation) * self.scale - self.offset
419 return im_positions
421 def to_atom_positions(self, im_positions):
422 """Converts image plane positions to atomic coordinates."""
423 positions = (
424 (im_positions + self.offset) / self.scale
425 ) @ self.rotation.T
426 return positions
428 def get_bbox_from_atoms(self, atoms, im_radii):
429 """Uses supplied atoms and radii to compute the bounding box of the
430 atoms in the image plane"""
431 im_positions = self.to_image_plane_positions(atoms.get_positions())
432 im_low = (im_positions - im_radii[:, None]).min(0)
433 im_high = (im_positions + im_radii[:, None]).max(0)
434 return np.array([im_low, im_high])
436 def get_bbox_from_cell(self, cell, disp=(0.0, 0.0, 0.0)):
437 """Uses supplied cell to compute the bounding box of the cell in the
438 image plane"""
439 displacement = np.array(disp)
440 cell_verts_in_atom_coords = get_cell_vertex_points(cell, displacement)
441 cell_vertices = self.to_image_plane_positions(cell_verts_in_atom_coords)
442 im_low = cell_vertices.min(0)
443 im_high = cell_vertices.max(0)
444 return np.array([im_low, im_high])
446 def get_image_plane_center(self):
447 return self.to_atom_positions(np.array([self.w / 2, self.h / 2, 0]))
449 def get_atom_direction(self, direction):
450 c0 = self.to_atom_positions([0, 0, 0]) # self.get_image_plane_center()
451 c1 = self.to_atom_positions(direction)
452 atom_direction = c1 - c0
453 return atom_direction / np.linalg.norm(atom_direction)
455 def get_camera_direction(self):
456 """Returns vector pointing away from camera toward atoms/cell in atomic
457 coordinates"""
458 return self.get_atom_direction([0, 0, -1])
460 def get_camera_up(self):
461 """Returns the image plane up direction in atomic coordinates"""
462 return self.get_atom_direction([0, 1, 0])
464 def get_camera_right(self):
465 """Returns the image plane right direction in atomic coordinates"""
466 return self.get_atom_direction([1, 0, 0])
469def cell_to_lines(writer, cell):
470 # XXX this needs to be updated for cell vectors that are zero.
471 # Cannot read the code though! (What are T and D? nn?)
472 nlines = 0
473 nsegments = []
474 for c in range(3):
475 d = np.sqrt((cell[c] ** 2).sum())
476 n = max(2, int(d / 0.3))
477 nsegments.append(n)
478 nlines += 4 * n
480 positions = np.empty((nlines, 3))
481 T = np.empty(nlines, int)
482 D = np.zeros((3, 3))
484 n1 = 0
485 for c in range(3):
486 n = nsegments[c]
487 dd = cell[c] / (4 * n - 2)
488 D[c] = dd
489 P = np.arange(1, 4 * n + 1, 4)[:, None] * dd
490 T[n1:] = c
491 for i, j in [(0, 0), (0, 1), (1, 0), (1, 1)]:
492 n2 = n1 + n
493 positions[n1:n2] = P + i * cell[c - 2] + j * cell[c - 1]
494 n1 = n2
496 return positions, T, D
499def make_patch_list(writer):
500 from matplotlib.patches import Circle, PathPatch, Wedge
501 from matplotlib.path import Path
503 indices = writer.positions[:, 2].argsort()
504 patch_list = []
505 for a in indices:
506 xy = writer.positions[a, :2]
507 if a < writer.natoms:
508 r = writer.d[a] / 2
509 if writer.frac_occ:
510 site_occ = writer.occs[str(writer.tags[a])]
511 # first an empty circle if a site is not fully occupied
512 if (np.sum([v for v in site_occ.values()])) < 1.0:
513 # fill with white
514 fill = '#ffffff'
515 patch = Circle(xy, r, facecolor=fill, edgecolor='black')
516 patch_list.append(patch)
518 start = 0
519 # start with the dominant species
520 for sym, occ in sorted(
521 site_occ.items(), key=lambda x: x[1], reverse=True
522 ):
523 if np.round(occ, decimals=4) == 1.0:
524 patch = Circle(
525 xy, r, facecolor=writer.colors[a], edgecolor='black'
526 )
527 patch_list.append(patch)
528 else:
529 # jmol colors for the moment
530 extent = 360.0 * occ
531 patch = Wedge(
532 xy,
533 r,
534 start,
535 start + extent,
536 facecolor=default_colors[atomic_numbers[sym]],
537 edgecolor='black',
538 )
539 patch_list.append(patch)
540 start += extent
542 else:
543 # why are there more positions than atoms?
544 # is this related to the cell?
545 if (
546 (xy[1] + r > 0)
547 and (xy[1] - r < writer.h)
548 and (xy[0] + r > 0)
549 and (xy[0] - r < writer.w)
550 ):
551 patch = Circle(
552 xy, r, facecolor=writer.colors[a], edgecolor='black'
553 )
554 patch_list.append(patch)
555 else:
556 a -= writer.natoms
557 c = writer.T[a]
558 if c != -1:
559 hxy = writer.D[c]
560 patch = PathPatch(Path((xy + hxy, xy - hxy)))
561 patch_list.append(patch)
562 return patch_list
565class ImageChunk(ABC):
566 """Base class for a file chunk with enough information to make ``Atoms``."""
568 @abstractmethod
569 def build(self, *args, **kwargs) -> Atoms:
570 """Construct ``Atoms`` from the stored information and return it."""
573class ImageIterator:
574 """Iterate over chunks, to return the corresponding Atoms objects.
575 Will only build the atoms objects which corresponds to the requested
576 indices when called.
577 Assumes ``ichunks`` is in iterator, which returns ``ImageChunk``
578 type objects. See extxyz.py:iread_xyz as an example.
579 """
581 def __init__(self, ichunks: Callable[..., Iterator[ImageChunk]]) -> None:
582 self.ichunks = ichunks
584 def __call__(self, fd: IO, index=None, **kwargs) -> Iterator[Atoms]:
585 if isinstance(index, str):
586 index = string2index(index)
588 if index is None or index == ':':
589 index = slice(None, None, None)
591 if not isinstance(index, (slice, str)):
592 index = slice(index, (index + 1) or None)
594 for chunk in self._getslice(fd, index):
595 yield chunk.build(**kwargs)
597 def _getslice(self, fd: IO, indices: slice) -> Iterator[ImageChunk]:
598 iterator: Iterator[ImageChunk]
599 try:
600 iterator = islice(
601 self.ichunks(fd),
602 indices.start,
603 indices.stop,
604 indices.step,
605 )
606 except ValueError:
607 # Negative indices. Go through the whole thing to get the length,
608 # which allows us to evaluate the slice, and then read it again
609 if not hasattr(fd, 'seekable') or not fd.seekable():
610 msg = 'Negative indices only supported for seekable streams'
611 raise ValueError(msg)
612 startpos = fd.tell()
613 chunks = list(_ for _ in self.ichunks(fd))
614 nchunks = len(chunks)
615 fd.seek(startpos)
616 iterator = (chunks[_] for _ in index2range(indices, nchunks))
617 return iterator
620def verify_cell_for_export(cell, check_orthorhombric=True):
621 """Function to verify if the cell size is defined and if the cell is
623 Parameters
624 ----------
626 cell: cell object
627 cell to be checked.
629 check_orthorhombric: bool
630 If True, check if the cell is orthorhombric, raise an ``ValueError`` if
631 the cell is orthorhombric. If False, doesn't check if the cell is
632 orthorhombric.
634 Raise a ``ValueError`` if the cell if not suitable for export to mustem xtl
635 file or prismatic/computem xyz format:
636 - if cell is not orthorhombic (only when check_orthorhombric=True)
637 - if cell size is not defined
638 """
640 if check_orthorhombric and not cell.orthorhombic:
641 raise ValueError(
642 'To export to this format, the cell needs to be orthorhombic.'
643 )
644 if cell.rank < 3:
645 raise ValueError(
646 'To export to this format, the cell size needs '
647 'to be set: current cell is {}.'.format(cell)
648 )
651def verify_dictionary(atoms, dictionary, dictionary_name):
652 """
653 Verify a dictionary have a key for each symbol present in the atoms object.
655 Parameters
656 ----------
658 dictionary: dict
659 Dictionary to be checked.
662 dictionary_name: dict
663 Name of the dictionary to be displayed in the error message.
665 cell: cell object
666 cell to be checked.
669 Raise a ``ValueError`` if the key doesn't match the atoms present in the
670 cell.
671 """
672 # Check if we have enough key
673 for key in set(atoms.symbols):
674 if key not in dictionary:
675 raise ValueError(
676 'Missing the {} key in the `{}` dictionary.'.format(
677 key, dictionary_name
678 )
679 )
682def segment_list(data, segment_size):
683 """Segments a list into sublists of a specified size."""
684 return [
685 data[i : i + segment_size] for i in range(0, len(data), segment_size)
686 ]
689def validate_comment_line(comment: str, name: str = 'Comment line') -> str:
690 """Strip trailing whitespace and check for illegal characters."""
691 comment = comment.rstrip()
693 if '\n' in comment:
694 raise ValueError(f'{name} should not have line breaks.')
696 return comment
699def connectivity2bonds(connectivity: np.ndarray) -> list[tuple[int, int]]:
700 """Convert adjacency matrix to list of bonds (as tuple of atom indices)"""
701 idcs0, idcs1 = np.nonzero(np.triu(connectivity, k=1))
702 return list(zip(idcs0, idcs1))