Giter VIP home page Giter VIP logo

nglview's Introduction

Citation | Installation | Example | Usage | Command line | API doc | Interface classes | Website | Acknowledgment

Build Status Build Extension Status

Try nglview online: Binder

An IPython/Jupyter widget to interactively view molecular structures and trajectories. Utilizes the embeddable NGL Viewer for rendering. Support for showing data from the file-system, RCSB PDB, simpletraj and from objects of analysis libraries mdtraj, pytraj, mdanalysis, ParmEd, rdkit, ase, HTMD, biopython, cctbx, pyrosetta, schrodinger's Structure

Should work with Python 3. If you experience problems, please file an issue.

Ask question about usage? Please post here

membrane

Table of contents

Installation

Released version

  • Available on conda-forge channel

    conda install nglview -c conda-forge
  • Available on PyPI

   pip install nglview

Jupyterlab: nglview works best with jupyterlab >= 3.0 and no further steps needed. Known to work versions

nglview lab notebook ipywidgets Known issue(s)
3.1.0 4.0.10 7.0.6 8.1.1 HTML embed doesn't work
3.0.8 4.0.10 7.0.6 8.1.1 show_pdbid doesn't work

Notes

If you are using notebook v5.0, you need to increase the iopub_data_rate_limit to visualize big structure (e.g: solvated system)

jupyter notebook --NotebookApp.iopub_data_rate_limit=10000000

Development version

Requirement: ipywidgets >= 7.0, notebook >= 4.2

The development version can be installed directly from github:

notebook user

    git clone https://github.com/arose/nglview
    cd nglview
    python setup.py install

    # if you edit files in ./js folder, make sure to rebuild the code
    cd js
    npm install

    # probably need to activate widgetsnbextension
    # python -m ipykernel install --sys-prefix
    # jupyter nbextension enable --py --sys-prefix widgetsnbextension
    # jupyter nbextension enable --py --sys-prefix nglview

    # tested with ipywidgets 5.2.2, notebook 4.2.1

Example

Showcase from users

Usage

Open a notebook

jupyter notebook

and issue

import nglview
view = nglview.show_pdbid("3pqr")  # load "3pqr" from RCSB PDB and display viewer widget
view

A number of convenience functions are available to quickly display data from the file-system, RCSB PDB, simpletraj and from objects of analysis libraries mdtraj, pytraj, mdanalysis, ParmEd, rdkit, HTMD, biopython.

Function Description
show_file(path) Shows any NGL supported file formats (pdb, gro, mol2, sdf, dx, ..) in path
show_pdbid(pdbid) Shows pdbid fetched from RCSB PDB
show_simpletraj(struc_path, traj_path) Shows structure & trajectory loaded with simpletraj
show_mdtraj(traj) Shows MDTraj trajectory traj
show_pytraj(traj) Shows PyTraj trajectory traj
show_parmed(structure) Shows ParmEd structure
show_mdanalysis(univ) Shows MDAnalysis Universe or AtomGroup univ
show_rdkit(mol) Shows rdkit rdkit.Chem.rdchem.Mol
show_ase(atoms) Shows ase Atoms
show_asetraj(traj) Shows ase trajectory traj
show_pymatgen(struct) Shows pymatgen Structure
show_htmd(mol) Shows HTMD Molecules
show_biopython(mol) Shows Biopython structural entities
show_iotbx(mol) Shows cctbx's iotbx structure
show_rosetta(pose) Shows pyrosetta's Pose
show_iodata(obj) Shows iodata's IOData
show_psi4(obj) Shows psi4's Molecule
show_qcelemental Shows QCelementary's Molecule
show_openbabel Shows openbabel's OMol
show_prody Shows prody's Ensemble or AtomGroup

API

Representations

view.add_representation('cartoon', selection='protein')

# or shorter
view.add_cartoon(selection="protein")
view.add_surface(selection="protein", opacity=0.3)

# specify color
view.add_cartoon(selection="protein", color='blue')

# specify residue
view.add_licorice('ALA, GLU')

# clear representations
view.clear_representations()

# update parameters for ALL cartoons of component 0 (default)
view.update_cartoon(opacity=0.4, component=0)

