Python documentationView source ↗
On this page

Python API Reference

cosmol_viewer.binding_contract_json() → str

Return the JSON API contract, including language names and platform restrictions.

cosmol_viewer.select(source) → Selector

Import a CK object once and select directly from its native Rust snapshot. Live selectors, selections and Scenes share the import. To import edited data while an old snapshot is still in use, pass a new CK object (for example a copy).

class cosmol_viewer.Scene

A 3D scene container for visualizing molecular or geometric shapes.

This class allows adding, updating, and removing shapes in a scene, as well as modifying scene-level properties such as scale, camera, and background color. Static image export is also a scene-level operation via scene.save_image(...) and scene.to_png(...); it does not depend on a Viewer instance or the current notebook/browser/window size.

Positioned shapes include Sphere and Stick. Use add or set with CK objects, selections and styles for molecular/protein displays. Shapes can optionally be assigned a string id so they can be updated or removed later.

Examples

scene = Scene()
Members (26)
add(item, style=None) → None

Add a positioned shape, CK object or source-bound selection. Omitted styles use the core defaults: molecules use BallAndStick, proteins use Cartoon. Selections use BallAndStick (molecule atoms), Stick (bonds), Sphere (protein atoms), or Cartoon (residues). Shapes already carry their own style. The native source import is shared by selections and Scenes.

display(width=1200, height=900, background=None) → None

Display this scene as a static PNG in a notebook.

This method does not create an interactive viewer. It renders through the same offscreen path as scene.to_png(...) and displays the resulting PNG with IPython.display. The optional background argument follows scene.to_png(...).

recenter(center) → None

Recenter the scene at a given point.

Parameters:

center ([float, float, float]) – The new scene center as XYZ coordinates.

recenter_on(source) → None
remove_shape(id) → None

Remove a shape from the scene by its ID.

Parameters:

id (str) – The ID of the shape to remove.

rotate_camera(azimuth_delta, elevation_delta, roll_delta=0.0) → None

Rotate the current camera by orbit-style angle deltas.

Parameters:
  • azimuth_delta (float) – Horizontal angle delta in degrees.

  • elevation_delta (float) – Vertical angle delta in degrees.

  • roll_delta (float, optional) – Roll angle delta in degrees.

save_image(path, width=800, height=600, background=None) → None

Render this scene directly to a PNG file.

This path uses the native offscreen renderer and does not depend on a Viewer, notebook JavaScript, or the current display size. On platforms with a headless GL path, the in-process renderer avoids creating a GUI event loop. If the in-process renderer cannot be created after a native viewer has already run, save_image automatically retries in an isolated Python subprocess. Google Colab uses the isolated software-rendering path automatically. Set COSMOL_VIEWER_RENDER_ISOLATED=1 to force the isolated path elsewhere.

Parameters:
  • path (str or os.PathLike[str]) – Output PNG path.

  • width (int, optional) – Output image width in pixels.

  • height (int, optional) – Output image height in pixels.

  • background (str or [int, int, int] or [int, int, int, int], optional) – Export background. If omitted, use the scene background. Use "transparent" for a transparent PNG, a hex color such as #ffffff, #ffffffff, or an RGB/RGBA sequence.

set(name, item, style=None) → None

Create or replace named content; failed projections preserve the old content.

set_ambient_light(intensity) → None

Set the global ambient light strength.

Defaults to 0.55, matching the renderer’s previous hard-coded ambient term.

set_auto_rotate(enabled=True, speed=20.0) → None

Enable or disable automatic camera rotation for the scene.

Parameters:
  • enabled (bool, optional) – If True, the camera keeps orbiting around the current target while normal drag rotation remains enabled. Defaults to True.

  • speed (float, optional) – Horizontal orbit speed in degrees per second. Defaults to 20.0.

set_background_color(background_color) → None

Set the background color of the scene.

Parameters:

background_color (tuple[int, int, int] or str) – The background color as an RGB tuple or a hex string such as “#FFFFFF”.

set_camera_distance(distance) → None

Set the camera distance while keeping the current target and rotation.

set_camera_fov(fov) → None

Set the camera field of view in degrees.

set_camera_target(target) → None

Set the camera target while keeping the current distance and rotation.

set_camera_view(azimuth=0.0, elevation=0.0, roll=0.0, distance=35.0, target=Ellipsis, fov=15.0) → None

Set the camera with orbit-style angles.

Parameters:
  • azimuth (float, optional) – Horizontal camera angle in degrees around the target.

  • elevation (float, optional) – Vertical camera angle in degrees around the target.

  • roll (float, optional) – Camera roll in degrees.

  • distance (float, optional) – Distance from the camera to the target.

  • target ([float, float, float], optional) – XYZ point the camera looks at.

  • fov (float, optional) – Vertical field of view in degrees.

