Quick Start¶
Load a molecule, compose a scene, open an interactive view, and export an image. Choose Python or JavaScript above any code example to switch every example on this page. The URL records your choice, including when reloading or sharing a link.
Read a Molecule¶
Use COSMolKit to read an SDF file containing molecular coordinates. The examples
below use a file named molecule.sdf.
Follow the Installation instructions first. Place the SDF file in your script’s working directory.
from pathlib import Path
from cosmolkit import Molecule
from cosmol_viewer import Scene, Viewer
sdf = Path("molecule.sdf").read_text(encoding="utf-8")
molecule = Molecule.from_sdf(sdf)
Compose a Scene¶
Add the molecule and center the view on it. Molecules use ball-and-stick styling by default; proteins use cartoons. A selection is only needed when displaying a subset of atoms or residues.
scene = Scene()
scene.add(molecule)
scene.recenter_on(molecule)
Use add(item) to append content or set(name, item) to create or replace
named content. Both accept an optional style after the item.
Open an Interactive View¶
Open the scene in an interactive view to rotate and zoom the molecule.
In a notebook, the viewer appears inline. In a desktop Python script it opens a window. Keep the returned viewer if you want to update the scene.
viewer = Viewer.open(scene, width=800, height=500)
Export an Image¶
Export a PNG directly from the scene using offscreen rendering. Its size is independent of the interactive window; opening a viewer is optional for image export.
scene.save_image("molecule.png", width=1200, height=900)
In a desktop script, call viewer.keep_alive() after exporting if the
interactive window should remain open. In a notebook, use scene.display()
to show a static image inline. See Static and Offscreen Rendering for transparent PNGs and
in-memory output.