pymatgen.vis package

The vis package implements various visualization tools. For example, a VTK Structure viewer.

Submodules

pymatgen.vis.plotters module

This module defines generic plotters.

class SpectrumPlotter(xshift=0.0, yshift=0.0, stack=False, color_cycle=('qualitative', 'Set1_9'))[source]

Bases: object

Plot Spectrum objects and subclasses.

Note that the interface is extremely flexible given that there are many different ways in which people want to view spectra. The typical usage is:

# Initializes plotter with some optional args. Defaults are usually # fine, plotter = SpectrumPlotter()

# Adds a DOS (A kind of spectra) with a label. plotter.add_spectrum(“Total DOS”, dos)

# Alternatively, you can add a dict of DOSs. This is the typical # form returned by CompleteDos.get_spd/element/others_dos(). plotter.add_spectra({“dos1”: dos1, “dos2”: dos2})

Parameters:
  • xshift (float) – A shift that is applied to the x values. This is commonly used to shift to an arbitrary zero. e.g. zeroing at the Fermi energy in DOS, or at the absorption edge in XAS spectra. The same xshift is applied to all spectra.

  • yshift (float) – A shift that is applied to the y values. This is commonly used to displace spectra for easier visualization. Successive spectra are applied successive shifts.

  • stack (bool) – Whether to stack plots rather than simply plot them. For example, DOS plot can usually be stacked to look at the contribution of each orbital.

  • color_cycle (str) – Default color cycle to use. Note that this can be overridden.

add_spectra(spectra_dict, key_sort_func=None)[source]

Add a dictionary of Spectrum, with an optional sorting function for the keys.

Parameters:
  • spectra_dict – dict of {label: Spectrum}

  • key_sort_func – function used to sort the dos_dict keys.

add_spectrum(label, spectrum, color=None)[source]

Adds a Spectrum for plotting.

Parameters:
  • label (str) – Label for the Spectrum. Must be unique.

  • spectrum – Spectrum object

  • color (str) – This is passed on to matplotlib. e.g. “k–” indicates a dashed black line. If None, a color will be chosen based on the default color cycle.

get_plot(xlim=None, ylim=None)[source]

Get a matplotlib plot showing the DOS.

Parameters:
  • xlim – Specifies the x-axis limits. Set to None for automatic determination.

  • ylim – Specifies the y-axis limits.

save_plot(filename: str, **kwargs)[source]

Save matplotlib plot to a file.

Parameters:
  • filename (str) – Filename to write to. Must include extension to specify image format.

  • kwargs – passed to get_plot.

show(**kwargs)[source]

Show the plot using matplotlib.

pymatgen.vis.structure_vtk module

This module contains classes to wrap Python VTK to make nice molecular plots.

The default styling follows VESTA’s ball-and-stick model: spheres drawn at 40% of the ionic radius of each species, bonds split into two halves colored by their end atoms, and translucent coordination polyhedra colored by the central atom with their edges outlined.

class MultiStructuresInteractorStyle(parent: MultiStructuresVis)[source]

Bases: StructureInteractorStyle

Interactor for MultiStructureVis.

Initialize MultiStructuresInteractorStyle.

keyPressEvent(obj, event)[source]

Key press event.

class MultiStructuresVis(element_color_mapping: dict[str, Sequence[int]] | None = None, show_unit_cell: bool = True, show_bonds: bool = False, show_polyhedron: bool = False, poly_radii_tol_factor: float = 0.5, excluded_bonding_elements: Sequence[str] | None = None, animated_movie_options: dict[str, str | float] | None = None, **kwargs: Any)[source]

Bases: StructureVis

Visualization for multiple structures.

Parameters:
  • element_color_mapping – Optional color mapping for the elements, as a dict of {symbol: rgb tuple}. For example, {“Fe”: (255, 123,0), ….} If None is specified, VESTA’s color scheme is used.

  • show_unit_cell – Set to False to not show the unit cell boundaries. Defaults to True.

  • show_bonds – Set to True to show bonds. Defaults to False.

  • show_polyhedron – Set to True to show polyhedrons. Defaults to False.

  • poly_radii_tol_factor – The polyhedron and bonding code uses the ionic radii of the elements or species to determine if two atoms are bonded. This specifies a tolerance scaling factor such that atoms which are (1 + poly_radii_tol_factor) * sum of ionic radii apart are still considered as bonded.

  • excluded_bonding_elements – List of atom types to exclude from bonding determination. Defaults to an empty list. Useful when trying to visualize a certain atom type in the framework (e.g., Li in a Li-ion battery cathode material).

  • animated_movie_options (dict) – Options for animated movie. Defaults to DEFAULT_ANIMATED_MOVIE_OPTIONS.

  • kwargs – Other kwargs supported by StructureVis, e.g., offscreen.

