Skip to content

MolecularViewer

3D viewer for structures and trajectories: styles, bonds, cells and periodic images, polyhedra and rings, charge/magmom/fragment coloring, forces, fixed atoms, an energy plot, measurement, and PNG/GIF export.

See the Basic Visualization, Trajectory Animation, Solid-State Structures, Polyhedron & Ring Highlight, and Fragment Coloring examples for walkthroughs.

Constructor

For a large structure or trajectory, enable high-performance mode and use the Minimal style to reduce rendering work:

MolecularViewer("trajectory.extxyz", high_performance=True, style="minimal").show()

The default is False; the High performance sidebar toggle switches the renderer at runtime. Minimal, Cartoon, Default and Glossy use analytical atom/bond surfaces. Other styles and shadows retain standard rendering. Bond distance criteria and atom coordinates are unchanged.

During molecular trajectory playback, the mode prepares up to eight future frames on Web Workers. The player reports initial buffering and preparation errors. Cell/bond edits invalidate preparation; cell ranges and the interactive view persist. The HTML stays self-contained. Python and CLI inputs are still loaded eagerly, and all selected frames are embedded in the page. The eight-frame preparation window bounds prepared playback data, not input memory or HTML size; it is not unlimited streaming. Slice the input or use CLI -i to reduce the frames loaded.

For a conventional ball-and-stick view with less rendering work, use style="minimal". It retains element colors and rounded atoms, with thin neutral bonds, simple diffuse shading, and no outline or specular highlight. With high performance enabled it uses one analytical cylinder per bond instead of two element-colored halves. With the option off it uses low-resolution instanced meshes.

MolecularViewer(data, *, topology=None, index=":", format=None,
                topology_format=None, fragments=None, fragment_colors=None,
                fragment_opacities=None, annotations=None, theme=None, **settings)
Parameter Type Description Default
data Atoms, list[Atoms], trajectory, dict, str Structure(s) to show. A path reads every frame with ASE; a glob ("frames/*.xyz") reads every matching file; dicts are viewer frames (see MolecularData). Required
topology path or None Matching MD topology; data becomes a coordinate path or ordered list of paths. Requires aseview[md]. None
index int, slice, str Frame index or slice, applied per input file before retaining converted frames. ":"
format str or None Coordinate file format override. auto
topology_format str or None MD topology format override; requires topology. auto
fragments Sequence Per-atom fragment labels (e.g. ["a", "a", "b", "b"], each unique value is one fragment) or atom-index groups (e.g. [[0, 1], [2, 3]], atoms in no group keep element colors). Selects color_by="fragment" unless color_by is given. None
fragment_colors list or dict Per-fragment colors, in fragment order or keyed by label (e.g. {"b": "#ff0000"}; group index for index groups) None
fragment_opacities list or dict Per-fragment opacity in 0–1, in fragment order or keyed by label. Multiplied with opacity. None
annotations list[dict] or None Ordered box/caption records. An explicit list replaces metadata; [] disables it; None reads frame-local atoms.info["aseview_annotations"]. See Box annotations. None
theme str spring, simple, glass, dark or darkgreen; None uses get_theme() None
**settings Any viewer setting that applies to this viewer, e.g. style="glossy", show_cell=False, color_by="charge", layout="grid"

For example, MolecularViewer("trajectory.dcd", topology="system.pdb", index="::10") reads selected MD frames. These read controls are separate from viewer settings. See paired MD inputs for supported formats, metadata and atom-order requirements.

The most used settings:

