Exemplo n.º 1
0
def view_estrogen_receptor():
    """
    load receptor structure and display with ngl
    """
    view = nv.show_pdbid("1g50", default=False)
    view._set_size("800px", "400px")
    view.add_cartoon(":B or :C")
    view.add_ball_and_stick("(:B or :C) and EST")
    view.center(":B or :C")
    return view
Exemplo n.º 2
0
def protein(input_type, input_value, output_image_filename=None):
    """
    Visualizing protein data.

    Parameters
    ----------
    input_type : str
        Either "pdb_code" or a file extension e.g. "pdb".
    input_value: str or pathlib.Path
        Either the PDB code of the protein or a local filepath.
    output_image_filename : str
        Optional; default: None.
        Filename to save a static image of the protein.

    Returns
    -------
    nglview.widget.NGLWidget
        Interactive NGL viewer visualizing a given protein and (if available) its co-crystallized
        ligand.
    """

    if input_type == "pdb_code":
        viewer = nv.show_pdbid(input_value, height="600px")
    else:
        with open(input_value) as f:
            viewer = nv.show_file(f,
                                  ext=input_type,
                                  height="600px",
                                  default_representation=False)
            viewer.add_representation("cartoon", selection="protein")

    viewer.add_representation(repr_type="ball+stick",
                              selection="hetero and not water")
    viewer.center("protein")

    if output_image_filename is not None:
        viewer.render_image(trim=True, factor=2)
        viewer._display_image()
        viewer.download_image(output_image_filename)
    return viewer
Exemplo n.º 3
0
def test_API_promise_to_have():

    # for Jupyter notebook extension
    nv._jupyter_nbextension_paths()

    view = nv.demo()

    # trigger _set_size
    with patch.object(view, '_remote_call') as mock_call:
        view.layout.width = '100px'
        view.layout.height = '500px'
        mock_call.assert_called_with('setSize',
                                     args=['', '500px'],
                                     target='Widget')

    # Structure
    structure = nv.Structure()
    structure.get_structure_string
    assert hasattr(structure, 'id')
    assert hasattr(structure, 'ext')
    assert hasattr(structure, 'params')

    # Widget
    nv.NGLWidget._set_coordinates

    nv.NGLWidget.add_component
    nv.NGLWidget.add_trajectory
    nv.NGLWidget._coordinates_dict
    nv.NGLWidget.set_representations
    nv.NGLWidget.clear
    nv.NGLWidget.center

    # add component
    view.add_component('rcsb://1tsu.pdb')
    view.add_pdbid('1tsu')

    # display
    js_utils.clean_error_output()
    display(view.player.widget_repr)
    view.player._display()
    view._display_image()

    # show
    try:
        nv.show_pdbid('1tsu')
    except:
        pass
    nv.show_url('https://dummy.pdb')
    # other backends will be tested in other sections

    # constructor
    ngl_traj = nv.PyTrajTrajectory(pt.datafiles.load_ala3())
    nv.NGLWidget(ngl_traj, parameters=dict(background_color='black'))
    nv.NGLWidget(ngl_traj, representations=[dict(type='cartoon', params={})])

    view.parameters
    view.camera
    view.camera = 'perspective'
    view._request_stage_parameters()
    view._ngl_repr_dict = REPR_DICT
    view._handle_repr_dict_changed(dict(new=dict(c0={})))

    # dummy
    class DummWidget():
        value = ''

    view.player.picked_widget = DummWidget()

    view._update_background_color(change=dict(new='blue'))
    tab = view.player._display()

    view.player.widget_repr = view.player._make_widget_repr()
    view._handle_n_components_changed(change=dict(new=2, old=1))
    view._handle_n_components_changed(change=dict(new=1, old=1))
    view._handle_n_components_changed(change=dict(new=1, old=0))
    view.on_loaded(change=dict(new=True))
    view.on_loaded(change=dict(new=False))

    view._first_time_loaded = False
    view
    view._first_time_loaded = True
    view
    view._init_gui = True
    view
    view._theme = 'dark'
    view

    view.display(gui=True, style='ngl')
    view.display(gui=False)
    view.display(gui=True, style='ipywidgets')
    view._set_sync_camera([view])
    view._set_unsync_camera([view])
    view._set_selection('.CA')
    view.color_by('atomindex')
    representations = [dict(type='cartoon', params=dict())]
    view.representations = representations
    repr_parameters = dict(opacity=0.3, params=dict())
    view.update_representation(parameters=repr_parameters)
    view._remove_representation()
    view.clear()
    view.add_representation('surface', selection='*', useWorker=True)
    view.add_representation('surface', selection='*', component=1)
    view.center()
    view._on_render_image(change=dict(new='xyz'))
    view.render_image()
    view.render_image(frame=2)
    view.download_image()

    assert view._dry_run(view._set_sync_camera,
                         [view])['methodName'] == 'setSyncCamera'

    msg = dict(type='request_frame', data=dict())
    view._ngl_handle_msg(view, msg=msg, buffers=[])
    msg = dict(type='repr_parameters', data=dict(name='hello'))
    view._ngl_handle_msg(view, msg=msg, buffers=[])
    view.loaded = True
    msg = dict(type='request_loaded', data=True)
    view._ngl_handle_msg(view, msg=msg, buffers=[])
    view.loaded = False
    msg = dict(type='request_loaded', data=True)
    view._ngl_handle_msg(view, msg=msg, buffers=[])
    msg = dict(type='all_reprs_info', data=REPR_DICT)
    view._ngl_handle_msg(view, msg=msg, buffers=[])
    msg = dict(type='stage_parameters', data=dict())
    view._ngl_handle_msg(view, msg=msg, buffers=[])
    # test negative frame (it will be set to self.count - 1)
    view.frame = -1
    msg = dict(type='request_frame', data=dict())
    # async_message
    msg = {'type': 'async_message', 'data': 'ok'}
    view._ngl_handle_msg(view, msg, [])
    # render_image
    r = view.render_image()
    Widget.widgets[r.model_id] = r
    msg = {'type': 'image_data', 'ID': r.model_id, 'data': b'YmxhIGJsYQ=='}
    view._ngl_handle_msg(view, msg, [])
    view.loaded = True
    view.show_only([
        0,
    ])
    view._js_console()
    view._get_full_params()

    # iter
    for c in view:
        assert isinstance(c, nv.widget.ComponentViewer)
