Skip to content

Viewer Module

The viewer module provides interactive, browser-based 3D visualization for protein structures generated by synth-pdb.

viewer

3D Molecular Viewer for synth-pdb.

Opens generated PDB structures in browser-based 3D viewer using 3Dmol.js. Based on pdbstat's molecular viewer implementation.

Functions

view_structure_in_browser(pdb_content, filename='structure.pdb', style='cartoon', color='spectrum', restraints=None, highlights=None, show_hbonds=True)

Open 3D structure viewer in browser.

Parameters:

Name Type Description Default
pdb_content str

PDB file contents as string

required
filename str

Name to display in viewer title

'structure.pdb'
style str

Initial representation style (cartoon/stick/sphere/line)

'cartoon'
color str

Initial color scheme (spectrum/chain/ss/white)

'spectrum'
restraints Optional[List[Any]]

Optional list of restraint dicts to visualize

None
Example

pdb = generate_pdb_content(length=20) view_structure_in_browser(pdb, "my_peptide.pdb")

Raises:

Type Description
Exception

If viewer fails to open

Source code in synth_pdb/viewer.py
def view_structure_in_browser(
    pdb_content: str,
    filename: str = "structure.pdb",
    style: str = "cartoon",
    color: str = "spectrum",
    restraints: Optional[List[Any]] = None,
    highlights: Optional[List[Any]] = None,
    show_hbonds: bool = True,
) -> None:
    """Open 3D structure viewer in browser.

    Args:
        pdb_content: PDB file contents as string
        filename: Name to display in viewer title
        style: Initial representation style (cartoon/stick/sphere/line)
        color: Initial color scheme (spectrum/chain/ss/white)
        restraints: Optional list of restraint dicts to visualize

    Example:
        >>> pdb = generate_pdb_content(length=20)
        >>> view_structure_in_browser(pdb, "my_peptide.pdb")

    Raises:
        Exception: If viewer fails to open

    """
    try:
        logger.info(f"Opening 3D viewer for {filename}")

        # Generate HTML with embedded 3Dmol.js viewer
        html = _create_3dmol_html(
            pdb_content, filename, style, color, restraints, highlights, show_hbonds
        )

        # Save to temporary file
        with tempfile.NamedTemporaryFile(
            mode="w", suffix=".html", delete=False, encoding="utf-8"
        ) as f:
            f.write(html)
            temp_path = f.name

        # Open in default browser
        webbrowser.open(f"file://{temp_path}")

        logger.info(f"3D viewer opened in browser: {temp_path}")

    except Exception as e:
        logger.error(f"Failed to open 3D viewer: {e}")
        raise