DEFAULT_ANIMATED_MOVIE_OPTIONS: ClassVar[dict[str, str | float]] = {'looping_type': 'restart', 'number_of_loops': 1, 'time_between_frames': 0.1, 'time_between_loops': 1.0}[source]
apply_tags() → None[source]

Apply tags.

display_help() → None[source]

Display the help for various keyboard shortcuts.

display_info(info: str) → None[source]
Parameters:

info (str) – Information.

display_warning(warning: str) → None[source]
Parameters:

warning (str) – Warning.

erase_info() → None[source]

Erase all info.

erase_warning() → None[source]

Remove warnings.

set_animated_movie_options(animated_movie_options: dict[str, str | float] | None = None) → None[source]
Parameters:

animated_movie_options (dict) – Options for animated movie.

Raises:

ValueError – If an option is not one of DEFAULT_ANIMATED_MOVIE_OPTIONS.

set_structure(structure: Structure | Molecule, reset_camera: bool = True, to_unit_cell: bool = False) → None[source]

Add a structure to the visualizer.

Parameters:
  • structure – structure to visualize

  • reset_camera – Set to True to reset the camera to a default determined based on the structure.

  • to_unit_cell – Whether or not to fall back sites into the unit cell.

set_structures(structures: Sequence[Structure], tags: list[dict] | None = None) → None[source]

Add list of structures to the visualizer.

Parameters:
  • structures (list[Structures]) – structures to be visualized.

  • tags (list[dict]) – List of tags to be applied to the structures.

class StructureInteractorStyle(parent: StructureVis)[source]

Bases: object

A custom interactor style for visualizing structures.

Initialize StructureInteractorStyle.

keyPressEvent(obj, _event)[source]

Key press event.

leftButtonPressEvent(obj, event)[source]

Left mouse button press event.

leftButtonReleaseEvent(obj, event)[source]

Left mouse button release event.

mouseMoveEvent(obj, event)[source]

Mouse move event.

class StructureVis(element_color_mapping: dict[str, Sequence[int]] | None = None, show_unit_cell: bool = True, show_bonds: bool = False, show_polyhedron: bool = True, poly_radii_tol_factor: float = 0.5, excluded_bonding_elements: Sequence[str] | None = None, offscreen: bool = False, atom_radius_scale: float = 0.4, bond_radius: float = 0.1, polyhedron_opacity: float = 0.5)[source]

Bases: object

Structure visualization using VTK.

Constructs a Structure Visualization.

Parameters:
  • element_color_mapping – Optional color mapping for the elements, as a dict of {symbol: rgb tuple}. For example, {“Fe”: (255, 123,0), ….} If None is specified, VESTA’s color scheme is used.

  • show_unit_cell – Set to False to not show the unit cell boundaries. Defaults to True.

  • show_bonds – Set to True to show bonds. Defaults to False.

  • show_polyhedron – Set to True to show polyhedrons. Defaults to True.

  • poly_radii_tol_factor – The polyhedron and bonding code uses the ionic radii of the elements or species to determine if two atoms are bonded. This specifies a tolerance scaling factor such that atoms which are (1 + poly_radii_tol_factor) * sum of ionic radii apart are still considered as bonded.

  • excluded_bonding_elements – List of atom types to exclude from bonding determination. Defaults to an empty list. Useful when trying to visualize a certain atom type in the framework (e.g., Li in a Li-ion battery cathode material).

  • offscreen – Render without opening a window, e.g., to write images in scripts or on headless machines. show() is unavailable when True. Defaults to False.

  • atom_radius_scale – Spheres are drawn with radius atom_radius_scale * ionic radius. Defaults to 0.4, as in VESTA’s ball-and-stick model.

  • bond_radius – Radius of bond cylinders in Å. Defaults to 0.1.

  • polyhedron_opacity – Opacity of coordination polyhedra. Defaults to 0.5.

Useful keyboard shortcuts implemented.

