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:
objectInteractive 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()
- __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:
- Returns:
Self, for method chaining.
- Raises:
TypeError – If mol is not an
OEMolBase.- Return type:
- 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:
- Returns:
Self, for method chaining.
- Raises:
TypeError – If du is not an
OEDesignUnit.- Return type:
- add_molecules(mols, prefix=None, enable='first')[source]
Add multiple OpenEye molecules to the viewer.
- Parameters:
mols (Iterable) – Iterable of OpenEye molecules (
OEMolBasesubclasses).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 aSequence[bool]whereTruemeans 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:
- 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 aSequence[bool]whereTruemeans 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:
- 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
Noneto 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
colorkey 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:
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:
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().
- hide_style(style, selection=None)[source]
Synonym for
remove_style().
- 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:
- 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:
- 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:
name (str | None) – Optional isosurface name for later removal.
level (float | None) – Contour level.
Nonelets 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:
- 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. IfFalse, only carbon atoms are recolored, preserving element coloring for heteroatoms (N, O, S, etc.).
- Returns:
Self, for method chaining.
- Return type:
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.
- 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:
- 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.
- 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:
- 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:
- display()[source]
Display the viewer in the current notebook environment.
Wraps
to_html()in an<iframe>withsrcdoc. Automatically detects whether the environment is Marimo or Jupyter and returns the appropriate display object.- Returns:
A displayable object (
marimo.Htmlor 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:
objectContainer 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.
- class cnotebook.c3d.convert.MapData(name, data, format, encoding)[source]
Bases:
objectContainer for volumetric map data ready for 3Dmol.js consumption.
- Parameters:
- 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:
- Returns:
MoleculeDatawithformat="sdf"andsource_type="molecule".- Raises:
TypeError – If mol is not an
oechem.OEMolBase.ValueError – If conformer generation fails.
- Return type:
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:
- Returns:
MapDatawith 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:
- 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:
- Returns:
MoleculeDatawithformat="pdb"andsource_type="design_unit".- Raises:
TypeError – If du is not an
oechem.OEDesignUnit.- Return type:
Example:
from openeye import oechem du = oechem.OEDesignUnit() oechem.OEReadDesignUnit("complex.oedu", du) data = convert_design_unit(du)