API

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_shape(..)
    animation.add_frame(scene)

Viewer.play(animation, width=800.0, height=500.0)
add_frame(scene)

Add a frame to the animation.

Parameters:

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

set_static_scene(scene)

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.

class cosmol_viewer.Molecule

A molecular shape object.

This class is typically created from an SDF-format string parsed by COSMolKit.

Examples

content = open("structure.sdf", "r").read()
mol = Molecule.from_sdf(content).centered()
centered()

Center the molecule around the origin.

Returns:

The centered molecule object.

Return type:

Molecule

color(self, c: tuple[int, int, int]) Molecule
color(self, c: str) Molecule

Set the shape color.

disable_outline()

Disable the outline around this molecule.

Returns:

The updated molecule object.

Return type:

Molecule

enable_outline(color=None, width=None)

Enable an outline around this molecule.

Parameters:
  • color (tuple[int, int, int] or str, optional) – The outline color as an RGB tuple or a hex string. If omitted, the current outline color is kept.

  • width (float, optional) – The outline width in scene units. If omitted, the current outline width is kept.

Returns:

The updated molecule object.

Return type:

Molecule

static from_cosmolkit(molecule)

Create a viewer molecule from a Python cosmolkit.Molecule object.

The conversion is performed on the Rust side by exporting the COSMolKit molecule atoms, bonds, and coordinates into the viewer molecule format. 3D conformer coordinates are preferred over 2D coordinates. If the COSMolKit molecule has no stored coordinates, 2D coordinates are computed first.

Parameters:

molecule (cosmolkit.Molecule) – A molecule object from the Python cosmolkit package built against a compatible COSMolKit version.

Returns:

The converted viewer molecule object.

Return type:

Molecule

static from_sdf(sdf)

Create a molecule from an SDF-format string.

SDF parsing is delegated to COSMolKit; the viewer receives atoms, bonds, and coordinates from the parsed molecule.

Parameters:

sdf (str) – The SDF file content as a string.

Returns:

The parsed molecule object.

Return type:

Molecule

get_center()

Get the geometric center of the molecule.

Returns:

The center coordinates of the molecule.

Return type:

[float, float, float]

metallic(self, metallic: float) Molecule

Set the surface metallic factor.

opacity(self, opacity: float) Molecule

Set the surface opacity.

roughness(self, roughness: float) Molecule

Set the surface roughness.

set_outline(enabled, color=None, width=None)

Configure the molecule outline.

Parameters:
  • enabled (bool) – Whether to render an outline around this molecule.

  • color (tuple[int, int, int] or str, optional) – The outline color as an RGB tuple or a hex string. If omitted, the current outline color is kept.

  • width (float, optional) – The outline width in scene units. If omitted, the current outline width is kept.

Returns:

The updated molecule object.

Return type:

Molecule

class cosmol_viewer.Protein

A protein shape object.

This class is typically created from an mmCIF- or PDB-format string parsed by COSMolKit’s protein reader. The viewer core assigns secondary structure from backbone geometry and generates the displayed ChimeraX-style cartoon ribbon.

Examples

content = open("2AMD.cif", "r", encoding="utf-8").read()
prot = Protein.from_mmcif(content).centered().rainbow_residues()

Use .color("\#F9FAFB") for a uniform cartoon color.

centered()

Center the protein around the origin.

Returns:

The centered protein object.

Return type:

Protein

color(self, c: tuple[int, int, int]) Protein
color(self, c: str) Protein

Set the shape color.

static from_mmcif(mmcif)

Create a protein from an mmCIF-format string.

Parsing is delegated to COSMolKit’s protein reader. The viewer core assigns secondary structure from the resulting backbone geometry before mesh generation.

Parameters:

mmcif (str) – The mmCIF file content as a string.

Returns:

The parsed protein object.

Return type:

Protein

static from_pdb(pdb)

Create a protein from a PDB-format string.

Parsing is delegated to COSMolKit’s protein reader. The viewer core assigns secondary structure from the resulting backbone geometry before mesh generation.

Parameters:

pdb (str) – The PDB file content as a string.

Returns:

The parsed protein object.

Return type:

Protein

get_center()

Get the geometric center of the protein.

Returns:

The center coordinates of the protein.

Return type:

[float, float, float]

metallic(self, metallic: float) Protein

Set the surface metallic factor.

opacity(self, opacity: float) Protein

Set the surface opacity.

rainbow_residues()

Color the protein cartoon with ChimeraX-style rainbow coloring by residue.

Each biopolymer chain is colored independently from blue at the first rendered residue to red at the last rendered residue, matching ChimeraX rainbow / color sequential residues default behavior for cartoon ribbons.

Returns:

The updated protein object.

Return type:

Protein

roughness(self, roughness: float) Protein

Set the surface roughness.

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.

Supported shape types include Sphere, Stick, Molecule, and Protein. Shapes can optionally be assigned a string id so they can be updated or removed later.

Examples

scene = Scene()
add_shape(shape)

Add a shape to the scene without assigning an explicit ID.

Parameters:

shape (Sphere or Stick or Molecule or Protein) – A shape instance to add to the scene.

add_shape_with_id(id, shape)

Add a shape to the scene with a specific ID.

Parameters:
  • id (str) – A unique string identifier for the shape.

  • shape (Sphere or Stick or Molecule or Protein) – A shape instance to add to the scene.

Notes

If a shape with the same ID already exists, it is replaced.

display(width=800, height=600, background=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)

Recenter the scene at a given point.

Parameters:

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

remove_shape(id)

Remove a shape from the scene by its ID.

Parameters:

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

replace_shape(id, shape)

Replace an existing shape in the scene by its ID.

Parameters:
rotate_camera(azimuth_delta, elevation_delta, roll_delta=0.0)

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)

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.

Parameters:
  • path (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_auto_rotate(enabled=True, speed=20.0)

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)

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)

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

set_camera_fov(fov)

Set the camera field of view in degrees.

set_camera_target(target)

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)

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_scale(scale)

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)

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)

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)

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.

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()

Set the background color of the scene to black.

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))
color(self, c: tuple[int, int, int]) Sphere
color(self, c: str) Sphere

Set the shape color.

metallic(self, metallic: float) Sphere

Set the surface metallic factor.

opacity(self, opacity: float) Sphere

Set the surface opacity.

roughness(self, roughness: float) Sphere

Set the surface roughness.

set_center(center)

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)

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.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)
color(self, c: tuple[int, int, int]) Stick
color(self, c: str) Stick

Set the shape color.

metallic(self, metallic: float) Stick

Set the surface metallic factor.

opacity(self, opacity: float) Stick

Set the surface opacity.

roughness(self, roughness: float) Stick

Set the surface roughness.

set_end(end)

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)

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)

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.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.render(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.

static get_environment()

Get the current runtime environment.

Returns:

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

Return type:

str

static play(animation, width, height)

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

static render(scene, width, height)

Render 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

update(scene)

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.