C3D Module

Interactive 3D molecule viewer for Jupyter and Marimo notebooks.

C3D Class

class cnotebook.c3d.C3D(width=800, height=None, theme='auto')[source]

Bases: object

Interactive 3D molecule viewer for Jupyter and Marimo notebooks.

Provides a builder-style API for constructing a self-contained 3Dmol.js viewer that can be displayed inline in notebook cells.

Example:

from openeye import oechem
from cnotebook.c3d import C3D

mol = oechem.OEMol()
oechem.OESmilesToMol(mol, "c1ccccc1")

viewer = (
    C3D(width=800, height=600)
    .add_molecule(mol, name="benzene")
    .add_style("cartoon", {"chain": "A"})
    .set_background("#ffffff")
)
viewer.display()
Parameters:
  • width (int)

  • height (int | None)

  • theme (str)

__init__(width=800, height=None, theme='auto')[source]

Create a new C3D viewer instance.

Parameters:
  • width (int) – Viewer width in pixels.

  • height (int | None) – Viewer height in pixels. When None (the default), the height is chosen automatically: 300 px for small viewers, 500 px when the console is visible, or 600 px when the largest molecule has more than 1 000 atoms.

  • theme (str) – Color theme. "auto" detects from the host environment, "dark" or "light" sets explicitly.

add_molecule(mol, name=None, disabled=False)[source]

Add an OpenEye molecule to the viewer.

The molecule is converted to SDF format via convert_molecule(). If the molecule lacks 3D coordinates, conformer generation is attempted automatically.

Parameters:
  • mol (Any) – OpenEye molecule (OEMolBase subclass).

  • name (str | None) – Optional display name for the molecule.

  • disabled (bool) – If True, the molecule is hidden when the viewer starts. It can be made visible later via the sidebar.

Returns:

Self, for method chaining.

Raises:

TypeError – If mol is not an OEMolBase.

Return type:

C3D

add_design_unit(du, name=None, disabled=False)[source]

Add an OpenEye design unit to the viewer.

The design unit is converted to PDB format via convert_design_unit().

Parameters:
  • du (Any) – OpenEye design unit (OEDesignUnit).

  • name (str | None) – Optional display name for the design unit.

  • disabled (bool) – If True, the design unit is hidden when the viewer starts. It can be made visible later via the sidebar.

Returns:

Self, for method chaining.

Raises:

TypeError – If du is not an OEDesignUnit.

Return type:

C3D

add_molecules(mols, prefix=None, enable='first')[source]

Add multiple OpenEye molecules to the viewer.

Parameters:
  • mols (Iterable) – Iterable of OpenEye molecules (OEMolBase subclasses).

  • prefix (str | None) – Optional prefix prepended to each entry’s name via f"{prefix}{base_name}".

  • enable (str | Sequence[bool]) – Controls which entries are visible on load. "all" enables all, "first" enables only the first (default), or a Sequence[bool] where True means enabled. If the sequence is shorter than mols, remaining entries are disabled.

Returns:

Self, for method chaining.

Raises:
  • ValueError – If enable is an unrecognized string.

  • TypeError – If enable is not a string or Sequence.

Return type:

C3D

add_design_units(dus, prefix=None, enable='first')[source]

Add multiple OpenEye design units to the viewer.

Parameters:
  • dus (Iterable) – Iterable of OpenEye design units (OEDesignUnit).

  • prefix (str | None) – Optional prefix prepended to each entry’s name via f"{prefix}{base_name}".

  • enable (str | Sequence[bool]) – Controls which entries are visible on load. "all" enables all, "first" enables only the first (default), or a Sequence[bool] where True means enabled. If the sequence is shorter than dus, remaining entries are disabled.

Returns:

Self, for method chaining.

Raises:
  • ValueError – If enable is an unrecognized string.

  • TypeError – If enable is not a string or Sequence.

Return type:

C3D

add_style(style, selection=None, color=None)[source]

Add a visual style to apply to selected atoms.

Parameters:
  • style (str | Dict[str, Any]) – Either a preset name ("cartoon", "stick", "sphere", "line", "cross", "surface") or a raw 3Dmol.js style dict that is passed through verbatim.

  • selection (str | Dict[str, Any] | None) – Atoms to style. Can be None to style all atoms, a selection expression string (e.g. "chain A", "resn LIG"), an entry name to target a specific molecule, or a raw 3Dmol.js selection dict (e.g. {"chain": "A"}).

  • color (str | None) – Optional color string. When style is a preset name, this is set as the color key in the style spec. Ignored when style is a dict.

