dash_bio.Molecule3dViewer Examples and Reference

see Molecule3dViewer in action.

Molecule3dViewer

An example of a default Molecule3dViewer component without any extra properties.

Selection data
import dash_bio as dashbio
from dash import Dash, html, Input, Output, callback
from dash_bio.utils import PdbParser, create_mol3d_style

app = Dash()

parser = PdbParser('https://git.io/4K8X.pdb')

data = parser.mol3d_data()
styles = create_mol3d_style(
    data['atoms'], visualization_type='cartoon', color_element='residue'
)

app.layout = html.Div([
    dashbio.Molecule3dViewer(
        id='dashbio-default-molecule3d',
        modelData=data,
        styles=styles
    ),
    "Selection data",
    html.Hr(),
    html.Div(id='default-molecule3d-output')
])

@callback(
    Output('default-molecule3d-output', 'children'),
    Input('dashbio-default-molecule3d', 'selectedAtomIds')
)
def show_selected_atoms(atom_ids):
    if atom_ids is None or len(atom_ids) == 0:
        return 'No atom has been selected. Click somewhere on the molecular \
        structure to select an atom.'
    return [html.Div([
        html.Div('Element: {}'.format(data['atoms'][atm]['elem'])),
        html.Div('Chain: {}'.format(data['atoms'][atm]['chain'])),
        html.Div('Residue name: {}'.format(data['atoms'][atm]['residue_name'])),
        html.Br()
    ]) for atm in atom_ids]

if __name__ == '__main__':
    app.run(debug=True)

Customization

Zoom Factor

The current stage of the molecule viewer can be zoomed by a constant factor with the zoom prop. This maintains the rotation and orientation of the stage while zooming, as well as any selections or property changes from other callbacks.

It is important to note that the zoom animation can conflict with the zoomTo animation if both props are set. In this case, it is recommended to set animationDuration to values that would not overlap, or use fixedPath to prioritize the animation which occurs.

import json
import urllib.request as urlreq
from dash import Dash, html, dcc, Input, Output, callback
import dash_bio as dashbio

app = Dash()



model_data = urlreq.urlopen(
    'https://git.io/mol3d-model_data.js'
).read().decode('utf-8')

styles_data = urlreq.urlopen(
    'https://git.io/mol3d-styles_data.js'
).read().decode('utf-8')

model_data = json.loads(model_data)
styles_data = json.loads(styles_data)

app.layout = html.Div(
    [
        dashbio.Molecule3dViewer(
            id="zoomfactor-molecule3d", styles=styles_data, modelData=model_data
        ),
        dcc.Slider(
            id="zoomfactor-slider",
            min=0.4,
            max=2.0,
            step=None,
            marks={0.4: "0.4", 0.8: "0.8", 1.2: "1.2", 1.6: "1.6", 2.0: "2.0"},
            value=0.8,
        ),
    ]
)

@callback(
    Output("zoomfactor-molecule3d", "zoom"),
    Input("zoomfactor-slider", "value"),
    prevent_initial_call=True,
)
def zoom(value):
    return {"factor": value, "animationDuration": 1000, "fixedPath": False}

if __name__ == "__main__":
    app.run(debug=True)

Zooming to Specific Residues

We can zoom into specific residues and chains on the molecule by setting the zoomTo prop. An optional animationDuration denotes the duration of the zoom animation (in milliseconds),

The residue selection must be supplied in the following format:

"sel": {"chain":str,"resi":int}

The chain key indicates the protein chain identifier from the molecule’s model data, and resi is the internal integer index value on the chain for the residue of interest.

In the example below, select the rows on the table to zoom into and label the chosen residue.

from dash import Dash, html, dash_table, Input, Output, callback
import dash_bio as dashbio
from dash_bio.utils import PdbParser, create_mol3d_style
import pandas as pd

app = Dash()

parser = PdbParser('https://git.io/4K8X.pdb')

data = parser.mol3d_data()
styles = create_mol3d_style(
    data['atoms'], visualization_type='cartoon', color_element='residue'
)

df = pd.DataFrame(data["atoms"])
df = df.drop_duplicates(subset=['residue_name'])
df['positions'] = df['positions'].apply(lambda x: ', '.join(map(str, x)))

app.layout = html.Div(
    [
        dash_table.DataTable(
            id="zooming-specific-residue-table",
            columns=[{"name": i, "id": i} for i in df.columns],
            data=df.to_dict("records"),
            row_selectable="single",
            page_size=10,
        ),
        dashbio.Molecule3dViewer(
            id="zooming-specific-molecule3d-zoomto",
            modelData=data,
            styles=styles
        ),
    ]
)


@callback(
    Output("zooming-specific-molecule3d-zoomto", "zoomTo"),
    Output("zooming-specific-molecule3d-zoomto", "labels"),
    Input("zooming-specific-residue-table", "selected_rows"),
    prevent_initial_call=True
)
def residue(selected_row):
    row = df.iloc[selected_row]
    row['positions'] = row['positions'].apply(lambda x: [float(x) for x in x.split(',')])
    return [
        {
            "sel": {"chain": row["chain"], "resi": row["residue_index"]},
            "animationDuration": 1500,
            "fixedPath": True,
        },
        [
            {
                "text": "Residue Name: {}".format(row["residue_name"].values[0]),
                "position": {
                    "x": row["positions"].values[0][0],
                    "y": row["positions"].values[0][1],
                    "z": row["positions"].values[0][2],
                },
            }
        ],
    ]

if __name__ == "__main__":
    app.run(debug=True)

Selection Type

Choose what gets highlighted with the same color upon selection.

import dash_bio as dashbio
from dash_bio.utils import PdbParser, create_mol3d_style

parser = PdbParser('https://git.io/4K8X.pdb')

data = parser.mol3d_data()
styles = create_mol3d_style(
    data['atoms'], visualization_type='cartoon', color_element='residue'
)

dashbio.Molecule3dViewer(
    modelData=data,
    styles=styles,
    selectionType='Chain'
)

Background Color/Opacity

Change the background color and opacity of the canvas on which Mol3D is rendered.

import dash_bio as dashbio
from dash_bio.utils import PdbParser, create_mol3d_style

parser = PdbParser('https://git.io/4K8X.pdb')

data = parser.mol3d_data()
styles = create_mol3d_style(
    data['atoms'], visualization_type='cartoon', color_element='residue'
)

dashbio.Molecule3dViewer(
    modelData=data,
    styles=styles,
    backgroundColor='#FF0000',
    backgroundOpacity=0.2
)

Labels

Add labels corresponding to the atom of the molecule. Label styles can be set with additional parameters. For styling keys, see.

import dash_bio as dashbio
from dash_bio.utils import PdbParser, create_mol3d_style

parser = PdbParser('https://git.io/4K8X.pdb')

data = parser.mol3d_data()
styles = create_mol3d_style(
    data['atoms'], visualization_type='cartoon', color_element='residue'
)

dashbio.Molecule3dViewer(
    modelData=data,
    styles=styles,
    labels=[
        {'text': 'Residue Name: GLY1', 'fontColor': 'red', 'font': 'Courier New, monospace'},
        {'text': 'Residue Chain: A', 'position': {'x': 15.407, 'y': -8.432, 'z': 6.573}}
    ],
)

Shapes

Add predefined renderable shapes to the molecule. Supported shape types are Arrow, Sphere, and Cylinder.

import dash_bio as dashbio
from dash_bio.utils import PdbParser, create_mol3d_style

parser = PdbParser('https://git.io/4K8X.pdb')

data = parser.mol3d_data()
styles = create_mol3d_style(
    data['atoms'], visualization_type='cartoon', color_element='residue'
)

dashbio.Molecule3dViewer(
    modelData=data,
    styles=styles,
    shapes=[
        {
            'type': 'Sphere',
            'center': {'x': 0, 'y': 0, 'z': 0},
            'radius': 3.0,
            'color': 'blue',
            'opacity': 1
        },
        {
            'type': 'Arrow',
            'start': {'x': 40, 'y': 20.0, 'z': 0.0},
            'end': {'x': 20.0, 'y': 10.0, 'z': 0.0},
            'radius': 1.0,
            'radiusRadio': 0.5,
            'mid': 1.0,
            'color': 'red',
            'opacity': 1
        },
        {
            'type': 'Cylinder',
            'start': {'x': 10.0, 'y': -30.0, 'z': 0.0},
            'end': {'x': 20.0, 'y': -50.0, 'z': 0.0},
            'radius': 1.0,
            'fromCap': 1,
            'toCap': 2,
            'color': 'green',
            'opacity': 1
        }
    ],
)

Isosurfaces

Render a 3D isosurface. Volumetric orbital data must be provided in the cube file format.

import urllib.request as urlreq

import dash_bio as dashbio
from dash_bio.utils import PdbParser, create_mol3d_style

parser = PdbParser('https://git.io/4K8X.pdb')

data = parser.mol3d_data()
styles = create_mol3d_style(
    data['atoms'], visualization_type='cartoon', color_element='residue'
)


cube_data = urlreq.urlopen(
    'https://git.io/benzene-homo.cube'
).read().decode('utf-8')


dashbio.Molecule3dViewer(
    modelData=data,
    styles=styles,
    selectionType='atom',
    orbital={
        'cube_file': cube_data,
        'iso_val': 0.1,
        'opacity': 1.0,
        'positiveVolumetricColor': 'red',
        'negativeVolumetricColor': 'blue',
    }
)

Molecule3dViewer Properties

Access this documentation in your Python terminal with:
```python

help(dash_bio.Molecule3dViewer)
```

Our recommended IDE for writing Dash apps is Dash Enterprise’s
Data Science Workspaces,
which has typeahead support for Dash Component Properties.
Find out if your company is using
Dash Enterprise
.

id (string; optional):
The ID used to identify this component in callbacks.

selectionType (a value equal to: ‘atom’, ‘residue’ or ‘chain’; default 'atom'):
The selection type - may be atom, residue or chain.

backgroundColor (string; default '#FFFFFF'):
Property to change the background color of the molecule viewer.

backgroundOpacity (number; default 0):
Property to change the background opacity - ranges from 0 to 1.

styles (list of dicts; optional):
Property that can be used to change the representation of the
molecule. Options include sticks, cartoon and sphere.

styles is a list of dicts with keys:

  • color (string; optional)

  • visualization_type (a value equal to: ‘cartoon’, ‘sphere’ or ‘stick’; optional)

modelData (dict; optional):
The data that will be used to display the molecule in 3D The data will
be in JSON format and should have two main dictionaries - atoms, bonds.

modelData is a dict with keys:

  • atoms (list; optional)

  • bonds (list; optional)

atomLabelsShown (boolean; optional):
Property to either show or hide labels.

selectedAtomIds (list; optional):
Property that stores a list of all selected atoms.

labels (list of dicts; optional):
Labels corresponding to the atoms of the molecule. Each label has a
text field, a string containing the label content, and can have many
other styling fields as described in
https://3dmol.csb.pitt.edu/doc/types.html#LabelSpec.

orbital (dict; optional):
Add an isosurface from volumetric data provided in the cube_file.

orbital is a dict with keys:

  • cube_file (string; optional):
    The filepath containing raw volumetric data for vertex coloring.

  • iso_val (number; optional):
    The isovalue to draw the surface at.

  • negativeVolumetricColor (string; optional):
    Color for the negative value of the isosurface orbital.

  • opacity (number; optional):
    Transparency of the surface, between 0 and 1.

  • positiveVolumetricColor (string; optional):
    Color for the positive value of the isosurface orbital.

zoom (dict; default { factor: 0.8, animationDuration: 0, fixedPath: False,}):
Zoom the current view by a constant factor, with optional parameters
to modify the duration and motion of the zoom animation.

zoom is a dict with keys:

  • animationDuration (number; optional):
    An optional parameter that denotes the duration of a zoom
    animation, in milliseconds.

  • factor (number; optional):
    Magnification factor. Values greater than 1 will zoom, in, less
    than one will zoom out. Default 2.

  • fixedPath (boolean; optional):
    If True, animation is constrained to requested motion, overriding
    updates that happen during the animation.

zoomTo (dict; default { sel: {}, animationDuration: 0, fixedPath: False,}):
Zoom to center of atom selection.

zoomTo is a dict with keys:

  • animationDuration (number; optional):
    An optional parameter that denotes the duration of a zoom
    animation , in milliseconds.

  • fixedPath (boolean; optional):
    If True, animation is constrained to requested motion, overriding
    updates that happen during the animation.

  • sel (dict; optional):
    Selection specification specifying model and atom properties to
    select. Default: all atoms in viewer.

    sel is a dict with keys:

    • chain (string; optional):
      Chain that the residue is located on.

    • resi (number; optional):
      The index value used to identify the residue; residues are
      numbered sequentially starting from 1.

shapes (list of dicts; optional):
Add a predefined renderable shape objects to the molecule. Valid shape
types are Arrow, Sphere, and Cylinder.

height (number; optional):
The height (in px) of the container.

width (number; optional):
The width (in px) of the container.

style (dict; default { height: 500, width: 500,}):
Generic style overrides on the plot div.

onRenderNewData (optional):
Callback to re-render molecule viewer when modelData is changed.

onChangeSelection (optional):
Callback to change append selectedAtomIds when a selection is made.

loading_state (dict; optional):
Object that holds the loading state object coming from dash-renderer.

loading_state is a dict with keys:

  • component_name (string; optional):
    Holds the name of the component that is loading.

  • is_loading (boolean; optional):
    Determines if the component is loading or not.

  • prop_name (string; optional):
    Holds which property is loading.

Example Data