Visualization
atomli.visualize uses atomli’s browser viewer for structures, trajectories, and
volumetric fields. Notebook display and exported HTML share the same scene data.
Field contours, annotations, and camera controls are available in notebooks
and exported HTML; Jupyter also supports communication with a running kernel.
Jupyter notebooks
Section titled “Jupyter notebooks”Place a viewer last in a notebook cell:
from atomli.build import moleculefrom atomli.visualize import view
atoms = molecule("H2O")view(atoms)Viewer factories return displayable objects. Assignment alone does not display
a viewer. Use display(v) after assigning v = view(atoms).
This rule also applies to view_field and view_pdb.
End a live control call with ; to suppress another rich display of its return
value.
Display an HTML viewer once. Its controls update that output.
Basic HTML display does not require anywidget. The notebook must be trusted,
and the browser must reach tako.atom.li to load the renderer.
For kernel callbacks and direct PNG capture, install atomli[visualization]
and select widget=True.
Structures and trajectories
Section titled “Structures and trajectories”from atomli.io import readfrom atomli.visualize import view
frames = read("adsorption-fixed-host.extxyz", ":")v = view(frames, tags={0: "Li site", 4: "O"})display(v)v.write_html("adsorption.html")Trajectory viewer for constrained water adsorption
The frame selector and playback controls operate on saved geometries. Drag to
rotate and scroll to zoom. A bare Atoms value also displays a structure in a
notebook; its text representation remains unchanged.
Volumetric isosurfaces
Section titled “Volumetric isosurfaces”from atomli.visualize import view_fieldfrom atomli.analysis import Analysis
analysis = Analysis(atoms, shape=[41, 41, 41], margin=2.5)fields = analysis.fields("electron_density", charges=False)surface = view_field(atoms, fields, isovalue=0.06, opacity=0.65)display(surface)surface.set_slice(axis="z", position=0.5, style="both");surface.write_html("density.html")Electron density isosurface with live contour controls
isovalue uses the field’s declared units. surface="both" displays signed
orbital lobes. color_by=esp maps a registered second field onto the surface.
Contour and section changes reuse samples; geometry changes require resampling.
A batch can supply both the surface and its colors:
fields = analysis.fields(["rdg", "sign_lambda2_rho"], charges=False)view_field(atoms, fields, kind="rdg", isovalue=0.5, color_by="sign_lambda2_rho", colormap="diverging")Select kind= when a batch contains several fields.
rdg is the reduced density gradient.
sign_lambda2_rho is density times the sign of the middle Hessian eigenvalue.
Density, ESP, orbital, spin, and periodic examples.
Labels and measurements
Section titled “Labels and measurements”v = view(atoms, tags="index")display(v)v.add_distance(0, 4)v.add_angle(5, 4, 6)v.set_tags({0: "Li site", 4: "O"})v.set_bond_orders([{"i": 4, "j": 5, "order": 0.9}]);PBE water structure annotated with calculated Mulliken charges
The figure uses calculated PBE/def2-SVP Mulliken charges. Supplied labels do not
perform a population analysis. Distances use Å and angles use degrees. Atom
indices follow the input order. clear_annotations() removes the overlays.
Live driver updates
Section titled “Live driver updates”from atomli.optimize import BFGS
v = view(atoms)display(v)opt = BFGS(atoms)opt.attach(v.update, interval=1)if not opt.run(fmax=0.003, steps=160): raise RuntimeError("Optimization did not converge")v.write_html("optimization.html")Water g-xTB BFGS relaxation streamed into a trajectory viewer
The figure runs this snippet on H₂O with g-xTB, starting from stretched O–H bonds and an opened H–O–H angle. BFGS reaches fmax 0.003 eV/Å in 8 steps, giving 9 frames (energy falls by 1.51 eV, fmax from 5.5 to 0.001 eV/Å). Positions are in Å. Frame 0 is the input geometry; the second tab plots energy and fmax against step.
update() appends positions while retaining the camera and timeline. Species,
atom count, and cell topology must remain compatible. Outside a notebook, frames
remain available for HTML export. Volumetric viewers are bound to one sampled
geometry and reject trajectory updates.
Proteins and ligands
Section titled “Proteins and ligands”from atomli.visualize import view_pdb
v = view_pdb("3PTB.pdb", representation="cartoon", style="bTube", controls=["proteinRepresentation", "style"])display(v)ligand = v.find(resname="BEN") # benzamidine, drawn with the atom stylev.select(v.near(ligand, 4.0)); # Select whole residues within 4 Å.Trypsin (PDB 3PTB) as a cartoon with benzamidine and the residues around it selected
view_pdb takes a PDB path or text and draws the chains as "cartoon" (helices and
strand arrows), "tube", "trace" or "atoms". view and Viewer.set accept the same
option as protein_representation. Ligands and ions keep the atom style. Waters are removed
by default, and the crystal cell is off because its box would set the camera fit.
select, find and near use the atom order of the filtered PDB: index 0 is the first
kept ATOM or HETATM line. Use chains=["A"] to keep one chain.
Playback, camera, and appearance
Section titled “Playback, camera, and appearance”v.pause()v.set_frame(0)v.set_fps(12)v.select([4, 5, 6])v.set_view("front")v.reset_camera()v.set(background="white", style="bTube", atom_scale=75)v.play()| Control | Values or convention |
|---|---|
style | bTube, skeletal, flat, vdw, bubble |
background | white, light, black |
atom_scale, bond_scale | Percent of default size |
color_scheme | Supported element palette |
cell, axes, labels, bonds, polyhedra | Boolean visibility controls |
tags | Full sequence, index mapping, or "index" |
Snake-case Python names and documented camel-case aliases are accepted. Unknown
options raise. repeat=(2, 2, 1) creates a display supercell without mutating the
source structure. close() releases the mounted viewer.
Live updates with native workers
Section titled “Live updates with native workers”Display one widget and start the native MD worker:
from IPython.display import displayfrom atomli import unitsfrom atomli.md import VelocityVerletfrom atomli.visualize import view
viewer = view(atoms, widget=True)display(viewer)
dyn = VelocityVerlet(atoms, timestep=0.5 * units.fs)dyn.attach(viewer.update, interval=10)job = dyn.run(steps=200, background=True)run(..., background=True) returns immediately.
Rust owns the calculator and retains its electronic state throughout the run.
The notebook kernel publishes observer events automatically.
Native socket notifications wake the kernel when events become available.
Python structures, writers, and callbacks stay on their creating thread.
The native observer queue holds at most two geometry packets.
The worker waits when that queue is full.
Observer events and trajectory records remain complete.
viewer.update() submits positions without waiting for the browser.
Rust keeps one message in flight and one replaceable pending display frame.
Browser acknowledgements release the next pending frame.
Intermediate display frames can be replaced.
viewer.stream_stats reports message counts, buffer bytes, replacements, and transport errors.
Browser errors stop the stream and appear in these statistics.
Later updates return False, so display failures do not stop MD or trajectory output.
Missing browser replies stop the stream after 30 seconds.
Widget updates transfer positions in one binary buffer.
Each frame contains 12 * number_of_atoms bytes.
The first update also sends the mounted geometry to initialize the trajectory.
Float32 matches the renderer’s position precision.
Stored structures and HTML exports retain their original coordinate precision.
The camera and WebGL context remain active.
The browser still updates bonds and renders the scene.
New single-structure widgets retain two frames by default.
Loaded trajectories retain their initial frame count.
An explicit max_frames sets the retained history limit.
Live updates require at least two retained frames in the current renderer.
Use a separate atomli.io.Trajectory writer to retain the full run.
Position updates require unchanged atom identities, cell vectors, and periodic flags.
dyn.run(steps) preserves the blocking ASE contract.
Call job.wait(timeout=30) in terminal scripts to publish events and collect the result.
job.done also publishes available events.
job.cancel() requests cancellation after the current native integration step.
A wait timeout leaves the job active.
Call cancel() and wait() to collect a cancelled job.
job.stats reports native elapsed time and queue measurements.
Observers can read state and write output.
Observers must not change atoms or replace the calculator during a background run.
Such changes stop the job and raise an error when the job is collected.
Background MD currently supports Lennard-Jones, GFN2-xTB, and g-xTB calculators.
Other calculators raise NotImplementedError when they cannot transfer retained state safely.
Geometry optimizers retain their existing blocking interface.
Sampled density fields require new field evaluation and a separate transfer path.
FieldViewer.update() remains unsupported.
Export and Jupyter communication
Section titled “Export and Jupyter communication”v.write_html("scene.html")v.save("figure.png", dpi=400)v.save("trajectory.gif", fps=12, every=2)HTML is written by Python. PNG/GIF rendering requires a live browser and uses its download flow. A GIF requires multiple frames.
With anywidget>=0.9,<1, a connected notebook can receive events and save captured
PNG bytes to the kernel’s filesystem:
from IPython.display import display
v = view(atoms, widget=True)v.on("select", lambda selection: print(selection))display(v)image = await v.capture_png("figure.png", dpi=300)Figures for documentation pages
Section titled “Figures for documentation pages”A script can write a figure description instead of HTML. A page then mounts the viewer
or plot as a native widget, with no iframe. Controls called on a Viewer in a script
(set_frame, play, set_fps, select, set_view, set_camera) are recorded and
replayed when the page mounts it.
v = Viewer(frames).set_fps(12).play()v.write_spec("figures/mode.json", structure_path="figures/mode.extxyz")Viewer.load(atoms) replaces the structure of a viewer. Plot.write_spec and
FieldViewer.write_spec write the same atomli.figure/1 format. A field spec carries
its contour, opacity, and slice controls.
Study collects headline numbers, linked figures, a table, and provenance in one
study.json. Selecting a plot point or a table row loads that state’s structure into the
viewer.
study = Study("water-modes", "Water modes", method="PBE/def2-SVP")study.fact("r_oh", 0.975, "Å", label="O–H bond", precision=3)study.figure("modes", spectrum)study.figure("structure", states["bend"])study.link("mode", source="modes", target="structure", states=states)study.provenance("Computed", "atomli QC, analytical Hessian")study.write("public/studies/water-modes")write raises when a study has no provenance entry or no figure. The
water modes example is built this way.
API reference · Scientific plots · Reproducible adsorption workflow