# remove ALL cartoons of component 0 (default)
view.remove_cartoon(opacity=0.4, component=0)

# Not using default representation
view = nv.show_file('your.pdb', default=False)
view.center()
view.add_rope()

Representations can also be changed by overwriting the representations property of the widget instance view. The available type and params are described in the NGL Viewer documentation.

view.representations = [
    {"type": "cartoon", "params": {
        "sele": "protein", "color": "residueindex"
    }},
    {"type": "ball+stick", "params": {
        "sele": "hetero"
    }}
]

The widget constructor also accepts a representation argument:

initial_repr = [
    {"type": "cartoon", "params": {
        "sele": "protein", "color": "sstruc"
    }}
]

view = nglview.NGLWidget(struc, representation=initial_repr)
view

Properties

# set the frame number
view.frame = 100
# parameters for the NGL stage object
view.stage.set_parameters(**{
    # "percentages, "dist" is distance to camera in Angstrom
    "clipNear": 0, "clipFar": 100, "clipDist": 10,
    # percentages, start of fog and where on full effect
    "fogNear": 0, "fogFar": 100,
    # background color
    "backgroundColor": "black",
})

# note: NGLView accepts both origin camel NGL keywords (e.g. "clipNear")
# and snake keywords (e.g "clip_near")
# parameters to control the `delay` between snapshots
# change `step` to play forward (positive value) or backward (negative value)
# note: experimental code
view.player.parameters = dict(delay=0.04, step=-1)
# update camera type
view.camera = 'orthographic'
# change background color
view.background = 'black'

Trajectory

# adding new trajectory
view.add_trajectory(traj)
# traj could be a `pytraj.Trajectory`, `mdtraj.Trajectory`, `MDAnalysis.Universe`,
# `parmed.Structure`, `htmd.Molecule` or derived class of `nglview.Trajectory`

# change representation
view[0].add_cartoon(...) # equal to view.add_cartoon(component=0)
view[1].add_licorice(...) # equal to view.add_licorice(component=1)

Add extra component

# Density volumes (MRC/MAP/CCP4, DX/DXBIN, CUBE)
# Or adding derived class of `nglview.Structure`
view.add_component('my.ccp4')

# add component from url
view.add_component('rcsb://1tsu.pdb')
# NOTE: Trajectory is a special case of component.

Mouse

# coot mouse style (https://en.wikipedia.org/wiki/Coot_(software))
view.stage.set_parameters(mouse_preset='coot')

Interaction controls

Movie making

Require: moviepy (pip install moviepy)

from nglview.contrib.movie import MovieMaker
movie = MovieMaker(view, output='my.gif', in_memory=True)
movie.make()

Embed widget

embed

API doc

Command line

# open a notebook and import nglview
nglview

# Require installing pytraj (PR for other backends is welcome)
# open notebook, load `my.pdb` to pytraj's trajectory then display `view`
nglview my.pdb

# load density data
nglview my.ccp4

# open notebook, create trajectory with given topology `my.parm7` and trajecotry file `traj.nc`,
# then display `view`
nglview my.parm7 -c traj.nc

# load all trajectories with filename ending with 'nc'
# make sure to use quote " "
nglview my.parm7 -c "*.nc"

# open notebook, copy content from `myscript.py`
nglview myscript.py

# create a remote notebook
# just follow its instruction
nglview my.pdb --remote
nglview my.parm7 -c traj.nc --remote
nglview mynotebook.ipynb --remote

# demo (don't need pytraj)
nglview demo

# specify web browser
nglview my.pdb --browser=google-chrome

FAQ

Q&A

Website

Talks

Talks about NGL and nglview

Contributing

Join us here

Projects integrating NGLView