Exemplo n.º 4
0
 def show(self):
     """return a 3D view of the protein within the notebook"""
     view = nglview.show_pdbid(self.pdbid)
     return view
Exemplo n.º 5
0
def test_API_promise_to_have():

    # for Jupyter notebook extension
    nv._jupyter_nbextension_paths()

    view = nv.demo()

    # Structure
    structure = nv.Structure()
    structure.get_structure_string
    assert hasattr(structure, 'id')
    assert hasattr(structure, 'ext')
    assert hasattr(structure, 'params')

    # Widget
    nv.NGLWidget._set_coordinates

    nv.NGLWidget.add_component
    nv.NGLWidget.add_trajectory
    nv.NGLWidget.coordinates_dict
    nv.NGLWidget.set_representations
    nv.NGLWidget.clear
    nv.NGLWidget.center

    # add component
    view.add_component('rcsb://1tsu.pdb')
    view.add_pdbid('1tsu')

    # display
    js_utils.clean_error_output()
    display.display(view.player.widget_repr)
    view.player._display()
    view._display_image()

    # show
    try:
        nv.show_pdbid('1tsu')
    except:
        pass
    nv.show_url('https://dummy.pdb')
    # other backends will be tested in other sections

    # constructor
    ngl_traj = nv.PyTrajTrajectory(pt.datafiles.load_ala3())
    nv.NGLWidget(ngl_traj, parameters=dict(background_color='black'))
    nv.NGLWidget(ngl_traj, representations=[dict(type='cartoon')])

    view.parameters
    view.camera
    view.camera = 'perspective'
    view._request_stage_parameters()
    view._repr_dict = REPR_DICT
    view._handle_repr_dict_changed(dict(new=dict(c0={})))

    # dummy
    class DummWidget():
        value = ''

    view.player.picked_widget = DummWidget()

    view._update_background_color(change=dict(new='blue'))
    view.on_update_dragged_file(change=dict(new=2, old=1))
    view.on_update_dragged_file(change=dict(new=1, old=1))
    tab = view.player._display()

    view.player.widget_repr = view.player._make_widget_repr()
    view._handle_n_components_changed(change=dict(new=2, old=1))
    view._handle_n_components_changed(change=dict(new=1, old=1))
    view._handle_n_components_changed(change=dict(new=1, old=0))
    view.on_loaded(change=dict(new=True))
    view.on_loaded(change=dict(new=False))
    view._refresh_render()
    view.sync_view()

    view._first_time_loaded = False
    view._ipython_display_()
    view._first_time_loaded = True
    view._ipython_display_()
    view._init_gui = True
    view._ipython_display_()
    view._theme = 'dark'
    view._ipython_display_()

    view.display(gui=True)
    view.display(gui=False)
    view.display(gui=True, use_box=True)
    view._set_draggable(True)
    view._set_draggable(False)
    view._set_sync_frame()
    view._set_sync_camera()
    view._set_spin([0, 1, 0], 0.5)
    view._set_selection('.CA')
    view.color_by('atomindex')
    representations = [dict(type='cartoon', params=dict())]
    view.representations = representations
    repr_parameters = dict(opacity=0.3, params=dict())
    view.update_representation(parameters=repr_parameters)
    view._remove_representation()
    view.clear()
    view.add_representation('surface', selection='*', useWorker=True)
    view.add_representation('surface', selection='*', component=1)
    view.center()
    view._hold_image = True
    view._on_render_image(change=dict(new=u'xyz'))
    view._hold_image = False
    view._on_render_image(change=dict(new=u'xyz'))
    view.render_image()
    view.render_image(frame=2)
    view.download_image()

    msg = dict(type='request_frame', data=dict())
    view._ngl_handle_msg(view, msg=msg, buffers=[])
    msg = dict(type='repr_parameters', data=dict(name='hello'))
    view._ngl_handle_msg(view, msg=msg, buffers=[])
    view.loaded = True
    msg = dict(type='request_loaded', data=True)
    view._ngl_handle_msg(view, msg=msg, buffers=[])
    view.loaded = False
    msg = dict(type='request_loaded', data=True)
    view._ngl_handle_msg(view, msg=msg, buffers=[])
    msg = dict(type='all_reprs_info', data=REPR_DICT)
    view._ngl_handle_msg(view, msg=msg, buffers=[])
    msg = dict(type='stage_parameters', data=dict())
    view._ngl_handle_msg(view, msg=msg, buffers=[])
    # test negative frame (it will be set to self.count - 1)
    view.frame = -1
    msg = dict(type='request_frame', data=dict())

    view.loaded = True
    view.show_only([
        0,
    ])
    view._js_console()
    view._get_full_params()
    view.detach(split=False)
    view.detach(split=True)
    # view._set_place_proxy(HBox())

    # iter
    for c in view:
        assert isinstance(c, nv.widget.ComponentViewer)
