Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Usage questions about nglview: Please ask here first [3] #948

Closed
hainm opened this issue Feb 15, 2021 · 70 comments
Closed

Usage questions about nglview: Please ask here first [3] #948

hainm opened this issue Feb 15, 2021 · 70 comments
Labels

Comments

@hainm
Copy link
Collaborator

hainm commented Feb 15, 2021

For any questions relating to how/why/ ... Or anything you don't know where to ask.
For bug, suggestion or anything you want to ask separately, please open seperate issue

Previous Q&As

Or click the Q&A label.

@dominiquesydow
Copy link
Contributor

Hi!

Thanks for your great work on the NGL Viewer - highly appreciated!

In this minimal example, I have two point clouds that I have added each with add_buffer (a blue cloud and a cyan cloud).
Both show up with the label "shape" in the NGL Viewer GUI (in the menu on the right).

Is there a way to rename these "shape" labels (to e.g. "blue cloud" and "cyan cloud")?

image

Here my minimal code example: https://gist.github.com/dominiquesydow/0cc044a9936836bd3ceb096697307870

FYI: I am using add_buffer because these clouds usually contain much more points than in this example - and I would like to load all points in a cloud as one "component".


The documentation for add_buffer says:

Examples
--------
>>> view.shape.add_buffer("cone",
...     position1=[0, 0, 0],
...     position2=[1, 1, 1],
...     color=[1, 0, 0],
...     color2=[0, 1, 0],
...     radius= [1])

Is there maybe another argument that I can pass here to add a name? If so, I have not found the right keyword, yet.

@hainm
Copy link
Collaborator Author

hainm commented Mar 4, 2021

hi @dominiquesydow, that name is hard coded.

You can to hack the JS code:

Screen Shot 2021-03-04 at 5 47 12 PM

CODE

view._js('''

var params = {
'position1': [0, 0, 0],
'position2': [1, 1, 1],
'color': [1, 0, 0],
'color2' :[0, 1, 0],
'radius': [1],}

var shape = new NGL.Shape("abc");
var buffer = new NGL.ConeBuffer(params);
shape.addBuffer(buffer);
var shapeComp = this.stage.addComponentFromObject(shape);
shapeComp.addRepresentation("buffer");

'''
        )

@dominiquesydow
Copy link
Contributor

Hi @haim, thanks a lot for your super quick help - it works perfectly!

@taidbui
Copy link

taidbui commented Mar 7, 2021

Hi @hainm, do you know how to select atoms using their atom types as implemented in lammps?

Many thanks,

Tai

@hainm
Copy link
Collaborator Author

hainm commented Mar 7, 2021

Hi, no I don’t.

@hainm
Copy link
Collaborator Author

hainm commented Mar 8, 2021

@taidbui
Copy link

taidbui commented Mar 10, 2021

@hainm, thanks a lot for sharing this. It's very helpful.

@sbliven
Copy link

sbliven commented Mar 11, 2021

Is it possible to display all models simultaneously in nglview? In ngl this is the default, but I can't figure it out in nglview.

Example multi-model structure:
1itbA_cesymm.mmtf.zip

@hainm
Copy link
Collaborator Author

hainm commented Mar 11, 2021

Is it possible to display all models simultaneously in nglview? In ngl this is the default, but I can't figure it out in nglview.

Example multi-model structure:
1itbA_cesymm.mmtf.zip

@sbliven Please see this thread: #765 (comment)

@enricogandini
Copy link

How is the initial _camera_orientation generated?

I need to display two NGLWidget objects side by side, each with a different molecule. I want to find a "best" initial orientation for both of them.
So, I thought I should calculate the initial _camera_orientation for a single molecule, then perform some operation that I decide (some sort of average?) to get a single "best" _camera_orientation for both molecules, and then use _set_camera_orientation on both NGLWidget objects.
I was not able to find the function that is used to calculate the initial _camera_orientation for a single molecule.

@hainm
Copy link
Collaborator Author

hainm commented Mar 16, 2021

hi @enricogandini: The value comes from NGL:

serialize_camera_orientation(){

https://github.com/nglviewer/ngl/blob/963b4fecde843fdf80c580e8f7bd55989db6a6f6/src/controls/viewer-controls.ts#L110

@enricogandini
Copy link

Thank you @hainm!

@wavy007
Copy link

wavy007 commented Mar 25, 2021

How would I go about monitoring a "loaded" signal for a large surface representation so that I could put a little loading symbol into the webpage while the surface representation was loading?

Basically I would like an equivalent of stage.signals.clicked.add(function() {....}) that fires when my surface representation (e.g. surfaceRep) finishes loading instead of when the stage is clicked.

@hainm
Copy link
Collaborator Author

hainm commented Mar 25, 2021

so that I could put a little loading symbol into the webpage while the surface representation was loading?

hi @wavy007: Please ask the question in NGL repo: https://github.com/nglviewer/ngl/issues
(Are you using nglview or NGL?)

@wavy007
Copy link

wavy007 commented Mar 25, 2021

Thanks, I've just posted there. I'm using NGL! Sorry about that!

@dlesnicki
Copy link

Topology changing with time

Hello,

I am trying to make a movie with NGLView with reactions. I want to display a trajectory for which the name of atoms changes with time. Is it possible to have the topology change per frame?

Minimal example in which "Na" at time 0 becomes "O" at time 1: (nice chemistry O_o )

file.xyz

         1
         
 Na  -48.014929215686692        56.934336168843998       -25.598812893054085     
         1
         
 O   -47.994817427741083        57.260234869219786       -25.899648025106263  

file.pdb

CRYST1    152.3    152.3    152.3  90.00  90.00  90.00 P 1           1
ATOM      1 Na    X      1     -48.015  56.934 -25.599  0.00  0.00          Na  
END
ATOM      1 O     X      1     -47.995  57.260 -25.900  0.00  0.00           O  
END

I tried loading with mdtraj but realized the topology is fixed. Then saw issue #620 but cannot manage to adapt it to my use-case.

@hainm
Copy link
Collaborator Author

hainm commented Mar 26, 2021

Topology changing with time

Hello,

I am trying to make a movie with NGLView with reactions. I want to display a trajectory for which the name of atoms changes with time. Is it possible to have the topology change per frame?

Minimal example in which "Na" at time 0 becomes "O" at time 1: (nice chemistry O_o )

file.xyz

         1
         
 Na  -48.014929215686692        56.934336168843998       -25.598812893054085     
         1
         
 O   -47.994817427741083        57.260234869219786       -25.899648025106263  

file.pdb

CRYST1    152.3    152.3    152.3  90.00  90.00  90.00 P 1           1
ATOM      1 Na    X      1     -48.015  56.934 -25.599  0.00  0.00          Na  
END
ATOM      1 O     X      1     -47.995  57.260 -25.900  0.00  0.00           O  
END

I tried loading with mdtraj but realized the topology is fixed. Then saw issue #620 but cannot manage to adapt it to my use-case.

hi @dlesnicki
Please follow this thread: #589 (comment)

@dlesnicki
Copy link

Topology changing with time

Hello,
I am trying to make a movie with NGLView with reactions. I want to display a trajectory for which the name of atoms changes with time. Is it possible to have the topology change per frame?
Minimal example in which "Na" at time 0 becomes "O" at time 1: (nice chemistry O_o )
file.xyz

         1
         
 Na  -48.014929215686692        56.934336168843998       -25.598812893054085     
         1
         
 O   -47.994817427741083        57.260234869219786       -25.899648025106263  

file.pdb

CRYST1    152.3    152.3    152.3  90.00  90.00  90.00 P 1           1
ATOM      1 Na    X      1     -48.015  56.934 -25.599  0.00  0.00          Na  
END
ATOM      1 O     X      1     -47.995  57.260 -25.900  0.00  0.00           O  
END

I tried loading with mdtraj but realized the topology is fixed. Then saw issue #620 but cannot manage to adapt it to my use-case.

hi @dlesnicki
Please follow this thread: #589 (comment)

Thank you @hainm for your help! Unfortunately it did not solve my case. As you can see on my screenshot, the structures for frame 0 and 1 have both the correct coordinates but frame 1 has a wrong atom name. Should I change something in get_structure_string()?
nglview

@hainm
Copy link
Collaborator Author

hainm commented Mar 27, 2021

hi @dlesnicki: You need to write your own get_structure_string function to return the string of pdb content.

@marvinbernhardt
Copy link

How to display a trajectory that I have in form of a numpy array?

I have a trajectory generated directly in python and I don't want to write it to disk. What is the easiest and/or most straightforward way to display this trajectory with nglview?

@hainm
Copy link
Collaborator Author

hainm commented Apr 11, 2021

How to display a trajectory that I have in form of a numpy array?

I have a trajectory generated directly in python and I don't want to write it to disk. What is the easiest and/or most straightforward way to display this trajectory with nglview?

hi @marvinbernhardt: You can use pytraj or any supported backends here

Screen Shot 2021-04-10 at 9 01 48 PM

@marvinbernhardt
Copy link

Hey hainm! Thank you for your answer, that is certainly one way to achieve what I asked for.

What I need this for is teaching. I have modified MIND to save the trajectory (LJ liquid) directly in a numpy array. Now I am looking for a (as simple as possible) way for students to look at their trajectory, directly from python. So creating and loading a pdb file is not ideal. If you have any idea, please let me know. I looked at some of the backends, but they mostly are made for loading files.

@hainm
Copy link
Collaborator Author

hainm commented Apr 11, 2021

hi @marvinbernhardt: You still need to provide something (e.g: pdb, sdf, mol2 ...file) to create a topology for your structure so nglview can render the initial frame. How can a program render your pure xyz coordinates?

You can use this code to make your own Trajectory reader to feed to nglview:

nglview/nglview/adaptor.py

Lines 340 to 368 in b1d50de

@register_backend('pytraj')
class PyTrajTrajectory(Trajectory, Structure):
'''PyTraj adaptor.
Example
-------
>>> import nglview as nv
>>> import pytraj as pt
>>> traj = pt.load(nv.datafiles.TRR, nv.datafiles.PDB)
>>> t = nv.PyTrajTrajectory(traj)
>>> w = nv.NGLWidget(t)
>>> w
'''
def __init__(self, trajectory):
self.trajectory = trajectory
self.ext = "pdb"
self.params = {}
self.id = str(uuid.uuid4())
def get_coordinates(self, index):
return self.trajectory[index].xyz
@property
def n_frames(self):
return self.trajectory.n_frames
def get_structure_string(self, index=0):
return _get_structure_string(self.trajectory[index:index + 1].save)

@marvinbernhardt
Copy link

marvinbernhardt commented Apr 12, 2021

I ended up using mdtraj, which is flexible enough to not use any files. Here is my wrapper function in case anyone is interested

def show_numpy_trajectory(traj, box, aspect_ratio=5):
    """Show Numpy trajectory with constant box.
    
    All atoms will be shown as argon atoms.
    
    Keyword arguments:
    traj -- Numpy array with shape (n_steps, 3, n_atoms) containing positions in nm
    box -- Numpy array with shape (3) in nm
    aspect_ratio -- parameter chaning the sphere size
    
    Returns:
    nglview.widget.NGLWidget
    """
    # create an argon topology
    top = md.Topology()
    chain = top.add_chain()
    for i in range(traj.shape[2]):
        residue = top.add_residue('AR', chain)
        top.add_atom('Ar', md.element.argon, residue)
    # create trajectory
    n_frames = len(traj)
    t = md.Trajectory(traj.swapaxes(1, 2), topology=top,
                      unitcell_lengths=np.repeat(box[np.newaxis, ...], n_frames, axis=0),
                      unitcell_angles=np.ones((n_frames, 3))*90.0)
    # create view and show trajectory
    view = nv.show.show_mdtraj(t)
    view.clear_representations()
    view.add_representation('ball+stick', aspectRatio=aspect_ratio)
    view.add_unitcell()
    return view

@gph82
Copy link
Contributor

gph82 commented Jun 2, 2021

I think this has been asked before and answered with NO.

When using iwd.display(gui=True), is there any way to programatically collapse a given component's menu, or the individual representation menus? I'm asking for the equivalent to hitting the "collapseAll"/minus sign icon.

Thanks!

@hainm
Copy link
Collaborator Author

hainm commented Jun 2, 2021

I think this has been asked before and answered with NO.

When using iwd.display(gui=True), is there any way to programatically collapse a given component's menu, or the individual representation menus? I'm asking for the equivalent to hitting the "collapseAll"/minus sign icon.

Thanks!

hi @gph82
I don't know (yet). But just FYI that we brought NGL GUI style to the notebook now: #830

The naive GUI with gui=True in your question is experimental and I don't want to support it anymore. Cheers.

@gph82
Copy link
Contributor

gph82 commented Jun 3, 2021

Hi @hainm, yeah I had noticed, that's great, and has actually made me us nglviewer much more lately.

Anyway, I know why the question sounded familiar, I myself (:facepalm: ) had followed-up on a similar question here, without success: nglviewer/ngl#745

@dprada
Copy link

dprada commented Sep 2, 2021

How to get the unit cell vectors from different frames?

Hi! How can be the unit cell vectors from different frames be obtained?

For example, working with the demo trajectory, the coordinates from a given frame (3, for instance) can be obtained this way:

import mdtraj as md
import nglview as nv

traj = md.load(nv.datafiles.XTC, top=nv.datafiles.GRO)
view = nv.show_mdtraj(traj)
view.component_0.get_coordinates(3)

Is there a way to get the unit cell vectors for frame 3 from the nglview.NGLWidget object? The pbc box in 'nv.datafiles.XTC' is not constant in time.

Thanks in advance!

@hainm
Copy link
Collaborator Author

hainm commented Sep 2, 2021

How to get the unit cell vectors from different frames?

Hi! How can be the unit cell vectors from different frames be obtained?

For example, working with the demo trajectory, the coordinates from a given frame (3, for instance) can be obtained this way:

import mdtraj as md
import nglview as nv

traj = md.load(nv.datafiles.XTC, top=nv.datafiles.GRO)
view = nv.show_mdtraj(traj)
view.component_0.get_coordinates(3)

Is there a way to get the unit cell vectors for frame 3 from the nglview.NGLWidget object? The pbc box in 'nv.datafiles.XTC' is not constant in time.

Thanks in advance!

hi @dprada

No, there is no way. Can you get that from traj?

view.component_0.get_coordinates(3)

PS: view.component_0 is deprecated syntax. May be use view[0]

@dprada
Copy link

dprada commented Sep 2, 2021

Ok. Thanks for the tip! I will use view[0] from now on.

@khoroshyy
Copy link

Hi.
Is there any way to load mol2 with multiple structures without splitting it before?
Basically, I would like to show it as a trajectory.
Thanks.
Petro.

@hainm
Copy link
Collaborator Author

hainm commented Sep 6, 2021

Hi.
Is there any way to load mol2 with multiple structures without splitting it before?
Basically, I would like to show it as a trajectory.
Thanks.
Petro.

@khoroshyy: do the structures have the same topology with different coordinates?

@khoroshyy
Copy link

Hi.
Is there any way to load mol2 with multiple structures without splitting it before?
Basically, I would like to show it as a trajectory.
Thanks.
Petro.

@khoroshyy: do the structures have the same topology with different coordinates?

Yes, they are the same molecules in different conformations. 10 conformation per file.
I have about 20 files, which I want to combine in a trajectory.

@khoroshyy
Copy link

But if there is a way to load different molecules I would be interested also.

@hainm
Copy link
Collaborator Author

hainm commented Sep 7, 2021

Hi.
Is there any way to load mol2 with multiple structures without splitting it before?
Basically, I would like to show it as a trajectory.
Thanks.
Petro.

@khoroshyy: do the structures have the same topology with different coordinates?

Yes, they are the same molecules in different conformations. 10 conformation per file.
I have about 20 files, which I want to combine in a trajectory.

@khoroshyy: You can try one of the supported packages here (e.g: pytraj, mdtraj, mdanalysis, parmed ...) to load your mol2 file to a trajectory: https://github.com/nglviewer/nglview#usage

Here is an example from pytraj (I am the author):

In [1]: import pytraj as pt

In [2]: fname = 'test/files/multimol.mol2'

In [3]: traj = pt.load(fname, top=fname)

In [4]: traj
Out[4]: 
pytraj.Trajectory, 200 frames: 
Size: 0.000165 (GB)
<Topology: 37 atoms, 1 residues, 1 mols, non-PBC>
           

In [5]: import nglview as nv


In [6]: view = nv.show_pytraj(traj)

In [7]: view

@hainm
Copy link
Collaborator Author

hainm commented Sep 7, 2021

But if there is a way to load different molecules I would be interested also.

nglview does not natively support this because each trajectory requires a single topology.

@khoroshyy
Copy link

@hainm Thanks, I was wondering how to load files without making FF topology for it.

@cadalyjr
Copy link

How to display double/triple bonds?

If traj is the trajectory file for a molecule with double/triple bounds, how do I visualize them?

view = nglview.show_asetraj(traj)
view.clear_representations()
view.add_ball_and_stick()
# ?

@amirhajibabaei
may be play around with multipleBond option.
Screen Shot 2021-06-23 at 12 45 34 AM

I tried the following via python API, but it didn't work. It just shows a single bond

import nglview
from ase.build import molecule

print(nglview.__version__)

traj = [molecule('O2')]

rep = [
    {"type": "ball+stick", "params": {
        "multipleBond": "offset"  # "symmetric"
    }}
]

view = nglview.show_asetraj(traj)
#view.clear_representations()
view.representations = rep
view

hi @fredludlow: Do you have any idea why? Is that the limitation of NGL? thanks.

Thank you so much for this excellent application. I am also struggling to represent multiple bonds. Was there ever any resolution to this question?

@hainm
Copy link
Collaborator Author

hainm commented Sep 22, 2021

How to display double/triple bonds?

If traj is the trajectory file for a molecule with double/triple bounds, how do I visualize them?

view = nglview.show_asetraj(traj)
view.clear_representations()
view.add_ball_and_stick()
# ?

@amirhajibabaei
may be play around with multipleBond option.
Screen Shot 2021-06-23 at 12 45 34 AM

I tried the following via python API, but it didn't work. It just shows a single bond

import nglview
from ase.build import molecule

print(nglview.__version__)

traj = [molecule('O2')]

rep = [
    {"type": "ball+stick", "params": {
        "multipleBond": "offset"  # "symmetric"
    }}
]

view = nglview.show_asetraj(traj)
#view.clear_representations()
view.representations = rep
view

hi @fredludlow: Do you have any idea why? Is that the limitation of NGL? thanks.

Thank you so much for this excellent application. I am also struggling to represent multiple bonds. Was there ever any resolution to this question?

hi @cadalyjr, I don't think so.

@krassowski
Copy link

Is it possible to apply the workaround to the Chrome/Linux NGL (nglviewer/ngl#525) background bug in nglview? In the upstream issue nglStage.viewer.renderer.setClearColor( 0xffffff, 0.01); was suggested but I don't immediately see see if this can be done from nglview API.

@hainm
Copy link
Collaborator Author

hainm commented Sep 27, 2021

Is it possible to apply the workaround to the Chrome/Linux NGL (nglviewer/ngl#525) background bug in nglview? In the upstream issue nglStage.viewer.renderer.setClearColor( 0xffffff, 0.01); was suggested but I don't immediately see see if this can be done from nglview API.

hi @krassowski, please try view._execute_js_code: #768

@krassowski
Copy link

Thank you @hainm, it does something, though it does not fix it

view._execute_js_code('this.stage.viewer.renderer.setClearColor(0xffffff, 0.01);this.stage.viewer.requestRender();')

When I change the second argument I finally get a different background colour but the I get blinking and model disappearing unless actively being rotated.

@hainm
Copy link
Collaborator Author

hainm commented Sep 28, 2021

Thank you @hainm, it does something, though it does not fix it

view._execute_js_code('this.stage.viewer.renderer.setClearColor(0xffffff, 0.01);this.stage.viewer.requestRender();')

When I change the second argument I finally get a different background colour but the I get blinking and model disappearing unless actively being rotated.

hi @krassowski
I am trying to remove the code this.stage.viewer.requestRender(); and I can see the background changed. It's not perfect though, when not rotating the molecule, I get a dark color and get a light color if rotating.

NOT rotating:
image

Would be best to ask NGL developers.

@krassowski
Copy link

This is very silly question, but is there a simple way to display a single chain using show_pdbid? I am a bit confused about the **kwargs as it does not seem to be documented and it seems that no errors are raised if a non-supported key is passed.

@hainm
Copy link
Collaborator Author

hainm commented Sep 29, 2021

This is very silly question, but is there a simple way to display a single chain using show_pdbid?

Show the whole structure and use selection language?
http://nglviewer.org/ngl/api/manual/selection-language.html

I am a bit confused about the **kwargs as it does not seem to be documented and it seems that no errors are raised if a non-supported key is passed.

yeah, just ignore it. I don't recall either. :D

@krassowski
Copy link

So as a naive user I thought that maybe I could just pass a query as a keyword argument to show_pdbid(entity, chain='A'). Would it be a good thing for a PR?

@hainm
Copy link
Collaborator Author

hainm commented Sep 29, 2021

So as a naive user I thought that maybe I could just pass a query as a keyword argument to show_pdbid(entity, chain='A'). Would it be a good thing for a PR?

I think user need to pass the representations (which is a part of kwargs) `

representations=None,

Would it be a good thing for a PR?

I am not sure, this will populate all the selection keys in the link I sent you. Thanks.

@hainm hainm closed this as completed Oct 5, 2021
@hainm
Copy link
Collaborator Author

hainm commented Oct 5, 2021

New thread: #1000

@davidRFB
Copy link

davidRFB commented Feb 24, 2023

Hi ! I am using the dihedral measurement with picked atoms. Its wonderfull !
image
However I would like to know if there is a way of increase the fontsize and change the color in order to differentiate different ones.

used code:

import nglview as nv
view = nv.show_pytraj(traj_CGNoComp,gui=True)
view.clear_representations()
view.add_ball_and_stick(selection='344-346 or DCT')
view.add_surface(selection='@'+",".join([str(i) for i in res_index_NoComp[344]['epsilon']]),opacity=0.5,radius_scale=0.05)
view.center(selection='DCT')
view
`

@hainm
Copy link
Collaborator Author

hainm commented Mar 2, 2023

Hi ! I am using the dihedral measurement with picked atoms. Its wonderfull ! image However I would like to know if there is a way of increase the fontsize and change the color in order to differentiate different ones.

used code:

import nglview as nv
view = nv.show_pytraj(traj_CGNoComp,gui=True)
view.clear_representations()
view.add_ball_and_stick(selection='344-346 or DCT')
view.add_surface(selection='@'+",".join([str(i) for i in res_index_NoComp[344]['epsilon']]),opacity=0.5,radius_scale=0.05)
view.center(selection='DCT')
view
`

hi @davidRFB, unfortunately I don't think there is a way to do that. Cheers.

@fredludlow
Copy link

However I would like to know if there is a way of increase the fontsize and change the color in order to differentiate different ones.

@davidRFB - When you pick atoms, they're added to a global instance of DihedralRepresentation, which takes parameters labelSize etc - @hainm, this is accessible through the stage, I don't know nglview well enough to say if that makes it accessible?

Alternatively, if your'e building a figure, you can add an explicit DihedralRepresentation (again, not sure if this is exposed through the nglview API? It's a representation of type "dihedral")

@hainm
Copy link
Collaborator Author

hainm commented Mar 8, 2023

(again, not sure if this is exposed through the nglview API? It's a representation of type "dihedral")

@fredludlow unfortunately it's not exposed to nglview's API yet.
But one can access the stage directly via

view._js("""
var stage = this.stage;
""")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests