dash_bio.Molecule3dViewer Examples and Reference

see Molecule3dViewer in action.

Default Molecule3dViewer

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

import json
import six.moves.urllib.request as urlreq
from six import PY3
import dash
from dash.dependencies import Input, Output
import dash_bio as dashbio
import dash_html_components as html

app = dash.Dash(__name__)

model_data = urlreq.urlopen(
    'https://raw.githubusercontent.com/plotly/dash-bio-docs-files/master/' +
    'mol3d/model_data.js'
).read()
styles_data = urlreq.urlopen(
    'https://raw.githubusercontent.com/plotly/dash-bio-docs-files/master/' +
    'mol3d/styles_data.js'
).read()

if PY3:
    model_data = model_data.decode('utf-8')
    styles_data = styles_data.decode('utf-8')

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

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

@app.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(model_data['atoms'][atm]['element'])),
        html.Div('Chain: {}'.format(model_data['atoms'][atm]['chain'])),
        html.Div('Residue name: {}'.format(model_data['atoms'][atm]['residue_name'])),
        html.Br()
    ]) for atm in atom_ids]

if __name__ == '__main__':
    app.run_server(debug=True)
Selection data

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 six.moves.urllib.request as urlreq
from six import PY3
import dash
from dash.dependencies import Input, Output
import dash_bio as dashbio
import dash_core_components as dcc
import dash_html_components as html

app = dash.Dash(__name__)

model_data = urlreq.urlopen(
    "https://raw.githubusercontent.com/plotly/dash-bio-docs-files/master/"
    + "mol3d/model_data.js"
).read()
styles_data = urlreq.urlopen(
    "https://raw.githubusercontent.com/plotly/dash-bio-docs-files/master/"
    + "mol3d/styles_data.js"
).read()

if PY3:
    model_data = model_data.decode("utf-8")
    styles_data = styles_data.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,
        ),
    ]
)

@app.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_server(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.

import json
import six.moves.urllib.request as urlreq
from six import PY3
import dash
from dash.dependencies import Input, Output
import dash_table
import dash_bio as dashbio
import dash_html_components as html
import pandas as pd

app = dash.Dash(__name__)

model_data = urlreq.urlopen(
    "https://raw.githubusercontent.com/plotly/dash-bio-docs-files/master/"
    + "mol3d/model_data.js"
).read()
styles_data = urlreq.urlopen(
    "https://raw.githubusercontent.com/plotly/dash-bio-docs-files/master/"
    + "mol3d/styles_data.js"
).read()

if PY3:
    model_data = model_data.decode("utf-8")
    styles_data = styles_data.decode("utf-8")

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

df = pd.DataFrame(model_data["atoms"])
df = df.drop_duplicates(subset=['residue_name'])

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", styles=styles_data, modelData=model_data
        ),
    ]
)

@app.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]
    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_server(debug=True)

Selection Type

Choose what gets highlighted with the same color upon selection.

import json
import six.moves.urllib.request as urlreq
import dash_bio as dashbio

model_data = urlreq.urlopen(
    'https://raw.githubusercontent.com/plotly/dash-bio-docs-files/master/mol3d/model_data.js').read()
styles_data = urlreq.urlopen(
    'https://raw.githubusercontent.com/plotly/dash-bio-docs-files/master/mol3d/styles_data.js').read()
model_data = json.loads(model_data)
styles_data = json.loads(styles_data)

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

Background Color/Opacity

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

import json
import six.moves.urllib.request as urlreq
import dash_bio as dashbio

model_data = urlreq.urlopen('https://raw.githubusercontent.com/plotly/dash-bio-docs-files/master/mol3d/model_data.js').read()
styles_data = urlreq.urlopen('https://raw.githubusercontent.com/plotly/dash-bio-docs-files/master/mol3d/styles_data.js').read()

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

dashbio.Molecule3dViewer(
    styles=styles_data,
    modelData=model_data,
    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 json
import six.moves.urllib.request as urlreq
import dash_bio as dashbio

model_data = urlreq.urlopen(
    'https://raw.githubusercontent.com/plotly/dash-bio-docs-files/master/mol3d/model_data.js').read()
styles_data = urlreq.urlopen(
    'https://raw.githubusercontent.com/plotly/dash-bio-docs-files/master/mol3d/styles_data.js').read()
model_data = json.loads(model_data)
styles_data = json.loads(styles_data)

dashbio.Molecule3dViewer(
    styles=styles_data,
    modelData=model_data,
    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 json
import six.moves.urllib.request as urlreq
import dash_bio as dashbio

model_data = urlreq.urlopen(
    'https://raw.githubusercontent.com/plotly/dash-bio-docs-files/master/mol3d/model_data.js').read()
styles_data = urlreq.urlopen(
    'https://raw.githubusercontent.com/plotly/dash-bio-docs-files/master/mol3d/styles_data.js').read()
model_data = json.loads(model_data)
styles_data = json.loads(styles_data)

dashbio.Molecule3dViewer(
    styles=styles_data,
    modelData=model_data,
    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 json
import six.moves.urllib.request as urlreq
import dash_bio as dashbio

model_data = urlreq.urlopen('https://raw.githubusercontent.com/plotly/dash-bio-docs-files/master/mol3d/benzene_model_data.js').read()
styles_data = urlreq.urlopen('https://raw.githubusercontent.com/plotly/dash-bio-docs-files/master/mol3d/benzene_style_data.js').read()

cube_data = urlreq.urlopen('https://raw.githubusercontent.com/plotly/dash-bio-docs-files/master/mol3d/benzene-homo.cube').read().decode('utf-8')

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

dashbio.Molecule3dViewer(
    styles=styles_data,
    modelData=model_data,
    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.

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

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.

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.

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)

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.

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

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

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

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’, ‘stick’; optional)

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.