Exemplo n.º 6
0
def test_API_promise_to_have():

    # for Jupyter notebook extension
    nv._jupyter_nbextension_paths()

    view = nv.demo()

    # Structure
    structure = nv.Structure()
    structure.get_structure_string
    assert hasattr(structure, 'id')
    assert hasattr(structure, 'ext')
    assert hasattr(structure, 'params')

    # Widget
    nv.NGLWidget._set_coordinates

    nv.NGLWidget.add_component
    nv.NGLWidget.add_trajectory
    nv.NGLWidget.coordinates_dict
    nv.NGLWidget.set_representations
    nv.NGLWidget.clear
    nv.NGLWidget.center

    # add component
    view.add_component('rcsb://1tsu.pdb')
    view.add_pdbid('1tsu')

    # display
    js_utils.clean_error_output()
    display.display(view.player.widget_repr)
    view.player._display()
    view._display_image()

    # show
    try:
        nv.show_pdbid('1tsu')
    except:
        pass
    nv.show_url('https://dummy.pdb')
    # other backends will be tested in other sections

    # constructor
    ngl_traj = nv.PyTrajTrajectory(pt.datafiles.load_ala3())
    nv.NGLWidget(ngl_traj, parameters=dict(background_color='black'))
    nv.NGLWidget(ngl_traj, representations=[dict(type='cartoon')])

    view.parameters
    view.camera
    view.camera = 'perspective'
    view._request_stage_parameters()
    view._repr_dict = REPR_DICT
    view._handle_repr_dict_changed(dict(new=dict(c0={})))

    # dummy
    class DummWidget():
        value = ''

    view.player.picked_widget = DummWidget()

    view._update_background_color(change=dict(new='blue'))
    view.on_update_dragged_file(change=dict(new=2, old=1))
    view.on_update_dragged_file(change=dict(new=1, old=1))
    tab = view.player._display()

    view.player.widget_repr = view.player._make_widget_repr()
    view._handle_n_components_changed(change=dict(new=2, old=1))
    view._handle_n_components_changed(change=dict(new=1, old=1))
    view._handle_n_components_changed(change=dict(new=1, old=0))
    view.on_loaded(change=dict(new=True))
    view.on_loaded(change=dict(new=False))
    view._refresh_render()
    view.sync_view()

    view._first_time_loaded = False
    view._ipython_display_()
    view._first_time_loaded = True
    view._ipython_display_()
    view._init_gui = True
    view._ipython_display_()
    view._theme = 'dark'
    view._ipython_display_()

    view.display(gui=True)
    view.display(gui=False)
    view.display(gui=True, use_box=True)
    view._set_draggable(True)
    view._set_draggable(False)
    view._set_sync_frame()
    view._set_sync_camera()
    view._set_spin([0, 1, 0], 0.5)
    view._set_selection('.CA')
    view.color_by('atomindex')
    representations = [dict(type='cartoon', params=dict())]
    view.representations = representations
    repr_parameters = dict(opacity=0.3, params=dict())
    view.update_representation(parameters=repr_parameters)
    view._remove_representation()
    view.clear()
    view.add_representation('surface', selection='*', useWorker=True)
    view.add_representation('surface', selection='*', component=1)
    view.center()
    view._hold_image = True
    view._on_render_image(change=dict(new=u'xyz'))
    view._hold_image = False
    view._on_render_image(change=dict(new=u'xyz'))
    view.render_image()
    view.render_image(frame=2)
    view.download_image()

    msg = dict(type='request_frame', data=dict())
    view._ngl_handle_msg(view, msg=msg, buffers=[])
    msg = dict(type='repr_parameters', data=dict(name='hello'))
    view._ngl_handle_msg(view, msg=msg, buffers=[])
    view.loaded = True
    msg = dict(type='request_loaded', data=True)
    view._ngl_handle_msg(view, msg=msg, buffers=[])
    view.loaded = False
    msg = dict(type='request_loaded', data=True)
    view._ngl_handle_msg(view, msg=msg, buffers=[])
    msg = dict(type='all_reprs_info', data=REPR_DICT)
    view._ngl_handle_msg(view, msg=msg, buffers=[])
    msg = dict(type='stage_parameters', data=dict())
    view._ngl_handle_msg(view, msg=msg, buffers=[])
    # test negative frame (it will be set to self.count - 1)
    view.frame = -1
    msg = dict(type='request_frame', data=dict())

    view.loaded = True
    view.show_only([0,])
    view._js_console()
    view._get_full_params()
    view.detach(split=False)
    view.detach(split=True)
    # view._set_place_proxy(HBox())

    # iter
    for c in view: 
        assert isinstance(c, nv.widget.ComponentViewer)
