index | modules | gitlab | page source

# Visualization

`ase.visualize.``view`(atoms, data=None, viewer=None, repeat=None)

This provides an interface to various visualization tools, such as `ase.gui`, RasMol, VMD, gOpenMol, Avogadro, ParaView or NGLView. The default viewer is the ase.gui, described in the `ase.gui` module. The simplest invocation is:

    >>> from ase.visualize import view
    >>> view(atoms)

where `atoms` is any `Atoms` object. Alternative viewers can be used by specifying the optional keyword `viewer=...` - use one of ‘ase.gui’, ‘gopenmol’, ‘vmd’, ‘rasmol’, ‘paraview’, ‘ngl’. The VMD and Avogadro viewers can take an optional `data` argument to show 3D data, such as charge density:

    >>> view(atoms, viewer='VMD', data=...)

The nglview viewer additionally supports any indexible sequence of `Atoms` objects, e.g. lists of structures and `Trajectory` objects.

If you do not wish to open an interactive gui, but rather visualize your structure by dumping directly to a graphics file; you can use the `write` command of the `ase.io` module, which can write ‘eps’, ‘png’, and ‘pov’ files directly, like this:

    >>> from ase.io import write
    >>> write('image.png', atoms)

It is also possible to plot directly to a Matplotlib subplot object, which allows for a large degree of customisability. More information.

## Viewer for Jupyter notebooks

A simple viewer based on X3D is built into ASE, which should work on modern browsers without additional packages, by typing the following command into a Jupyter notebook:

    >>> view(atoms, viewer='x3d')

For a more feature-rich viewer, nglview is a dedicated viewer for the Jupyter notebook interface. It uses an embeddable NGL WebGL molecular viewer. The viewer works only in the web browser environment and embeds the live javascript output into the notebook. To utilize this functionality you need to have NGLView and ipywidgets packages installed in addition to the Jupyter notebook.

The basic usage provided by the `ase.visualize.view()` function exposes only small fraction of the NGL widget capabilities. The simplest form:

    >>> view(atoms, viewer='ngl')

creates interactive ngl viewer widget with the few additional control widgets added on the side. The object returned by the above call is a reference to the \(.gui\) member of the `ase.visualize.nglview.NGLDisplay` containing actual viewer (\(.view\) member), a reference to control widgets box (\(.control_box\) member) and `ase.visualize.view.nglview.NGLDisplay.custom_colors()` method. The notebook interface is not blocked by the above call and the returned object may be further manipulated by the following code in the separate cell (the \(_\) variable contains output from the previous cell):

    >>> v=_
    >>> v.custom_colors({'Mn':'green','As':'blue'})
    >>> v.view._remote_call("setSize", target="Widget", args=["400px", "400px"])
    >>> v.view.center_view()
    >>> v.view.background='#ffc'
    >>> v.view.parameters=dict(clipDist=-200)

The \(.view\) member exposes full API of the NGLView widget. The \(.control_box\) member is a `ipywidgets.HBox` containing `nglview.widget.NGLWidget` and `ipywidgets.VBox` with control widgets. For the full documentation of these objects consult the NGLView, NGL and ipywidgets websites.

class `ase.visualize.ngl.``NGLDisplay`(atoms, xsize=500, ysize=500)

  Structure display class

  Provides basic structure/trajectory display in the notebook and optional gui which can be used to enhance its usability. It is also possible to extend the functionality of the particular instance of the viewer by adding further widgets manipulating the structure.

  `custom_colors`(clr=None)

    Define custom colors for some atoms. Pass a dictionary of the form {‘Fe’:’red’, ‘Au’:’yellow’} to the function. To reset the map to default call the method without parameters.

`ase.visualize.ngl.``view_ngl`(atoms, w=500, h=500)

  Returns the nglviewer + some control widgets in the VBox ipywidget. The viewer supports any Atoms objectand any sequence of Atoms objects. The returned object has two shortcuts members:

  .view:
    nglviewer ipywidget for direct interaction
  .control_box:
    VBox ipywidget containing view control widgets

`NGLDisplay.``custom_colors`(clr=None)

  Define custom colors for some atoms. Pass a dictionary of the form {‘Fe’:’red’, ‘Au’:’yellow’} to the function. To reset the map to default call the method without parameters.

## Plotting iso-surfaces with Mayavi

The `ase.visualize.mlab.plot()` function can be used from the command-line:

    $ python -m ase.visualize.mlab abc.cube

