コード例 #1
0
ファイル: test_widget.py プロジェクト: marscher/nglview
def test_add_struture_then_trajectory():
    view = nv.show_structure_file(get_fn('tz2.pdb'))
    view.loaded = True
    traj = pt.datafiles.load_trpcage()
    view.add_trajectory(traj)
    view.frame = 3
    coords = view.coordinates_dict[1].copy()
    aa_eq(coords, traj[3].xyz)
    view.loaded = False
    view.add_trajectory(traj)
コード例 #2
0
def demo(*args, **kwargs):
    '''

    Examples
    --------
    >>> import nglview as nv
    >>> view = nv.demo()
    >>> view # doctest: +SKIP
    '''
    from nglview import show_structure_file
    return show_structure_file(datafiles.PDB, *args, **kwargs)
コード例 #3
0
ファイル: visualize.py プロジェクト: kbsezginel/HostDesigner
def show(*args, camera='perspective', move='auto', div=5, distance=(-10, -10), axis=0, caps=True, save=None, group=True, rotate=None):
    """
    Show given structure(s) using nglview
        - save: file_path -> save pdb file to given path
        - camera: 'perspective' / 'orthographic'
        - move: 'auto' / 'single' / None -> separate multiple structures equally distant from each other
        - distance: tuple (x, y) -> separation distance
        - axis: 0 / 1 / 2 -> separation direction (0:x, 1:y, 2:z)
        - caps: bool -> capitalize atom names so they show true colors in nglview+
        - group: bool -> group molecules in pdb file (to show bonds properly in nglview)
        - rotate: 0 / 1 / 2 -> rotate 90 degrees in (0:x, 1:y, 2:z) axis (view in xy plane)
    """
    if move is 'auto':
        translation_vectors = arrange_structure_positions(len(args), div=div, distance=distance)
    elif move is 'single':
        translation_vectors = axis_translation(len(args), distance=distance[0], axis=axis)
    else:
        translation_vectors = [[0, 0, 0]] * len(args)

    atom_names = []
    atom_coors = []
    group_numbers = []
    for mol_index, (molecule, vec) in enumerate(zip(args, translation_vectors), start=1):
        atom_names += molecule.atom_names
        coordinates = molecule.atom_coors
        if rotate is not None:
            coordinates = rotate_90(coordinates, axis=rotate)
        coordinates = translate(coordinates, vector=vec)
        atom_coors += coordinates
        group_numbers += [mol_index] * len(molecule.atom_names)

    # nglview require atom names in all caps to color them properly
    if caps:
        atom_names = [name.upper() for name in atom_names]

    # nglview requires molecules to be grouped separately to show proper bonding
    if not group:
        group_numbers = [1] * len(atom_names)
    temp_pdb_file = tempfile.NamedTemporaryFile(mode='w+', suffix='.pdb')
    write_pdb(temp_pdb_file, atom_names, atom_coors, group=group_numbers)

    view = nglview.show_structure_file(temp_pdb_file.name)
    view.camera = camera
    temp_pdb_file.close()

    if save is not None:
        with open(save, 'w') as save_file:
            write_pdb(save_file, atom_names, atom_coors, group=group_numbers)

    return view
コード例 #4
0
ファイル: structprop.py プロジェクト: sid-dinesh94/ssbio
    def view_structure(self, only_chains=None, opacity=1.0, recolor=False, gui=False):
        """Use NGLviewer to display a structure in a Jupyter notebook

        Args:
            only_chains (str, list): Chain ID or IDs to display
            opacity (float): Opacity of the structure
            recolor (bool): If structure should be cleaned and recolored to silver
            gui (bool): If the NGLview GUI should show up

        Returns:
            NGLviewer object

        """
        # TODO: show_structure_file does not work for MMTF files - need to check for that and load accordingly

        if ssbio.utils.is_ipynb():
            import nglview as nv
        else:
            raise EnvironmentError('Unable to display structure - not running in a Jupyter notebook environment')

        if not self.structure_file:
            raise ValueError("Structure file not loaded")

        only_chains = ssbio.utils.force_list(only_chains)
        to_show_chains = '( '
        for c in only_chains:
            to_show_chains += ':{} or'.format(c)
        to_show_chains = to_show_chains.strip(' or ')
        to_show_chains += ' )'

        if self.file_type == 'mmtf' or self.file_type == 'mmtf.gz':
            view = nv.NGLWidget()
            view.add_component(self.structure_path)
        else:
            view = nv.show_structure_file(self.structure_path, gui=gui)

        if recolor:
            view.clear_representations()
            if only_chains:
                view.add_cartoon(selection='{} and (not hydrogen)'.format(to_show_chains), color='silver', opacity=opacity)
            else:
                view.add_cartoon(selection='protein', color='silver', opacity=opacity)
        elif only_chains:
            view.clear_representations()
            view.add_cartoon(selection='{} and (not hydrogen)'.format(to_show_chains), color='silver', opacity=opacity)

        return view
コード例 #5
0
def test_show_structure_file():
    view = nv.show_structure_file(nv.datafiles.PDB)
コード例 #6
0
ファイル: test_widget.py プロジェクト: abradle/nglview
def test_show_structure_file():
    view = nv.show_structure_file(nv.datafiles.PDB)
コード例 #7
0
def view_ball_stick(structfile):
    """Return a nglview object to view structfile as a ball+stick model"""
    v = nv.show_structure_file(structfile)
    v.representations = [{'type': 'ball+stick', 'params': {}}]
    v.parameters = {'backgroundColor': 'black'}
    return v
コード例 #8
0
def demo(*args, **kwargs):
    from nglview import show_structure_file
    return show_structure_file(datafiles.PDB, *args, **kwargs)
コード例 #9
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
コード例 #10
0
 def view(self):
     linker_path = self.export()
     return nglview.show_structure_file(linker_path)
コード例 #11
0
def show(*args,
         camera='perspective',
         move='auto',
         div=5,
         distance=(-10, -10),
         axis=0,
         caps=True,
         save=None,
         group=True,
         rotate=None):
    """
    Show given structure(s) using nglview
        - save: file_path -> save pdb file to given path
        - camera: 'perspective' / 'orthographic'
        - move: 'auto' / 'single' / None -> separate multiple structures equally distant from each other
        - distance: tuple (x, y) -> separation distance
        - axis: 0 / 1 / 2 -> separation direction (0:x, 1:y, 2:z)
        - caps: bool -> capitalize atom names so they show true colors in nglview+
        - group: bool -> group molecules in pdb file (to show bonds properly in nglview)
        - rotate: 0 / 1 / 2 -> rotate 90 degrees in (0:x, 1:y, 2:z) axis (view in xy plane)
    """
    if move is 'auto':
        translation_vectors = arrange_structure_positions(len(args),
                                                          div=div,
                                                          distance=distance)
    elif move is 'single':
        translation_vectors = axis_translation(len(args),
                                               distance=distance[0],
                                               axis=axis)
    else:
        translation_vectors = [[0, 0, 0]] * len(args)

    atom_names = []
    atom_coors = []
    group_numbers = []
    for mol_index, (molecule, vec) in enumerate(zip(args, translation_vectors),
                                                start=1):
        atom_names += molecule.atom_names
        coordinates = molecule.atom_coors
        if rotate is not None:
            coordinates = rotate_90(coordinates, axis=rotate)
        coordinates = translate(coordinates, vector=vec)
        atom_coors += coordinates
        group_numbers += [mol_index] * len(molecule.atom_names)

    # nglview require atom names in all caps to color them properly
    if caps:
        atom_names = [name.upper() for name in atom_names]

    # nglview requires molecules to be grouped separately to show proper bonding
    if not group:
        group_numbers = [1] * len(atom_names)
    temp_pdb_file = tempfile.NamedTemporaryFile(mode='w+', suffix='.pdb')
    write_pdb(temp_pdb_file, atom_names, atom_coors, group=group_numbers)

    view = nglview.show_structure_file(temp_pdb_file.name)
    view.camera = camera
    temp_pdb_file.close()

    if save is not None:
        with open(save, 'w') as save_file:
            write_pdb(save_file, atom_names, atom_coors, group=group_numbers)

    return view