(Feel free to make a PR to add/remove your project here. Thanks.)

  • AMBER - A package of programs for molecular dynamics simulations of proteins and nucleic acids
  • mbuild - A hierarchical, component based molecule builder
  • deepchem - Deep-learning models for Drug Discovery and Quantum Chemistry
  • htmd - High throughput molecular dynamics simulations
  • Moleidoscope - Molecular kaleidoscope
  • ssbio - Tools for enabling structural systems biology
  • hublib - hublib is a Python library for the HUBzero science gateway platform.
  • molPX: ipython API to visualize MD-trajectories along projected trajectories
  • nanoribbon
  • ase: Atomic Simulation Environment
  • pida: Software for analyzing multiple protein-protein interaction docking solutions,
  • pytim
  • MobleyLab/drug-computing Educational materials for, and related to, UC Irvine's Drug Discovery Computing Techniques course.
  • pyiron: an integrated development environment for implementing, testing, and running simulations in computational materials science.
  • BioSimSpace: An interoperable framework for biomolecular simulation
  • pyrod: PyRod - Tracing water molecules in molecular dynamics simulations
  • kugupu: kugupu - a molecular network generator to study charge transport pathways in amorphous materials
  • pnab: proto-Nucleic Acid Builder
  • opencadd: A Python library for structural cheminformatics
  • teachopencadd: TeachOpenCADD: a teaching platform for computer-aided drug design (CADD) using open source packages and data
  • query.libretexts.org: query.libretexts.org
  • datamol: A python library to work with molecules.
  • dynophores: Dynamic pharmacophore modeling of molecular interactions
  • pychemcurv: Discrete and local curvature applied to chemistry and chemical reactivity
  • AutoSolvate: Automated workflow for generating quantum chemistry calculation of explicitly solvated molecules
  • plipify: PLIPify: Protein-Ligand Interaction Frequencies across Multiple Structures
  • Melodia: Differential Geometry of Proteins Backbones
  • pyrosetta_viewer3d: Display PackedPose objects, Pose objects, or PDB files within a Jupyter notebook and Google Colab
  • py4vasp: Python interface for VASP
  • eminus: A plane wave density functional theory code.
  • MolSysMT: Molecular Systems Multi-Tool

Acknowledgment

Cite

If you would like to acknowledge our work, feel free to cite:

Hai Nguyen, David A Case, Alexander S Rose; NGLview - Interactive molecular graphics for Jupyter notebooks, Bioinformatics, , btx789, https://doi.org/10.1093/bioinformatics/btx789

License

Generally MIT, see the LICENSE file for details.

nglview's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

nglview's Issues

Orthographic view?

Couldn't find anything in the docs, but is there a way to switch the viewer to an orthographic mode instead of perspective?

add_representation is too sensitive to space

FYI:

working

view.add_representation('cartoon', color='residueindex')

NOT working (there is extra space in cartoon word

view.add_representation('cartoon ', color='residueindex')
  • can you confirm in your computer?
  • if my statement is true, what's our solution here, either
    • I can use python to strip left and right spaces
    • you take care js side

more English please

from this issue: #4

w = NGLWidget(...)
w.representations = [
    { "type": "cartoon", "params": {
        "sele": "protein", "color": "residueindex"
    } },
    { "type": "ball+stick", "params": {
        "sele": "hetero"
    } }
]

Since user need to specify options to change representation, should we use more complete English keyword? For example: does 'sele' mean 'select' or something else?

beautiful rendering

I am collecting examples about beautiful color schemes (IMO).

I am not good at colorizing stuff, so it's great if there is anyone interested in.

  • from molsoft

image

image

Automatically refresh static assets/resources

For the notebook, static assets/resources (like JavaScript files) are installed with notebook.nbextensions.install_nbextension. When the assets are updated (often during development, for the user upon a new release) the browser still has them cached and a "forced" refresh is needed. This should happen automatically for new releases and caching should be switched off during development.

better add_representation

currently whenever add_representation is called, the viewer is re-rendered (?) so the transition is not smooth (structure disappears and reload).

try yourself in notebook

1st cell

import pytraj as pt
import nglview as nv

t0 = pt.fetch_pdb('3pqr')
view = nv.show_pytraj(t0)

view.representations = []
view.add_representation('cartoon', color='residueindex')
view

2nd cell (cause non-smooth transition)

view.add_representation('label', '.CA', color='blue')

Preparing 0.4 release

  • Update API documentation
  • Update Changelog
  • Add notebook examples
  • Note support for pytraj, mdanalysis, mdtraj, simpletraj prominently in README
  • Resolve dependency issue #17

wishlist: animation

for example: rotate molecule, then zoom to specific region, then change the representation, update color, ...

Not sure how difficult it is, but it's good for making movie, for using notebook for presentation.

center vs center_view vs centerView

center vs center_view vs centerView. Which one is better name? else?

def center_view(zoom=True, selection='*'):
    self._remote_call('centerView', target='viewer', args=[zoom, selection])

add alias for commonly used representations?

for example

view.add_representation('cartoon', selection='not hydrogen', color='red')

alias

view.cartoon('not hydrogen', color='red')

and so on.

What do you think?
(learn from chemview and pv programs).

advantage: we can use autocompletion.

Error importing nglview (windows 7)

I installed nglview via conda on windows 7 and got the following error when I tried to import nglview in a jupyter notebook

symlink C:\Users\yalhadid\AppData\Roaming\jupyter\nbextensions\nglview -> C:\Anaconda3\lib\site-packages\nglview\html\static

---------------------------------------------------------------------------
OSError                                   Traceback (most recent call last)
<ipython-input-1-24944f7c2fa8> in <module>()
----> 1 import nglview

C:\Anaconda3\lib\site-packages\nglview\__init__.py in <module>()
    445     })
    446 