Setting Description Default
style Atom/bond look: default, 2d, cartoon, neon, glossy, metallic, cinematic, bubble, rowan, grey, plus the -v3 variants (Styles) "cartoon"
atom_size, bond_thickness Atom radius scale and bond radius 0.4, 0.09
radius_contrast, radius_contrast_mode How much radii differ by element (0 = uniform) and the mapping (log/linear) 1, "log"
bond_threshold, bond_cutoffs Bond when distance < threshold × (r₁ + r₂); maximum per-pair detection distances in Å such as {"C-H": 1.2} require custom_bond_cutoffs=True 1.2
color_by element, charge, magmom or fragment "element"
color_scheme, element_colors Element palette (jmol, cpk, pymol, vmd) and per-element overrides such as {"O": "#ff0000"} "jmol"
show_cell, cell_repeat Unit cell and VESTA-style repeats, e.g. {"a": [0, 1], "b": [0, 1], "c": [0, 0]} True
show_boundary_atoms, show_bonded_neighbors Atoms on cell faces/edges/corners, and bonded neighbours across the cell False
show_polyhedron, polyhedron_pairs Coordination polyhedra, e.g. ["Ti-O"] (empty: chosen automatically) False
show_rings, show_h_bond Ring faces and hydrogen bonds False
show_forces, force_scale, show_constraint Force arrows and fixed-atom markers False
show_energy_plot, show_force_max_plot Energy per frame, plus Fmax on a second axis False, True
projection, rotation_mode, layout orthographic/perspective, trackball/orbit, single/grid
view_preset, view_direction, view_up Starting camera: x/y/z/a/b/c or an explicit direction such as [1, 1, 1] "auto"
trajectory_framing Fixed camera extent from "first" or all loaded frames ("all"); playback doesn't refit the camera "first"
fps Trajectory playback speed in frames per second 20

The full list, with ranges and which viewers accept each one, is in Viewer Settings.

Element visibility and opacity

Use element_visibility to hide an element and element_opacities to fade it:

MolecularViewer(
    atoms,
    element_visibility={"H": False},
    element_opacities={"C": 0.35, "O": 0.7},
    opacity=0.8,
).show()

The JavaScript names are elementVisibility and elementOpacities. Both maps default to {}: an unlisted element is visible with element opacity 1. Keys are case-sensitive element symbols, including X for a dummy site; visibility values are booleans and opacity values are finite numbers from 0 to 1. These controls work independently of color_by and element colors.

The Per-element opacity switch controls whether both maps apply. It defaults to on. Turn it off to use global opacity without element overrides; fragment and overlay structure opacity still apply. The saved element values return when enabled again. In Python use custom_element_appearance=False; in JavaScript use customElementAppearance: false.

In Visibility, each element has a checkbox and an opacity slider from 0 to 100%, in steps of 5%. Unchecking it retains its slider value; checking it again restores that opacity. The block's Reset clears both element maps. It leaves element colors, global opacity, fragment settings and the camera unchanged.

Effective atom alpha is the product of global opacity, element opacity, fragment opacity when assigned, and structure opacity in an overlay. For example, 0.8 * 0.35 * 0.5 = 0.14, regardless of the color mode. A hidden element or zero effective alpha removes its atoms from drawing and picking, and removes incident bonds. hide_hydrogens=True also keeps hydrogen hidden. Bond alpha is the smaller effective alpha of its two endpoints. Hiding and fading leave input symbols and coordinates unchanged.

Fully opaque atoms and bonds keep the fast instanced rendering path. Fractional primitives use more draw calls so they can be sorted from far to near for each camera, in both standard and high-performance modes. Large translucent structures can therefore cost more than opaque ones. Normal styles use alpha blending; Neon retains its additive appearance. Conventional sorting by primitive depth has limits where translucent surfaces intersect or surround one another: it does not provide order-independent transparency or glass refraction.

Maximum bond detection distances

MolecularViewer(
    atoms,
    custom_bond_cutoffs=True,
    bond_cutoffs={"C-H": 1.2, "H-H": 0},
).show()

bond_cutoffs supplies maximum bond detection distances in Å, active only with custom_bond_cutoffs=True. A pair is detected only when distance < cutoff; equality is excluded, and 0 disables that pair. Unlisted pairs retain the radius-based bond_threshold defaults. Pair order is irrelevant: "H-C" is stored in canonical alphabetical order as "C-H". The Per-pair cutoffs sidebar controls edit the same settings; turning custom mode off retains the map for later use. These settings change detected bonds, including periodic neighbours, without moving atoms or changing actual interatomic distances.

Charge and magnetic moment coloring

color_by="charge" needs per-atom charges (atoms.arrays["charges"] or atoms.info["charges"]); color_by="magmom" needs magnetic moments (atoms.arrays["magmoms"]/["initial_magmoms"] or atoms.info["magmom"]). Both use a fixed red–white–blue scale centered on zero with a colorbar; normalize_charges=True makes the scale symmetric around the largest magnitude, and show_charge_labels=True prints the values.

Fragment coloring

Fragments are resolved in this order:

  1. the fragments= argument
  2. ASE tags (atoms.set_tags(...)), ignored when every tag is equal (e.g. the all-zero default)
  3. atoms.info["fragments"]
  4. atoms.arrays["residuenames"] from PDB files or MD topologies

The first three sources accept a per-atom label list such as ["a", "a", "b", "b"] or a list of atom-index groups such as [[0, 1], [2, 3]] (group k is labelled k; atoms in no group keep their element color). Fragments are numbered in first-appearance order, shared across trajectory frames. The fragment_colormap setting picks the palette, and the sidebar edits single fragment colors and opacities.

Residue names group atoms by resname, regardless of residue number or chain; blank names stay unassigned. Original residue metadata remains in the per-atom arrays.

Fixed atoms

show_constraint=True marks atoms fixed by FixAtoms. In the serialized viewer data, fixed is an index list such as [0, 1, 2], not a boolean mask. Boolean or 3-axis selective-dynamics masks live under arrays.fixed or arrays.move_mask when they are present.

Disordered sites

ASE CIF occupancy metadata is kept: mixed or partially occupied sites are drawn as sectors, with a white vacancy sector when occupancies sum to less than one. Frames may carry a species list aligned with symbols, each site a list of {"symbol": str, "occupancy": float} entries. Element visibility and opacity use the site's identity in frame.symbols, rather than individual entries in species. Hiding that symbol hides the whole site; fading it applies to its occupied sectors. The vacancy marker remains opaque while the site is visible. These maps do not edit occupancies or independently hide a minority species within a site.

Polyhedra

With polyhedron_neighbors="shell" (default), vertices are the nearest coordination shell: atoms within (1 + polyhedron_tolerance) × the closest distance, periodic images included. "bonds" uses the drawn bonds instead. A polyhedron is drawn only when all of its vertex atoms are drawn, so enable show_bonded_neighbors or add cell repeats to close shells at the cell boundary.

Box annotations

Annotations draw a screen-aligned box around a selected atom group, with an optional caption. They don't move atoms or change bonds. MolecularViewer, LiteViewer, and view(..., annotations=...) accept the same records. Normal-mode, overlay, fragment-selector, and surface viewers don't support annotations.

from ase.build import molecule
from aseview import MolecularViewer

water = molecule("H2O")
cues = [{
    "id": "water-group",
    "selector": {"kind": "index", "values": [0, 1, 2]},
    "frames": {"start": 0, "stop": 1},
    "text": "Water molecule",
    "color": "#f59e0b",
}]
viewer = MolecularViewer(water, annotations=cues)

Each record accepts only these fields:

Field Contract
id Required nonempty string, unique within the explicit list or within one frame's metadata list.
selector Required {"kind": "index", "values": [0, 1]} or {"kind": "map", "array": "atom_map", "values": [13, 14]}. Values must be a nonempty list of distinct integers.
frames Explicit lists only: {"start": 0, "stop": 2} activates frames 0 and 1. The interval is half-open and must satisfy 0 <= start < stop <= number_of_loaded_frames. Omitted bounds default to 0 and the loaded frame count.
text Optional plain string. Omit it or use "" for a box without a caption. HTML and Markdown are displayed literally.
color Optional "#RRGGBB" box stroke and label background color; otherwise the annotation_color setting applies.

An index selector uses zero-based positions in each frame's atom list. It doesn't track chemical identity if that list is reordered. A map selector looks up positive integer labels in atoms.arrays["atom_map"], or another named per-atom array, independently in each frame. The array must have one scalar value per atom; 0 and None mean unassigned. Duplicate assigned labels are an error, even when the duplicated label isn't selected. Missing labels or an absent array omit those targets, never substitute positional indices. If no selected atoms are visible, neither the box nor its caption is drawn.

Ranges refer to the frames supplied to the viewer, after Python slicing or CLI -i selection and file concatenation. For example, [0, 1) on a trajectory loaded with -i ::2 selects its first loaded frame, not the first two frames of the original file. Invalid ranges and unknown record fields raise ValueError before HTML is written.

Frame-local ASE metadata

When annotations=None, each frame may supply its own list in atoms.info["aseview_annotations"]. Metadata records have the same fields except that frames is prohibited: a record applies only to the frame carrying it. Reusing an ID in different frames is allowed; the normalized payload prefixes it with frame-N:. Frames without the key contribute no annotations.

from ase.build import molecule
from aseview import MolecularViewer

water = molecule("H2O")
water.info["aseview_annotations"] = [{
    "id": "oxygen",
    "selector": {"kind": "index", "values": [0]},
    "text": "Oxygen",
}]
metadata_viewer = MolecularViewer(water)
disabled_viewer = MolecularViewer(water, annotations=[])

An explicit annotations=[...] replaces all frame metadata, rather than merging with it. Viewer construction leaves input coordinates, arrays, and metadata unchanged. Keep annotation records in your Python data or a JSON sidecar; Copy structure isn't an annotation-preservation workflow.

Drawing and export

Each active group has its own box, including when several groups overlap. The box encloses the projected visible atom radii plus annotation_padding, and follows camera rotation, pan, zoom, frame changes, and grid panels. Only loaded primary-cell atoms are targets; periodic replicas aren't annotated. Hidden or off-screen atoms don't contribute to the box.

Labels attach to the upper-left box edge without a gap, with a below-box fallback near the top edge. Their opaque background uses the box color and is sized to text plus padding rather than stretched to the full box width. Text wraps within the current panel. Crowded panels can move captions within the panel, shorten them with an ellipsis, or omit a caption when no space remains. Placement avoids other captions, not other boxes or molecular geometry. The font stack follows the theme at weight 700; black or white text is chosen for higher contrast against the label background. Box strokes default to 3 CSS pixels. To distinguish reaction intervals, assign a different record color to each interval; colors are not assigned automatically. Preserve an existing visualization's theme, masks and geometry when adding labels. Use show_annotations=False to hide all groups; appearance settings are annotation_color, annotation_line_width, annotation_padding, and annotation_font_size. See Viewer Settings for their ranges.

Standalone HTML and notebook viewing use the same annotation drawing as image export. Python save_png() opens a fresh view and exports loaded frame 0 with either backend="browser" or backend="native". The PNG toolbar button and browser toPNG() export the current frame and camera. GIF export draws cues for each sampled frame; step and max_frames can skip a short-lived cue. Labels remain opaque even on transparent PNG backgrounds. Choose step=1 and avoid thinning when every cue needs to appear. Native and browser font rasterization can differ.

For trajectories that move beyond the first frame's extent, opt into trajectory_framing="all". It fits a fixed camera extent to all loaded frames; "first" retains the default first-frame fit. Neither mode follows atoms or refits during playback. Annotation boxes follow the camera, but don't enlarge its fitted extent to reserve caption space.

See Trajectory annotations for a runnable Python and CLI example.

In the viewer

  • Toolbar: settings, reset view, view along x/y/z (a/b/c for crystals), grid layout, PNG and GIF export (scale, transparent background, file name, frame step), copy the current frame or every frame as xyz, extxyz, cif or POSCAR, and measure mode.
  • Measure (M): click up to four atoms to read a distance, an angle or a dihedral; Esc clears the selection.
  • Mouse: left-drag rotates, right-drag (or Shift+drag) pans, the wheel zooms.

Cell ranges

Enable Cell ranges in the periodic settings to crop between opposing cell faces. Drag either endpoint handle to resize the range, or drag the selected span to move both endpoints together while preserving its width. The interval stops at either envelope boundary; the Å readout, visible atoms and boundary planes follow the range.

Focus the selected span to move it with arrow keys: 1% of the envelope per press, or 10% with Shift. Home and End move the whole interval to the lower and upper bounds. The same span also supports touch dragging.

Methods

Open Measure (or press M) to type zero-based atom indices or pick atoms in the canvas. Two fields measure distance; + adds a third for an angle or a fourth for a dihedral. Save or Enter keeps the measurement and starts a new two-field draft. Each recorded row has its own visibility and delete controls. Measurements update with trajectory frames; hidden or missing atoms make the entire measurement unavailable until those atoms reappear.

Values controls numbers beside the measured distance and inside angle sectors, including PNG/GIF exports. View → Atom indices independently shows bare, depth-tested indices at atom centers. Enable them from Python with show_atom_indices=True. Clearing or leaving Measure preserves recorded measurements; loading replacement data clears them.

Every viewer has the same output methods.

Method Description
show(width="100%", height=600) Display inline in Jupyter (an iframe with the page as srcdoc)
get_html(title="aseview") The self-contained HTML page as a string (no network access needed)
save_html(filename, title="aseview") Write the page to a file
save_png(filename, *, width=None, height=None, scale=None, transparent=True, quality=None, timeout_ms=30000, browser_executable_path=None, backend="browser", node_executable_path=None, native_module_dir=None) Render headlessly and save a PNG
save_gif(filename, *, width=None, height=None, scale=None, fps=None, step=None, max_frames=None, timeout_ms=60000, browser_executable_path=None) Render sampled frames headlessly and save an animated GIF

viewer.settings holds the validated settings (camelCase keys) and viewer.data the frames.

Image export from Python

The default browser backend for save_png and save_gif needs the optional export dependency:

pip install "aseview[export]"
python -m playwright install chromium
viewer.save_png("molecule.png", width=1600, height=1200, scale=2, transparent=False)
viewer.save_gif("trajectory.gif", fps=15, step=2)

width and height set the page size in CSS pixels, scale multiplies it (quality="low" | "medium" | "high" is scale 1, 2 or 3 for PNG). step keeps every Nth frame and max_frames thins long trajectories. Both raise ImageExportError on failure. The export extra pins Playwright below 1.15 for CentOS 7/glibc 2.17 compatibility. The same exports are in the viewer toolbar, and the CLI has no image-export options.

For local PNG export without Chromium, use backend="native" after installing the optional Node/EGL runtime with python -m aseview.native install. It uses the same geometry, material shaders, lighting, camera and colormaps. Native width/height size the canvas directly. See native PNG installation for old-server build requirements and Canvas/driver differences.

Examples

Basic usage

from ase.io import read
from aseview import MolecularViewer

atoms = read("molecule.xyz")
MolecularViewer(atoms).show()

Custom styling

MolecularViewer(
    atoms,
    style="neon",
    atom_size=0.5,
    bond_thickness=0.15,
    background_color="#000000",
    view_preset="c",
).show()

Trajectory with forces

trajectory = read("md.xyz", index=":")
MolecularViewer(
    trajectory,
    show_forces=True,
    force_scale=2.0,
    show_energy_plot=True,
).show()

Partial charges

import numpy as np
from ase.build import molecule

water = molecule("H2O")
water.arrays["charges"] = np.array([-0.82, 0.41, 0.41])
MolecularViewer(water, color_by="charge", show_charge_labels=True).show()

Fragments

water = molecule("H2O")
ammonia = molecule("NH3")
ammonia.translate([3.0, 0.0, 0.0])
dimer = water + ammonia

MolecularViewer(
    dimer,
    fragments=["w"] * 3 + ["n"] * 4,
    fragment_colormap="viridis",
    fragment_colors={"n": "#ef4444"},
).show()

# Equivalent atom-index groups (atoms left out keep element colors).
MolecularViewer(dimer, fragments=[[0, 1, 2], [3, 4, 5, 6]]).show()

Crystal with polyhedra

from ase.build import bulk

nacl = bulk("NaCl", "rocksalt", a=5.64)
MolecularViewer(
    nacl,
    cell_repeat={"a": [0, 1], "b": [0, 1], "c": [0, 1]},
    show_boundary_atoms=True,
    show_polyhedron=True,
    polyhedron_pairs=["Na-Cl"],
).show()

Fixed atoms and hydrogen bonds

from ase.constraints import FixAtoms

atoms = read("surface.xyz")
atoms.set_constraint(FixAtoms(indices=list(range(12))))
MolecularViewer(atoms, show_constraint=True, show_h_bond=True, h_bond_threshold=2.8).show()

Save to file

MolecularViewer(atoms, style="glossy").save_html("molecule_viewer.html")