h : Show help A/a : Increase/decrease cell by one unit vector in a-direction B/b : Increase/decrease cell by one unit vector in b-direction C/c : Increase/decrease cell by one unit vector in c-direction # : Toggle showing of polyhedrons - : Toggle showing of bonds [ : Decrease poly_radii_tol_factor by 0.05 ] : Increase poly_radii_tol_factor by 0.05 r : Reset camera direction o : Orthogonalize structure Up/Down : Rotate view along Up direction by 90 clock/anticlockwise Left/right : Rotate view along camera direction by 90 clock/anticlockwise

add_bonds(neighbors: Sequence[Site], center: Site, color: Sequence[float] | None = None, opacity: float | None = None, radius: float = 0.1) → None[source]

Adds bonds for a site.

Parameters:
  • neighbors – Neighbors of the site.

  • center – The site in the center for all bonds.

  • color – Color of the tubes representing the bonds. Defaults to None, which colors each half of a bond by the atom at that end, as in VESTA.

  • opacity – Opacity of the tubes representing the bonds

  • radius – Radius of tube s representing the bonds

add_edges(edges: Sequence[Sequence[Sequence[float]]], type: str = 'line', linewidth: float = 2, color: tuple[float, float, float] = (0.0, 0.0, 0.0)) → None[source]
Parameters:
  • edges (Sequence) – List of edges. Each edge is a list of two points.

  • type (str) – Type of the edge. Defaults to “line”. Unused.

  • linewidth (float) – Width of the line.

  • color (tuple[float, float, float]) – RGB color.

add_faces(faces: Sequence[Sequence[ArrayLike]], color: Sequence[float], opacity: float = 0.35) → None[source]

Adding face of polygon. Faces with more than three vertices are drawn as a fan of triangles around their centroid.

Parameters:
  • faces (list) – Coordinates of the faces.

  • color (tuple) – RGB color.

  • opacity (float) – Opacity

Raises:

ValueError – If a face has fewer than three vertices.

add_line(start: ArrayLike, end: ArrayLike, color: Sequence[float] = (0.5, 0.5, 0.5), width: float = 1) → None[source]

Adds a line.

Parameters:
  • start – Starting coordinates for line.

  • end – Ending coordinates for line.

  • color – Color for text as RGB. Defaults to grey.

  • width – Width of line. Defaults to 1.

add_partial_sphere(coords: ArrayLike, radius: float, color: Sequence[float], start: float = 0, end: float = 360, opacity: float = 1.0) → vtkPolyDataMapper[source]