Exemplo n.º 7
0
def colored_struct(
    *,
    pdb,
    prop_df,
    chain_col='chain',
    site_col='site',
    color_col='color',
    representation='cartoon',
    highlight_col=None,
    highlight_representation='spacefill',
    show_other=False,
    other_color='#FFFFFF',
    orientation=None,
):
    """Create widget showing a colored structure.

    Parameters
    ------------
    pdb : str
        Existing PDB file, or ID to be downloaded from PDB.
    prop_df : pandas DataFrame
        Data on sites to show and how to color them. You are responsible for
        ensuring that chaing / site labels are consistent with those in `pdb`,
        no automatic checks of this are performed.
    chain_col: str
        Column in `prop_df` with PDB chain ID.
    site_col : str
        Column in `prop_df` with PDB site numbers.
    color_col : str
        Column in `prop_df` with color for each site.
    representation : str or list
        Protein representation (e.g., 'cartoon', 'surface', 'spacefill',
        or other `nglview <https://github.com/arose/nglview>`_ representation;
        or a list of such representations.
    highlight_col : str or `None`
        Optional column of boolean values in `prop_df` indicating
        sites to also draw in `highlight_representation`.
    highlight_representation : str
        Additional representation for sites specified in `highlight_col`.
    show_other : `False` or str
        Show selections **not** listed as sites in `prop_df`? If so, specify
        those selections. Can be 'all', 'protein', or other selection string
        (`see here <https://github.com/arose/ngl/tree/master/doc/usage>`_).
    other_color : str
        Color for any sites not in `prop_df` but shown via `show_other`.
    orientation : `None` or list of 16 numbers
        Orientation to show the structure, can be obtained via the
        `_camera_orientation` property of a structure widget
        (https://github.com/arose/nglview/issues/785#issuecomment-487409212).

    Returns
    --------
    nglview.widget.NGLWidget
        The widget can be shown in a Jupyter notebook.

    """
    # error checking on `prop_df` and its columns
    cols = []
    for colname, col, optional in [
        ('color_col', color_col, False),
        ('site_col', site_col, False),
        ('chain_col', chain_col, False),
        ('highlight_col', highlight_col, True),
    ]:
        if col is None:
            if not optional:
                raise ValueError(f"must specify `{colname}`")
        elif col not in prop_df.columns:
            raise ValueError(f"`prop_df` lacks `{colname}` of {col}")
        elif col in cols:
            raise ValueError(f"duplicate column names of {col}")
        else:
            cols.append(col)

    prop_df = (prop_df[cols].drop_duplicates())

    if len(prop_df) != len(prop_df.groupby([chain_col, site_col])):
        raise ValueError('Inconsistent duplicated rows for some sites in '
                         '`prop_df`. For each chain and site, entries must '
                         f"be the same for all rows in these columns: {cols}")

    # get PDB into a widget; use `default_representation=False` as here:
    # https://github.com/arose/nglview/issues/802#issuecomment-492760630
    if os.path.isfile(pdb):
        w = nglview.show_structure_file(
            pdb,
            default_representation=False,
        )
    else:
        try:
            w = nglview.show_pdbid(
                pdb,
                default_representation=False,
            )
        except HTTPError:  # noqa: F821
            raise ValueError(f"`pdb` {pdb} does not specify an existing "
                             'PDB file or an ID that can be downloaded')

    # Set up color schemes as here:
    # https://github.com/arose/nglview/pull/755
    # For details on selection strings, see here:
    # https://github.com/arose/ngl/blob/master/doc/usage/selection-language.md
    colorscheme = []
    selectionlist = []
    highlight_colorscheme = []
    highlight_selectionlist = []
    for row in prop_df.itertuples():
        color = getattr(row, color_col)
        sel_str = f":{getattr(row, chain_col)} and {getattr(row, site_col)}"
        selectionlist.append(f"({sel_str})")
        colorscheme.append([color, sel_str])
        if highlight_col and getattr(row, highlight_col):
            highlight_selectionlist.append(f"({sel_str})")
            highlight_colorscheme.append([color, sel_str])
    colorscheme.append([other_color, '*'])

    selection = ', '.join(selectionlist)
    if show_other:
        selection = f"({show_other}) or ({selection})"
    # uniquely label color schemes as here:
    # https://github.com/arose/nglview/issues/802#issuecomment-492501051
    colorscheme = nglview.color._ColorScheme(
        colorscheme,
        label=f"colorscheme_{secrets.token_hex(10)}",
    )
    highlight_selection = ', '.join(highlight_selectionlist)
    highlight_colorscheme = nglview.color._ColorScheme(
        highlight_colorscheme,
        label=f"colorscheme_{secrets.token_hex(10)}",
    )

    # color and style widget; set assembly to BU1 (biological unit 1) as here:
    # https://github.com/arose/ngl/blob/master/doc/usage/selection-language.md
    w.clear_representations()
    if isinstance(representation, str):
        representation = [representation]
    for r in representation:
        w.add_representation(
            r,
            selection=selection,
            color=colorscheme,
            assembly='BU1',
        )
    if highlight_representation and highlight_selection:
        w.add_representation(
            highlight_representation,
            selection=highlight_selection,
            color=highlight_colorscheme,
            assembly='BU1',
        )

    if orientation:
        if len(orientation) != 16:
            raise ValueError('`orientation` not list of 16 numbers')
        w._set_camera_orientation(orientation)

    return w