set_depth_cue(enabled=True) → None

Enable or disable depth cueing for the scene.

Depth cueing uses the ChimeraX model: fragments are linearly mixed toward the depth cue color according to camera-space depth. Depth cueing is disabled by default. When enabled, the default cue color follows the scene background color, so distant fragments fade out. It applies to molecules, ribbons, and protein surfaces.

set_depth_cue_color(color) → None

Set the depth cue color.

Parameters:

color (tuple[int, int, int] or str) – RGB color tuple or hex string such as "#FFFFFF". If unset, the scene background color is used.

set_depth_cue_range(start, end) → None

Set the fractional depth cue range.

Parameters:
  • start (float) – Fraction of the current scene depth range where dimming starts. Defaults to 0.5.

  • end (float) – Fraction of the current scene depth range where dimming reaches the depth cue color. Defaults to 1.0.

set_light_color(color) → None

Set the scene light color.

The color affects both ambient and directional light. The default light color is [255, 247, 247], matching the renderer’s previous hard-coded color.

Parameters:

color (tuple[int, int, int] or str) – RGB light color tuple or hex string such as "#fff7f7".

set_light_intensity(intensity) → None

Set the final directional light intensity multiplier.

Defaults to 1.0. Increasing this brightens the whole lit scene while keeping the current ambient, diffuse, specular, and light color settings.

set_lighting(ambient=0.55, diffuse=0.65, specular=1.0, intensity=1.0, color=None) → None

Set scene lighting parameters.

The defaults match the renderer’s historical hard-coded lighting, so calling this method with no arguments preserves the old appearance.

Parameters:
  • ambient (float, optional) – Global ambient light strength. Defaults to 0.55.

  • diffuse (float, optional) – Directional diffuse light strength. Defaults to 0.65.

  • specular (float, optional) – Multiplier for the existing material-dependent specular highlight curve. Defaults to 1.0.

  • intensity (float, optional) – Final directional light multiplier. Defaults to 1.0.

  • color (tuple[int, int, int] or str, optional) – RGB light color as a tuple or hex string such as "#fff7f7". Defaults to the previous light color [255, 247, 247].

set_scale(scale) → None

Set the global scale factor of the scene.

Parameters:

scale (float) – A positive scaling factor applied uniformly to all shapes.

set_transparent_background(enabled=True) → None

Enable or disable transparent scene background rendering.

Parameters:

enabled (bool, optional) – If True, render the scene background with alpha 0 so browser canvas content behind the viewer can show through. Defaults to True.

set_zoom_disabled(disabled=True) → None

Enable or disable interactive zooming for the scene.

Parameters:

disabled (bool, optional) – If True, mouse wheel and trackpad scroll zooming are ignored while drag rotation remains enabled. Defaults to True.

to_png(width=800, height=600, background=None) → bytes

Render this scene directly to PNG bytes.

This is useful in notebooks when you want to display or store an image without round-tripping through the browser canvas. On platforms with a headless GL path, the in-process renderer avoids creating a GUI event loop. If the in-process renderer cannot be created after a native viewer has already run, to_png automatically retries in an isolated Python subprocess. Google Colab uses the isolated software-rendering path automatically. Set COSMOL_VIEWER_RENDER_ISOLATED=1 to force the isolated path elsewhere.

Parameters:

background (str or sequence, optional) – If omitted, use the scene background. Use "transparent" for transparent PNG output or pass a color such as #ffffff or [255, 255, 255, 255].

use_black_background() → None

Set the background color of the scene to black.

class cosmol_viewer.Viewer

A viewer for interactively displaying 3D scenes in different runtime environments.

Depending on the runtime environment, the viewer automatically selects an appropriate backend:

  • Jupyter or Colab uses an inline WebAssembly canvas.

  • A Python script or terminal uses a native GUI window when supported.

Use Viewer.open(scene, width, height) to display a scene interactively, or Viewer.play(animation, width, height) to play an animation. Use scene.save_image(path, width, height) or scene.to_png(width, height) for static image output. Call viewer.keep_alive() at the end of a native script to wait until Enter is pressed or the viewer window closes.

Members (9)
camera_parameter_logging(enabled=True) → None

Enable or disable logging camera parameters whenever the viewer camera moves.

When enabled, viewer interaction logs one line of orbit-style camera parameters after drag, zoom, or auto-rotation changes the camera. The printed values can be passed back to scene.set_camera_view(...) to reproduce the view. Logging is disabled by default, and the angle conversion is only computed while this option is enabled.