to plot data from a cube-file or alternatively a wave function or an electron density from a calculator restart file:

    $ python -m ase.visualize.mlab -C gpaw abc.gpw

Options:

`ase.visualize.mlab.``plot`(atoms, data, contours)

  Plot atoms, unit-cell and iso-surfaces using Mayavi.

  Parameters:

  atoms: Atoms object
    Positions, atomiz numbers and unit-cell.
  data: 3-d ndarray of float
    Data for iso-surfaces.
  countours: list of float
    Contour values.

## PrimiPlotter

The PrimiPlotter is intended to do on-the-fly plotting of the positions of the atoms during long molecular dynamics simulations. The module `ase.visualize.primiplotter` contains the PrimiPlotter and the various output modules, see below.

class `ase.visualize.primiplotter.``PrimiPlotter`(atoms, verbose=0, timing=0, interval=1, initframe=0)

  Primitive PostScript-based plots during a simulation.

  The PrimiPlotter plots atoms during simulations, extracting the relevant information from the list of atoms. It is created using the list of atoms as an argument to the constructor. Then one or more output devices must be attached using set_output(device). The list of supported output devices is at the end.

  The atoms are plotted as circles. The system is first rotated using the angles specified by set_rotation([vx, vy, vz]). The rotation is vx degrees around the x axis (positive from the y toward the z axis), then vy degrees around the y axis (from x toward z), then vz degrees around the z axis (from x toward y). The rotation matrix is the same as the one used by RasMol.

  Per default, the system is scaled so it fits within the canvas (autoscale mode). Autoscale mode is enabled and disables using autoscale(“on”) or autoscale(“off”). A manual scale factor can be set with set_scale(scale), this implies autoscale(“off”). The scale factor (from the last autoscale event or from set_scale) can be obtained with get_scale(). Finally, an explicit autoscaling can be triggered with autoscale(“now”), this is mainly useful before calling get_scale or before disabling further autoscaling. Finally, a relative scaling factor can be set with SetRelativeScaling(), it is multiplied to the usual scale factor (from autoscale or from set_scale). This is probably only useful in connection with autoscaling.

  The radii of the atoms are obtained from the first of the following methods which work:

  1. If the radii are specified using PrimiPlotter.set_radii(r), they are used. Must be an array, or a single number.
  2. If the atoms has a get_atomic_radii() method, it is used. This is unlikely.
  3. If the atoms has a get_atomic_numbers() method, the corresponding covalent radii are extracted from the ASE.ChemicalElements module.
  4. If all else fails, the radius is set to 1.0 Angstrom.

  The atoms are colored using the first of the following methods which work.

  1. If colors are explicitly set using PrimiPlotter.set_colors(), they are used.
  2. If these colors are specified as a dictionary, the tags (from atoms.get_tags()) are used as an index into the dictionary to get the actual colors of the atoms.
  3. If a color function has been set using PrimiPlotter.set_color_function(), it is called with the atoms as an argument, and is expected to return an array of colors.
  4. If the atoms have a get_colors() method, it is used to get the colors.
  5. If these colors are specified as a dictionary, the tags (from atoms.get_tags()) are used as an index into the dictionary to get the actual colors of the atoms.
  6. If all else fails, the atoms will be white.

  The colors are specified as an array of colors, one color per atom. Each color is either a real number from 0.0 to 1.0, specifying a grayscale (0.0 = black, 1.0 = white), or an array of three numbers from 0.0 to 1.0, specifying RGB values. The colors of all atoms are thus a Numerical Python N-vector or a 3xN matrix.

  In cases 1a and 3a above, the keys of the dictionary are integers, and the values are either numbers (grayscales) or 3-vectors (RGB values), or strings with X11 color names, which are then translated to RGB values. Only in case 1a and 3a are strings recognized as colors.

  Some atoms may be invisible, and thus left out of the plot. Invisible atoms are determined from the following algorithm. Unlike the radius or the coloring, all points below are tried and if an atom is invisible by any criterion, it is left out of the plot.

  1. All atoms are visible.
  2. If PrimiPlotter.set_invisible() has be used to specify invisible atoms, any atoms for which the value is non-zero becomes invisible.
  3. If an invisiblility function has been set with PrimiPlotter.set_invisibility_function(), it is called with the atoms as argument. It is expected to return an integer per atom, any non-zero value makes that atom invisible.
  4. If a cut has been specified using set_cut, any atom outside the cut is made invisible.

  Note that invisible atoms are still included in the algorithm for positioning and scaling the plot.

  The following output devices are implemented.

  PostScriptFile(prefix): Create PS files names prefix0000.ps etc.

  PnmFile(prefix): Similar, but makes PNM files.

  GifFile(prefix): Similar, but makes GIF files.

  JpegFile(prefix): Similar, but makes JPEG files.

  X11Window(): Show the plot in an X11 window using ghostscript.

  Output devices writing to files take an extra optional argument to the constructor, compress, specifying if the output file should be gzipped. This is not allowed for some (already compressed) file formats.

  Instead of a filename prefix, a filename containing a % can be used. In that case the filename is expected to expand to a real filename when used with the Python string formatting operator (%) with the frame number as argument. Avoid generating spaces in the file names: use e.g. %03d instead of %3d.

  Parameters to the constructor:

  atoms: The atoms to be plottet.

  verbose = 0: Write progress information to stderr.

  timing = 0: Collect timing information.

  interval = 1: If specified, a plot is only made every interval’th time update() is called. Deprecated, normally you should use the interval argument when attaching the plotter to e.g. the dynamics.

  initframe = 0: Initial frame number, i.e. the number of the first plot.

  `log`(message)

    logs a message to the file set by set_log.

  `plot`()

    Create a plot now. Does not respect the interval timer.

    This method makes a plot unconditionally. It does not look at the interval variable, nor is this plot taken into account in the counting done by the update() method if an interval variable was specified.

  `set_color_function`(colors)

    Set a color function, to be used to color the atoms.

  `set_colors`(colors)

    Explicitly set the colors of the atoms.

    The colors can either be a dictionary mapping tags to colors or an array of colors, one per atom.

    Each color is specified as a greyscale value from 0.0 to 1.0 or as three RGB values from 0.0 to 1.0.

  `set_dimensions`(dims)

    Set the size of the canvas (a 2-tuple).

  `set_invisibility_function`(invfunc)

    Set an invisibility function.

  `set_invisible`(inv)

    Choose invisible atoms.

  `set_log`(log)

    Sets a file for logging.

    log may be an open file or a filename.

  `set_output`(device)

    Attach an output device to the plotter.

  `set_radii`(radii)

    Set the atomic radii. Give an array or a single number.

  `set_rotation`(rotation)

    Set the rotation angles (in degrees).

  `update`(newatoms=None)

    Cause a plot (respecting the interval setting).

    update causes a plot to be made. If the interval variable was specified when the plotter was create, it will only produce a plot with that interval. update takes an optional argument, newatoms, which can be used to replace the list of atoms with a new one.

## FieldPlotter

The FieldPlotter is intended to plot fields defined on the atoms in large-scale simulations. The fields could be e.g. pressure, stress or temperature (kinetic energy), i.e. any quantity that in a given simulation is best defined on a per-atom basis, but is best interpreted as a continuum field.

The current version of FieldPlotter only works if the number of atoms is at least 5-10 times larger than the number of pixels in the plot.

class `ase.visualize.fieldplotter.``FieldPlotter`(atoms, datasource=None, verbose=0, timing=0, interval=1, initframe=0)
  `log`(message)

    logs a message to the file set by set_log.

  `plot`(data=None)

    Create a plot now. Does not respect the interval timer.

    This method makes a plot unconditionally. It does not look at the interval variable, nor is this plot taken into account in the counting done by the update() method if an interval variable was specified.

    If data is specified, it must be an array of numbers with the same length as the atoms. That data will then be plotted. If no data is given, the data source specified when creating the plotter is used.

  `set_background`(value)

    Set the data value of the background. See also set_background_color

    Set the value of the background (parts of the plot without atoms) to a specific value, or to ‘min’ or ‘max’ representing the minimal or maximal data values on the atoms.

    Calling set_background cancels previous calls to set_background_color.

  `set_background_color`(color)

    Set the background color. See also set_background.

    Set the background color. Use a single value in the range [0, 1[ for gray values, or a tuple of three such values as an RGB color.

    Calling set_background_color cancels previous calls to set_background.

  `set_black_white_colors`(reverse=False)

    Set the color to Black-White (greyscale)

  `set_color_function`(colors)

    Set a color function, to be used to color the atoms.

  `set_colors`(colors, reverse=False)

    Explicitly set the colors of the atoms.

    The colors can either be a dictionary mapping tags to colors or an array of colors, one per atom.

    Each color is specified as a greyscale value from 0.0 to 1.0 or as three RGB values from 0.0 to 1.0.

  `set_data_range`(range1, range2=None)

    Set the range of the data used when coloring.

    This function sets the range of data values mapped unto colors in the final plot.

    Three possibilities:

    ‘data’: Autoscale using the data on visible atoms.
      The range goes from the lowest to the highest value present on the atoms. If only a few atoms have extreme values, the entire color range may not be used on the plot, as many values may be averaged on each point in the plot.
    ‘plot’: Autoscale using the data on the plot. Unlike ‘data’
      this guarantees that the entire color range is used.

    min, max: Use the range [min, max]

  `set_dimensions`(dims)

    Set the size of the canvas (a 2-tuple).

  `set_invisibility_function`(invfunc)

    Set an invisibility function.

  `set_invisible`(inv)

    Choose invisible atoms.

  `set_log`(log)

    Sets a file for logging.

    log may be an open file or a filename.

  `set_output`(device)

    Attach an output device to the plotter.

  `set_plot_plane`(plane)

    Set the plotting plane to xy, xz or yz (default: xy)

  `set_radii`(radii)

    Set the atomic radii. Give an array or a single number.

  `set_red_yellow_colors`(reverse=False)

    Set colors to Black-Red-Yellow-White (a.k.a. STM colors)

  `set_rotation`(rotation)

    Set the rotation angles (in degrees).

  `update`(newatoms=None)

    Cause a plot (respecting the interval setting).

    update causes a plot to be made. If the interval variable was specified when the plotter was create, it will only produce a plot with that interval. update takes an optional argument, newatoms, which can be used to replace the list of atoms with a new one.

## Matplotlib

    >>> import matplotlib.pyplot as plt
    >>> from ase.visualize.plot import plot_atoms
    >>> from ase.lattice.cubic import FaceCenteredCubic
    >>> slab = FaceCenteredCubic('Au', size=(2, 2, 2))
    >>> fig, ax = plt.subplots()
    >>> plot_atoms(slab, ax, radii=0.3, rotation=('90x,45y,0z'))
    >>> fig.savefig("ase_slab.png")

The data is plotted directly to a Matplotlib subplot object, giving a large degree of customizability.

    >>> import matplotlib.pyplot as plt
    >>> from ase.visualize.plot import plot_atoms
    >>> from ase.lattice.cubic import FaceCenteredCubic
    >>> slab = FaceCenteredCubic('Au', size=(2, 2, 2))
    >>> fig, axarr = plt.subplots(1, 4, figsize=(15, 5))
    >>> plot_atoms(slab, axarr[0], radii=0.3, rotation=('0x,0y,0z'))
    >>> plot_atoms(slab, axarr[1], scale=0.7, offset=(3, 4), radii=0.3, rotation=('0x,0y,0z'))
    >>> plot_atoms(slab, axarr[2], radii=0.3, rotation=('45x,45y,0z'))
    >>> plot_atoms(slab, axarr[3], radii=0.3, rotation=('0x,0y,0z'))
    >>> axarr[0].set_title("No rotation")
    >>> axarr[1].set_xlabel("X-axis, [$\mathrm{\AA}$]")
    >>> axarr[1].set_ylabel("Y-axis, [$\mathrm{\AA}$]")
    >>> axarr[2].set_axis_off()
    >>> axarr[3].set_xlim(2, 6)
    >>> axarr[3].set_ylim(2, 6)
    >>> fig.savefig("ase_slab_multiple.png")

    >>> stem_image = mpimg.imread("stem_image.jpg")
    >>> atom_pos = [(0.0, 0.0, 0.0), (0.5, 0.5, 0.5), (0.5, 0.5, 0.0)]
    >>> srtio3 = crystal(['Sr','Ti','O'], atom_pos, spacegroup=221, cellpar=3.905, size=(3, 3, 3))
    >>> fig, ax = plt.subplots()
    >>> ax.imshow(stem_image, cmap='gray')
    >>> plot_atoms(srtio3, ax, radii=0.3, scale=6.3, offset=(47, 54), rotation=('90x,45y,56z'))
    >>> ax.set_xlim(0, stem_image.shape[0])
    >>> ax.set_ylim(0, stem_image.shape[1])
    >>> ax.set_axis_off()
    >>> fig.tight_layout()
    >>> fig.savefig("iomatplotlib3.png")

Documentation v: 3.19.0

Versions
  3.20.0b1 (development)
  3.19.0 (latest stable)