--> 447 install(symlink=True)

C:\Anaconda3\lib\site-packages\nglview\__init__.py in install(user, symlink)
    436     staticdir = resource_filename('nglview', os.path.join('html', 'static'))
    437     install_nbextension(staticdir, destination='nglview',
--> 438                         user=user, symlink=symlink)
    439 
    440     cm = ConfigManager()

C:\Anaconda3\lib\site-packages\notebook\nbextensions.py in install_nbextension(path, overwrite, symlink, user, prefix, nbextensions_dir, destination, verbose)
    202                 if verbose >= 1:
    203                     print("symlink %s -> %s" % (full_dest, path))
--> 204                 os.symlink(path, full_dest)
    205         elif os.path.isdir(path):
    206             path = pjoin(os.path.abspath(path), '') # end in path separator

OSError: symbolic link privilege not held


release v0.5 todo

  • autorun some basic notebooks
  • need to update new NGL features
  • move LOG to different file
  • probably update GIF to README (with new NGL version): its render is very pretty.
  • add versions requirement in setup.py

Q: workflow?

what's your workflow when modifiying ngl, then update code to nglview?

I tried to modified nglview/html/static/ngl.js but my VIM program was freezing because it does not like that many lines of codes (41K). Can you just keep the original files from ngl (https://github.com/arose/ngl/tree/master/js/ngl)

If keeping the original files degrades the performance, can you post the exact commands you used? thanks from JS noob.

Non python 3 compatible import in MDAnalysis connector

MDAnalysis should not be used with python 3 yet, as the port is highly experimental at that point. I tried however, but hit an issue in nglview while using nglview.show_mdanalysis:

---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-99-ae3b559d7118> in <module>()
----> 1 v = nglview.show_mdanalysis(pi)

/home/jon/Envs/lipid3/lib/python3.4/site-packages/nglview/__init__.py in show_mdanalysis(atomgroup, **kwargs)
    118     '''
    119     structure_trajectory = MDAnalysisTrajectory(atomgroup)
--> 120     return NGLWidget(structure_trajectory, **kwargs)
    121 
    122 

/home/jon/Envs/lipid3/lib/python3.4/site-packages/nglview/__init__.py in __init__(self, structure, trajectory, representations, parameters, **kwargs)
    347         if parameters:
    348             self.parameters = parameters
--> 349         self.set_structure(structure)
    350         if trajectory:
    351             self.trajectory = trajectory

/home/jon/Envs/lipid3/lib/python3.4/site-packages/nglview/__init__.py in set_structure(self, structure)
    372     def set_structure(self, structure):
    373         self.structure = {
--> 374             "data": structure.get_structure_string(),
    375             "ext": structure.ext,
    376             "params": structure.params

/home/jon/Envs/lipid3/lib/python3.4/site-packages/nglview/__init__.py in get_structure_string(self)
    313                 "'MDAnalysisTrajectory' requires the 'MDAnalysis' package"
    314             )
--> 315         import cStringIO
    316         u = self.atomgroup.universe
    317         u.trajectory[0]

ImportError: No module named 'cStringIO'

The line numbers correspond to nglview-0.4 freshly installed with pip on python 3.4. The faulty import is now on line 386 of __init__.py.

Binary messages between kernel and browser

Does IPython support binary messages between kernel and browser? Modern browsers can receive binary and save it in an ArrayBuffer. This would make sending coordinates and topology data to the browser more efficient. It is often in an binary format in the kernel and can consumed as such in the browser thus avoiding converting/parsing to/from JSON.

new syntax for adding representations

(I am not sure about this issue's title, might update later).

What do you think about this syntax

import nglview as nv
w= nv.NGLWidget(...)

# new syntax
w.select('protein').representation('cartoon', **kwd)
w.select('hetero').representation('ball+stick', **kwd)

or

# new syntax
w.select('protein', representation='cartoon', **kwd)
w.select('hetero', representation='ball+stick', **kwd)

which is equal to

w.representations = [
    { "type": "cartoon", "params": {
        "sele": "protein", "color": "residueindex"
    } },
    { "type": "ball+stick", "params": {
        "sele": "hetero"
    } }
]

of course, we can still massively update representation via w.representations = ...

cache coordinates

I just visited bokeh project and they are still looking solution to send data to JS.
while waiting solution, I come up with dirty hack: trying to send all coordinates to JS side.

bokeh/bokeh#2204

  • first, we dont need to sync 'coordinates' between Python and JS. too slow.
  • in Python, call
view.send({'type': 'coordinatesdict', 'data': view.trajectory.get_coordinate_dict()})
  • in JS, create on_msg function to receive the message.
            // get message from Python
       this.coordinatesdict = undefined;
       this.model.on( "msg:custom", function (msg) {
                    this.on_msg( msg );
       }, this);

        on_msg: function(msg){
            if ( msg.type == 'call_method' ){
                 ...
            }else if( msg.type == 'coordinatesdict'){
                this.coordinatesdict = msg.data;
                console.log ( "received coordinatesdict" );
            }
        }

if frame changed

        frameChanged: function(){
            var frame = this.model.get( "frame" );
            var coordinates = this.coordinatesdict[frame];
            var component = this.structureComponent;
            if( coordinates && component ){
                var coords = new Float32Array( coordinates );
                component.structure.updatePosition( coords );
                component.updateRepresentations( { "position": true } );
            }

        },

I have not done benchmark yet but this should be much faster than sending coordinates from Python to JS every time frame changed.

mybinder

just create an issue so we can close it :))

add load_... or similar to load other packages?

can you add this.

something like

import pytraj as pt
import nglview as nv

traj = pt.load(fn, tn)
view = nv.load_pytraj(traj, **kwd)
# view = nv.load_mdanalysis(traj, **kwd)
# view = nv.load_mdtraj(traj, **kwd)

and so on for other package.
Aim is to hide the step of creating PytrajTrajectory and then calling NGLWidget(...).

link viewer

What's about link two widgets together (share rotation matrix?)

tz2_closest_100

MDAnalysis.Universe wrapper?

It would be awesome to be able to pass an MDAnalysis.Universe object into a wrapper object similar to nglview.MDTrajTrajectory, with the wrapper pulling coordinate information through that object. Haven't looked in detail at the library to see the best way to go about it, but it I imagine there could be pretty wild and wonderful ways to take advantage of MDAnalysis' feature set, including perhaps making selections using AtomGroup objects.

create new organization for nglview?

what do you think about create ngl organization? or anything that has fancy name.

pros:

  • you (@arose) can make a PR and let travis do the install and testing rather pushing directly to arose/nglview
  • Other can review your PR :D

rename `html` folder

there is nothing related to html. So what's about 'static' or 'js' or something else?

get_atom_indices

currently, AMBER use non-friendly atom mask syntax (but very flexible). Since we are proposing passing atom indices for nglview, we can also get the atom indices back by using nglview's selection too.

atom_indices = view.get_atom_indices(selection='charged')

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.