Native viewers log to the terminal. Notebook viewers log to the browser console; the command is submitted without waiting for a browser response.

Parameters:

enabled (bool, optional) – Whether to print camera parameters on camera movement. Defaults to True.

static get_environment() → str

Get the current runtime environment.

Returns:

One of "Jupyter", "Colab", "Plain Script", "IPython-Terminal", "Other IPython", or "Unknown".

Return type:

str

is_open() → bool

Check whether the native viewer is still open without blocking.

Use while viewer.is_open(): for dynamic update loops. Returns False after the child process exits or the viewer is finalized. This does not read console input; use keep_alive() for the final blocking wait with Enter.

Raises:

RuntimeError – If called in Jupyter or Colab, where child-process status is unavailable.

keep_alive() → None

Keep a native viewer alive until Enter is pressed or its child process exits.

This blocks the calling thread, but releases the Python GIL during short waits. Enter or stdin EOF closes the child process. A normal child exit returns normally; an unsuccessful child exit or an I/O failure raises OSError. Ctrl+C raises KeyboardInterrupt and also closes the child process.

This is a finalization step: afterwards the viewer cannot be updated or reused, including when an error interrupts the wait.

Raises:
  • RuntimeError – If called in Jupyter or Colab, or on an already finalized viewer.

  • OSError – If console I/O fails or the child process exits unsuccessfully.

  • KeyboardInterrupt – If the wait is interrupted by Ctrl+C.

static open(scene, width, height) → Viewer

Open an interactive viewer for a 3D scene.

Parameters:
  • scene (Scene) – The scene to render.

  • width (float) – The viewport width in pixels.

  • height (float) – The viewport height in pixels.

Returns:

The created viewer instance.

Return type:

Viewer

static play(animation, width, height) → Viewer

Play an animation.

Parameters:
  • animation (Animation) – An animation object containing frames and playback settings.

  • width (float) – The viewport width in pixels.

  • height (float) – The viewport height in pixels.

Returns:

The created viewer instance playing the animation.

Return type:

Viewer

show_camera_parameters(enabled=True) → None

Show or hide live camera parameters in the upper-left corner.

Displays azimuth, elevation, roll (degrees), distance, target and field of view. Updates with camera interaction and does not intercept dragging or zooming. Independent of camera_parameter_logging(); enabling this does not log to the terminal or browser console. Supported in native windows, Jupyter and Colab.

Parameters:

enabled (bool, optional) – Whether to show camera parameters. Defaults to True; initially hidden.

show_fps(enabled=True) → None

Show or hide the renderer FPS overlay in the upper-left corner.

The value is the repaint rate averaged over half-second windows, not the animation frame rate or GPU timing. Samples existing repaint events only; does not request continuous repainting. After one second without activity, a one-shot repaint shows zero FPS; this diagnostic repaint is not counted and does not renew the idle timer. Supported in native windows, Jupyter and Colab.

Parameters:

enabled (bool, optional) – Whether to show FPS. Defaults to True; initially hidden.

update(scene) → None

Update the viewer with a new scene.

Parameters:

scene (Scene) – The updated scene.

Notes

In Jupyter or Colab, frequent animation updates may be limited by notebook rendering capacity, which can lead to delayed or incomplete rendering.

class cosmol_viewer.Animation(interval, loops, interpolate)

A container for handling frame-based animations in the viewer.

Parameters:
  • interval (float) – Time in seconds between frames.

  • loops (int) – Number of times to loop the animation. Use -1 for infinite looping.

  • interpolate (bool) – Whether to interpolate between frames for smoother visualization.

Examples

animation = Animation(interval=0.1, loops=-1, interpolate=True)
for _ in range(100):
    scene = Scene()
    scene.add(..)
    animation.add_frame(scene)

Viewer.play(animation, width=800.0, height=500.0)
Members (6)
add_frame(scene) → None

Add a frame to the animation.

Parameters:

scene (Scene) – A scene object representing a single frame of the animation.

set_interpolate(interpolate) → None

Enable or disable interpolation between animation frames.

Parameters:

interpolate (bool) – Whether to interpolate between compatible frames for smoother visualization.

set_interval(interval) → None

Set the time between animation frames.

Parameters:

interval (float) – Time in seconds between frames. This uses the same unit as the Animation constructor and takes effect when the animation is played.

set_loops(loops) → None

Set the number of animation loops.

Parameters:

loops (int) – Number of times to loop the animation. Use -1 for infinite looping.

set_static_scene(scene) → None

Set a static scene that remains constant throughout the animation.

Parameters:

scene (Scene) – A scene object to be rendered statically. This is useful for background elements or reference structures.