Adding a partial sphere (to display partial occupancies.

Parameters:
  • coords (NDArray) – Coordinates

  • radius (float) – Radius of sphere

  • color (tuple) – RGB color of sphere

  • start (float) – Starting angle.

  • end (float) – Ending angle.

  • opacity (float) – Opacity.

Returns:

The mapper of the sphere.

Return type:

vtkPolyDataMapper

add_picker() → None[source]

Create a cell picker that shows information on picked sites next to them.

add_picker_fixed() → None[source]

Create a cell picker that shows information on picked sites in the corner of the window.

add_polyhedron(neighbors: Sequence[Site], center: Site, color: Sequence[float] | str, opacity: float = 1.0, draw_edges: bool = False, edges_color: Sequence[float] = (0.0, 0.0, 0.0), edges_linewidth: float = 2) → None[source]

Adds a polyhedron, drawn as the convex hull of its vertices. Coplanar vertices are drawn as a flat polygon. Fewer than three non-collinear vertices draw nothing.

Parameters:
  • neighbors – Neighbors of the polyhedron (the vertices).

  • center – The atom in the center of the polyhedron.

  • color – Color for the polyhedron as RGB, or “element” to use the color of the species with the highest occupancy on the central atom.

  • opacity – Opacity of the polyhedron

  • draw_edges – If set to True, a line will be drawn at each edge

  • edges_color – Color of the line for the edges

  • edges_linewidth – Width of the line drawn for the edges

add_site(site: Site) → None[source]

Add a site to the render window. The site is displayed as a sphere sized by the ionic radii of its species (see get_site_radius). Partially occupied sites are drawn as wedges of each species’ color in proportion to its occupancy, with any vacancy fraction in white.

Parameters:

site – Site to add.

add_text(coords: ArrayLike, text: str, color: Sequence[float] = (0, 0, 0)) → None[source]

Add text at a coordinate.

Parameters:
  • coords – Coordinates to add text at.

  • text – Text to place.

  • color – Color for text as RGB. Defaults to black.

add_triangle(neighbors: Sequence[Site], color: Sequence[float] | str, center: Site | None = None, opacity: float = 0.4, draw_edges: bool = False, edges_color: Sequence[float] = (0.0, 0.0, 0.0), edges_linewidth: float = 2) → None[source]

Adds a triangular surface between three atoms.

Parameters:
  • neighbors – Atoms between which a triangle will be drawn.

  • color – Color for triangle as RGB, or “element” to use the color of the central atom.

  • center – The “central atom” of the triangle

  • opacity – opacity of the triangle

  • draw_edges – If set to True, the a line will be drawn at each edge

  • edges_color – Color of the line for the edges

  • edges_linewidth – Width of the line drawn for the edges

Raises:

ValueError – If color is “element” and center is not provided.

display_help() → None[source]

Display the help for various keyboard shortcuts.

get_site_color(site: Site) → list[float][source]

RGB color (0-1) of the species with the highest occupancy on a site.

get_site_radius(site: Site, anion_symbols: set[str] | None = None) → float[source]

Radius (Å) of the sphere drawn for a site.

The occupancy-weighted mean ionic radius of the species on the site, scaled by atom_radius_scale.

Parameters:
  • site – Site to size.

  • anion_symbols – Symbols of elements treated as anions when they carry no oxidation state. Defaults to the most electronegative element of the last structure passed to set_structure.

Returns:

Sphere radius in Å.

Return type:

float

mapper_map: dict[source]
orthogonalize_structure() → None[source]

Orthogonalize the structure.

redraw(reset_camera: bool = False) → None[source]

Redraw the render window.

Parameters:

reset_camera – Set to True to reset the camera to a pre-determined default for each structure. Defaults to False.

rotate_view(axis_ind: int = 0, angle: float = 0) → None[source]

Rotate the camera view.

Parameters:
  • axis_ind – 0 rolls the camera about the view direction, 1 rotates it about the view-up vector (azimuth) and 2 about the horizontal screen axis (pitch). Defaults to 0.

  • angle – Angle to rotate by in degrees. Defaults to 0.

set_structure(structure: Structure | Molecule, reset_camera: bool = True, to_unit_cell: bool = True) → None[source]

Add a structure to the visualizer.

Parameters:
  • structure – structure to visualize

  • reset_camera – Set to True to reset the camera to a default determined based on the structure.

  • to_unit_cell – Whether or not to fall back sites into the unit cell.

show() → None[source]

Display the visualizer.

Raises:

RuntimeError – If the visualizer was created with offscreen=True.

structure: Structure | Molecule | None[source]
write_image(filename: str | Path = 'image.png', magnification: int = 1, image_format: str | None = None) → None[source]

Save render window to an image.

Parameters:
  • filename – file to save to. Defaults to image.png.

  • magnification – Use it to render high res images.

  • image_format – One of png, jpeg (jpg), tiff (tif) or bmp. Defaults to None, which infers the format from the extension of filename and falls back to png.

Raises:

ValueError – If the image format is not supported.

zoom(factor: float) → None[source]

Zoom the camera view by a factor.

get_ionic_radius(specie: Species | Element, anion_symbols: set[str] | None = None) → float[source]

Ionic radius (Å) of a species, used to size its sphere.

Species with an oxidation state use their Shannon ionic radius. Bare elements use their average anionic radius if they are listed in anion_symbols and their average cationic radius otherwise. Both fall back to the average ionic radius, then the atomic radius, then DEFAULT_IONIC_RADIUS.

Parameters:
  • specie – Element or Species.

  • anion_symbols – Symbols of elements to treat as anions when no oxidation state is set. Defaults to none.

Returns:

Ionic radius in Å.

Return type:

float

make_movie(structures: Sequence[Structure], output_filename: str | Path = 'movie.mp4', zoom: float = 1.0, fps: int = 20, bitrate: str = '10000k', quality: int = 1, **kwargs: Any) → None[source]

Generate a movie from a sequence of structures using vtk and ffmpeg.

Frames are rendered offscreen into a temporary directory. The camera is set from the first structure and kept fixed for the rest.

Parameters:
  • structures ([Structure]) – sequence of structures

  • output_filename (str) – filename for structure output. defaults to movie.mp4

  • zoom (float) – A zoom to be applied to the visualizer. Defaults to 1.0.

  • fps (int) – Frames per second for the movie. Defaults to 20.

  • bitrate (str) – Video bitrate. Defaults to “10000k” (fairly high quality).

  • quality (int) – A quality scale. Defaults to 1.

  • kwargs – Any kwargs supported by StructureVis to modify the images generated.

Raises:

RuntimeError – If ffmpeg is not on the PATH.