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(...)andscene.to_png(...); it does not depend on aViewerinstance or the current notebook/browser/window size.Positioned shapes include
SphereandStick. Useaddorsetwith CK objects, selections and styles for molecular/protein displays. Shapes can optionally be assigned a stringidso 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 withIPython.display. The optionalbackgroundargument followsscene.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_imageautomatically retries in an isolated Python subprocess. Google Colab uses the isolated software-rendering path automatically. SetCOSMOL_VIEWER_RENDER_ISOLATED=1to 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 toTrue.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 toTrue.
- 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 toTrue.
- 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_pngautomatically retries in an isolated Python subprocess. Google Colab uses the isolated software-rendering path automatically. SetCOSMOL_VIEWER_RENDER_ISOLATED=1to 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#ffffffor[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, orViewer.play(animation, width, height)to play an animation. Usescene.save_image(path, width, height)orscene.to_png(width, height)for static image output. Callviewer.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. ReturnsFalseafter the child process exits or the viewer is finalized. This does not read console input; usekeep_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 raisesKeyboardInterruptand 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.
- 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.
- 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
-1for 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
Animationconstructor 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
-1for 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
.cmvfile and passed toViewer.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¶
- class cosmol_viewer.Selector¶
- 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¶
- 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))
- 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)
- 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:
- 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¶