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
import dash_bio as dashbio
from dash import html
from dash_bio_utils import PdbParser, create_mol3d_style
from dash.dependencies import Input, Output

app = dash.Dash(__name__)

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')
])

@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)

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
import dash
from dash.dependencies import Input, Output
import dash_bio as dashbio
from dash import html, dcc

app = dash.Dash(__name__)



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,
        ),
    ]
)

@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 dash
from dash.dependencies import Input, Output
import dash_table
import dash_bio as dashbio
from dash_bio_utils import PdbParser, create_mol3d_style
import dash_html_components as html
import pandas as pd

app = dash.Dash(__name__)

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'])

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
        ),
    ]
)


@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 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:

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:

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:

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:

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

zoomTo is a dict with keys:

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

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

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

Example Data