Returns:

Self, for method chaining.

Raises:

ValueError – If style is a string that is not a recognized preset name.

Return type:

C3D

Example:

viewer = C3D()
viewer.add_molecule(mol, name="benzene")

# Style everything
viewer.add_style("stick")

# Style by selection expression
viewer.add_style("cartoon", "chain A")

# Style a specific entry
viewer.add_style("sphere", "benzene")

# Style with a 3Dmol.js dict
viewer.add_style("stick", {"chain": "A"}, color="green")
remove_style(style, selection=None)[source]

Remove a visual style from selected atoms.

Parameters:
  • style (str | Dict[str, Any]) – Either a preset name accepted by add_style(), "everything" to clear all styles from the selection, or a raw 3Dmol.js style dict. For dicts, the top-level style keys are removed from the matching atoms.

  • selection (str | Dict[str, Any] | None) – Atoms to modify. Uses the same selection forms as add_style().

Returns:

Self, for method chaining.

Raises:

ValueError – If style is a string that is not a recognized preset name.

Return type:

C3D

Example:

viewer = C3D()
viewer.add_molecule(mol, name="complex")
viewer.add_style("cartoon")
viewer.add_style("stick", "resn LIG")

# Hide the ligand sticks while leaving cartoon visible
viewer.remove_style("stick", "resn LIG")
show_style(style, selection=None, color=None)[source]

Synonym for add_style().

Parameters:
  • style (str | Dict[str, Any]) – Style preset or raw 3Dmol.js style dict.

  • selection (str | Dict[str, Any] | None) – Atoms to style.

  • color (str | None) – Optional color for preset styles.

Returns:

Self, for method chaining.

Return type:

C3D

hide_style(style, selection=None)[source]

Synonym for remove_style().

Parameters:
  • style (str | Dict[str, Any]) – Style preset or raw 3Dmol.js style dict.

  • selection (str | Dict[str, Any] | None) – Atoms to modify.

Returns:

Self, for method chaining.

Return type:

C3D

show_polar_hydrogens(rep)[source]

Show a representation for polar hydrogens.

Parameters:

rep (str | Dict[str, Any]) – Style preset or raw 3Dmol.js style dict to add.

Returns:

Self, for method chaining.

Return type:

C3D

hide_nonpolar_hydrogens(rep=None)[source]

Hide a representation for nonpolar hydrogens.

Parameters:

rep (str | Dict[str, Any] | None) – Style preset or raw 3Dmol.js style dict to remove. When None, all styles are removed from nonpolar hydrogens.

Returns:

Self, for method chaining.

Return type:

C3D

add_surface(selection, name=None, type='molecular', color='#FFFFFF', opacity=0.75, mode='surface')[source]

Add a named surface operation to the scene.

Parameters:
  • selection (str | Dict[str, Any]) – Atoms used to generate the surface.

  • name (str | None) – Optional surface name for later removal.

  • type (str) – Surface type. Accepted values are "molecular" and "sasa".

  • color (str) – CSS color string.

  • opacity (float) – Surface opacity.

  • mode (str) – Surface display mode. Accepted values are "surface" and "wireframe".

Returns:

Self, for method chaining.

Raises:

ValueError – If type or mode is not recognized.

Return type:

C3D

remove_surface(name)[source]

Remove a previously added surface by name.

Parameters:

name (str) – Surface name to remove.

Returns:

Self, for method chaining.

Return type:

C3D

add_map(path_or_grid, name=None, format=None, color='#38BDF8', opacity=1.0, show_box=False)[source]

Add a volumetric map operation to the scene.

Parameters:
  • path_or_grid (str | Path | Any) – Map file path or OpenEye scalar grid.

  • name (str | None) – Optional map name. Path inputs default to the file stem; grid inputs default to the grid title when available.

  • format (str | None) – Optional map format override for path inputs.

  • color (str) – CSS color string.

  • opacity (float) – Map opacity.

  • show_box (bool) – If True, show the map bounding box.

Returns:

Self, for method chaining.

Raises:

ValueError – If a map with the resolved name is already active.

Return type:

C3D

remove_map(name)[source]

Remove a previously added map by name.

Parameters:

name (str) – Map name to remove.

Returns:

Self, for method chaining.

Return type:

C3D

add_isosurface(map_name, name=None, level=None, selection=None, buffer=None, carve=None, representation='mesh', color='#0000FF', opacity=0.75)[source]

Add an isosurface operation for an active map.