to_payload() → str

Serialize the animation into a versioned payload for direct browser playback.

The returned UTF-8 string can be written to a .cmv file and passed to Viewer.playNotebook(canvas_id, payload) in the WebAssembly frontend. Static scenes and frames are prepared for WebAssembly rendering in the serialized copy; this method does not modify the animation object.

Returns:

A CMV2 Base64-encoded postcard payload, optionally gzip-compressed.

Return type:

str

Raises:

RuntimeError – If the animation has no frames or cannot be serialized.

class cosmol_viewer.Selection
Members (3)
aromatic() → Selection
element(element) → Selection

Return a filtered native selection; the original selection is reusable.

ids: list[int]
class cosmol_viewer.Selector
Members (3)
atoms() → Selection
bonds() → Selection
residues() → Selection
class cosmol_viewer.BallAndStick
Members (8)
color(color) → BallAndStick
conformer(id) → BallAndStick
coordinates_2d() → BallAndStick
metallic(value) → BallAndStick
opacity(value) → BallAndStick
outline(color, width) → BallAndStick
roughness(value) → BallAndStick
scale(value) → BallAndStick
class cosmol_viewer.Cartoon
Members (5)
color(color) → Cartoon
metallic(value) → Cartoon
opacity(value) → Cartoon
rainbow_residues() → Cartoon
roughness(value) → Cartoon
class cosmol_viewer.Sphere(center, radius)

A sphere shape in the scene.

Parameters:
  • center ([float, float, float]) – The [x, y, z] coordinates of the sphere center.

  • radius (float) – The radius of the sphere.

Examples

sphere = Sphere([0, 0, 0], 1.0).color("\#FF0000")
sphere = Sphere([0, 0, 0], 1.0).color((255, 0, 0))
Members (6)
color(color) → Sphere

Set RGB/hex color and return this shape for chaining.

metallic(metallic) → Sphere

Set the metallic factor and return this shape for chaining.

opacity(opacity) → Sphere

Set surface opacity and return this shape for chaining.

roughness(roughness) → Sphere

Set surface roughness and return this shape for chaining.

set_center(center) → Sphere

Set the center of the sphere.

Parameters:

center ([float, float, float]) – The new center coordinates of the sphere.

Returns:

The updated sphere object.

Return type:

Sphere

set_radius(radius) → Sphere

Set the radius of the sphere.

Parameters:

radius (float) – The new radius of the sphere.

Returns:

The updated sphere object.

Return type:

Sphere

class cosmol_viewer.SphereStyle
Members (8)
color(color) → SphereStyle
conformer(id) → SphereStyle
coordinates_2d() → SphereStyle
metallic(value) → SphereStyle
opacity(value) → SphereStyle
outline(color, width) → SphereStyle
roughness(value) → SphereStyle
scale(value) → SphereStyle
class cosmol_viewer.Stick(start, end, thickness)

A cylindrical stick shape connecting two points.

Parameters:
  • start ([float, float, float]) – The starting point of the stick.

  • end ([float, float, float]) – The ending point of the stick.

  • thickness (float) – The radius or thickness of the stick.

Examples

stick = Stick([0, 0, 0], [1, 1, 1], 0.1).opacity(0.5)
Members (7)
color(color) → Stick

Set RGB/hex color and return this shape for chaining.

metallic(metallic) → Stick

Set the metallic factor and return this shape for chaining.

opacity(opacity) → Stick

Set surface opacity and return this shape for chaining.

roughness(roughness) → Stick

Set surface roughness and return this shape for chaining.

set_end(end) → Stick

Set the ending point of the stick.

Parameters:

end ([float, float, float]) – The new ending point.

Returns:

The updated stick object.

Return type:

Stick

set_start(start) → Stick

Set the starting point of the stick.

Parameters:

start ([float, float, float]) – The new starting point.

Returns:

The updated stick object.

Return type:

Stick

set_thickness(thickness) → Stick

Set the thickness of the stick.

Parameters:

thickness (float) – The new thickness of the stick.

Returns:

The updated stick object.

Return type:

Stick

class cosmol_viewer.StickStyle
Members (8)
color(color) → StickStyle
conformer(id) → StickStyle
coordinates_2d() → StickStyle
metallic(value) → StickStyle
opacity(value) → StickStyle
outline(color, width) → StickStyle
roughness(value) → StickStyle
scale(value) → StickStyle
class cosmol_viewer.Surface
Members (5)
color(color) → Surface
configure(probe_radius=1.4, grid_spacing=0.5, solvent_accessible=False, sharp_boundaries=True) → Surface
metallic(value) → Surface
opacity(value) → Surface
roughness(value) → Surface