Parameters:
  • map_name (str) – Name of a map added by add_map().

  • name (str | None) – Optional isosurface name for later removal.

  • level (float | None) – Contour level. None lets the GUI choose a default.

  • selection (str | Dict[str, Any] | None) – Optional atom selection used for clipping.

  • buffer (float | None) – Optional selection buffer distance.

  • carve (float | None) – Optional carve distance.

  • representation (str) – Isosurface representation. Accepted values are "mesh" and "surface".

  • color (str) – CSS color string.

  • opacity (float) – Isosurface opacity.

Returns:

Self, for method chaining.

Raises:

ValueError – If map_name is not active or representation is not recognized.

Return type:

C3D

remove_isosurface(name)[source]

Remove a previously added isosurface by name.

Parameters:

name (str) – Isosurface name to remove.

Returns:

Self, for method chaining.

Return type:

C3D

set_color(selection, color, hets=True)[source]

Set the color for atoms matching a selection.

Operations are applied in the order they are called, so colors set after a preset will override the preset’s coloring.

Parameters:
  • selection (str | Dict[str, Any]) – Atoms to color. Can be a selection expression string (e.g. "chain A", "resn LIG"), an entry name to target a specific molecule, or a raw 3Dmol.js selection dict (e.g. {"chain": "A"}).

  • color (str) – CSS color string (e.g. "green", "#00ff00").

  • hets (bool) – If True (default), all atoms in the selection are recolored. If False, only carbon atoms are recolored, preserving element coloring for heteroatoms (N, O, S, etc.).

Returns:

Self, for method chaining.

Return type:

C3D

Example:

viewer = C3D()
viewer.add_molecule(mol, name="protein")
viewer.set_preset("sites")
viewer.set_color("chain A", "blue")
viewer.set_color("resn V4M", "magenta", hets=False)
set_ui(sidebar=True, menubar=True, console=True, terminal=None)[source]

Configure which UI panels are visible.

Parameters:
  • sidebar (bool) – Show the sidebar panel.

  • menubar (bool) – Show the menubar panel.

  • console (bool) – Show the command console panel.

  • terminal (bool | None) – Deprecated alias for console.

Returns:

Self, for method chaining.

Return type:

C3D

set_background(color)[source]

Set the viewer background color.

Parameters:

color (str) – CSS color string (e.g. "#ffffff" or "white").

Returns:

Self, for method chaining.

Return type:

C3D

set_theme(theme='auto')[source]

Set the GUI color theme.

Controls the overall UI appearance (panel backgrounds, text color, borders) and the viewer background color when no explicit background has been set via set_background().

Parameters:

theme (str) – "auto", "light", or "dark".

Returns:

Self, for method chaining.

Raises:

ValueError – If theme is not "auto", "light", or "dark".

Return type:

C3D

zoom_to(selection=None)[source]

Set the zoom target after loading.

Parameters:

selection (str | Dict[str, Any] | None) – Selection to zoom into. Can be a selection expression string (e.g. "resn 502", "chain A"), a raw 3Dmol.js selection dict (e.g. {"chain": "A"}), or None to fit all molecules in view.

Returns:

Self, for method chaining.

Return type:

C3D

orient(selection=True)[source]

Orient the view by aligning principal axes with the screen.

Uses PCA to align the longest molecular dimension horizontally, the second-longest vertically, and the shortest perpendicular to the screen, then zooms to fit. When used, this replaces any zoom_to() setting.

Parameters:

selection (bool | str | Dict[str, Any]) – Atoms to orient on. True orients on all atoms. A string selection expression (e.g. "chain A") or a raw 3Dmol.js selection dict (e.g. {"chain": "A"}) restricts orientation to the matching atoms.

Returns:

Self, for method chaining.

Return type:

C3D

set_preset(name)[source]

Apply a view preset.

Presets are compound styles defined in the 3dmol-js-gui that combine multiple representations into a common visualization. When a preset is set it replaces any styles added via add_style().

Available presets:

  • "simple" – Element-colored cartoon with per-chain carbons and sticks for ligands.

  • "sites" – Like simple, plus stick representation for residues within 5 angstroms of ligands.

  • "ball-and-stick" – Ball-and-stick for ligands only.

Parameters:

name (str) – Preset name (case-insensitive).

Returns:

Self, for method chaining.

Raises:

ValueError – If name is not a recognized preset.

Return type:

C3D

to_html()[source]

Generate a self-contained HTML document for the viewer.

All JavaScript and CSS dependencies are inlined so the document requires no external network requests.

Returns:

Complete HTML document as a string.

Raises:

ValueError – If no molecules have been added.

Return type:

str

display()[source]

Display the viewer in the current notebook environment.

Wraps to_html() in an <iframe> with srcdoc. Automatically detects whether the environment is Marimo or Jupyter and returns the appropriate display object.

Returns:

A displayable object (marimo.Html or a Jupyter-compatible display object with _repr_html_).

Conversion Utilities

Molecule conversion utilities for the C3D 3D viewer.

Converts OpenEye OEMolBase and OEDesignUnit objects into string representations (SDF or PDB) that 3Dmol.js can consume.

class cnotebook.c3d.convert.MoleculeData(name, data, format, source_type, num_atoms=0, disabled=False)[source]

Bases: object

Container for molecule data ready for 3Dmol.js consumption.

Parameters:
  • name (str) – Display name for the molecule.

  • data (str) – String content (SDF or PDB format).

  • format (str) – Format identifier ("sdf" or "pdb").

  • source_type (str) – Origin type ("molecule" or "design_unit").

  • num_atoms (int) – Number of atoms in the molecule.

  • disabled (bool) – If True, the entry is hidden when the viewer starts.

name: str
data: str
format: str
source_type: str
num_atoms: int = 0
disabled: bool = False
__init__(name, data, format, source_type, num_atoms=0, disabled=False)
Parameters:
Return type:

None

class cnotebook.c3d.convert.MapData(name, data, format, encoding)[source]

Bases: object

Container for volumetric map data ready for 3Dmol.js consumption.

Parameters:
  • name (str) – Display name for the map.

  • data (str) – Embedded map content.

  • format (str) – Format identifier ("ccp4" or "cube").

  • encoding (str) – Data encoding ("base64" or "text").

name: str
data: str
format: str
encoding: str
__init__(name, data, format, encoding)
Parameters:
Return type:

None

cnotebook.c3d.convert.convert_molecule(mol, name=None, disabled=False)[source]

Convert an OpenEye molecule to SDF string data for 3Dmol.js.

If the molecule lacks 3D coordinates, conformer generation is attempted automatically via Omega. A warning is logged when this occurs.

Parameters:
  • mol (OEMolBase) – OpenEye molecule to convert.

  • name (str | None) – Optional display name. Falls back to the molecule title, then to "molecule".

  • disabled (bool)

Returns:

MoleculeData with format="sdf" and source_type="molecule".

Raises:
  • TypeError – If mol is not an oechem.OEMolBase.

  • ValueError – If conformer generation fails.

Return type:

MoleculeData

Example:

from openeye import oechem
mol = oechem.OEMol()
oechem.OESmilesToMol(mol, "c1ccccc1")
data = convert_molecule(mol, name="benzene")
cnotebook.c3d.convert.convert_map(map_input, name=None, format=None)[source]

Convert a local map path or OpenEye scalar grid for 3Dmol.js.

Local paths are embedded directly. Binary CCP4-like formats are base64 encoded, while cube files are embedded as UTF-8 text. OpenEye scalar grids are written to temporary CCP4 files before embedding.

Parameters:
  • map_input (str | Path | Any) – Local map path or oegrid.OEScalarGrid.

  • name (str | None) – Optional display name. Path inputs fall back to the path stem, while scalar grids fall back to their title and then "map".

  • format (str | None) – Optional map format for path inputs.

Returns:

MapData with embedded map content.

Raises:
  • FileNotFoundError – If a path input does not exist.

  • ValueError – If a path input is not a file, the format is unsupported, or OpenEye grid writing fails.

  • TypeError – If map_input is not a supported map input.

Return type:

MapData

cnotebook.c3d.convert.convert_design_unit(du, name=None, disabled=False)[source]

Convert an OpenEye design unit to PDB string data for 3Dmol.js.

Extracts the full complex (all components) from the design unit and writes it as a PDB string.

Parameters:
  • du (OEDesignUnit) – OpenEye design unit to convert.

  • name (str | None) – Optional display name. Falls back to the design unit title, then to "design_unit".

  • disabled (bool) – bool, if True, the entry will appear as disabled in the entries list.

Returns:

MoleculeData with format="pdb" and source_type="design_unit".

Raises:

TypeError – If du is not an oechem.OEDesignUnit.

Return type:

MoleculeData

Example:

from openeye import oechem
du = oechem.OEDesignUnit()
oechem.OEReadDesignUnit("complex.oedu", du)
data = convert_design_unit(du)