Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
geom : :obj:`mdtraj.Trajectory` object or str with a filename to anything that :obj:`mdtraj` can read
ngl_wdg : an already instantiated widget to add the geom, default is None
n_small : if the geometry has less than n_small residues, force a "ball and stick" represenation
:return: :nglview.widget object
"""
if isinstance(geom, str):
geom = _md.load(geom)
if ngl_wdg is None:
if geom is None:
ngl_wdg = _nglview.NGLWidget()
else:
ngl_wdg = _nglview.show_mdtraj(geom)
else:
ngl_wdg.add_trajectory(geom)
# Let' some customization take place
## Do we need a ball+stick representation?
if geom is not None:
if geom.top.n_residues < n_small:
for ic in range(len(ngl_wdg._ngl_component_ids)):
# TODO FIND OUT WHY THIS FAILS FOR THE LAST REPRESENTATION
#print("removing reps for component",ic)
ngl_wdg.remove_cartoon(component=ic)
ngl_wdg.clear_representations(component=ic)
ngl_wdg.add_ball_and_stick(component=ic)
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
"""
try: # If the graphical packages are not available, the GUI will not work.
import nglview
except ImportError:
raise ImportError("The package nglview needs to be installed for the plot3d() function!")
# Always visualize the parent basis
parent_basis = self.get_parent_basis()
if select_atoms is None:
select_atoms = np.array(len(parent_basis)*[True])
else:
select_atoms = np.array(select_atoms)
if custom_array is not None:
custom_array = custom_array[select_atoms]
struct = nglview.TextStructure(self._ngl_write_structure(parent_basis.get_chemical_symbols()[select_atoms],
self.positions[select_atoms], self.cell, custom_array=custom_array))
view = nglview.NGLWidget(struct)
if spacefill:
if color_scheme is None and custom_array is not None:
color_scheme = 'occupancy'
elif color_scheme is None:
color_scheme = 'element'
view.add_spacefill(radius_type='vdw', color_scheme=color_scheme, radius=particle_size)
# view.add_spacefill(radius=1.0)
view.remove_ball_and_stick()
else:
view.add_ball_and_stick()
if show_cell:
if parent_basis.cell is not None:
view.add_unitcell()
if custom_3darray is not None:
for arr, pos in zip(custom_3darray[select_atoms], self.positions[select_atoms]):
view.shape.add_arrow(list(pos), list(pos+arr), list(0.5*arr/np.linalg.norm(arr)+0.5), 0.2)
nglview.NGLWidget
A nglview view of the molecule
"""
if not which_import("nglview", return_bool=True):
raise ModuleNotFoundError(
f"Python module nglwview not found. Solve by installing it: `conda install -c conda-forge nglview`"
) # pragma: no cover
import nglview as nv # type: ignore
if ngl_kwargs is None:
ngl_kwargs = {}
structure = nv.TextStructure(self.to_string("nglview-sdf"), ext="sdf")
widget = nv.NGLWidget(structure, **ngl_kwargs)
return widget
warnings.warn('custom_array is deprecated. Use scalar_field instead', DeprecationWarning)
scalar_field = custom_array
if custom_3darray is not None:
warnings.warn('custom_3darray is deprecated. Use vector_field instead', DeprecationWarning)
vector_field = custom_3darray
# Always visualize the parent basis
parent_basis = self.get_parent_basis()
if select_atoms is None:
select_atoms = np.array(len(parent_basis)*[True])
else:
select_atoms = np.array(select_atoms)
if scalar_field is not None:
scalar_field = scalar_field[select_atoms]
struct = nglview.TextStructure(self._ngl_write_structure(parent_basis.get_chemical_symbols()[select_atoms],
self.positions[select_atoms], self.cell, scalar_field=scalar_field))
view = nglview.NGLWidget(struct)
if spacefill:
if color_scheme is None and scalar_field is not None:
color_scheme = 'occupancy'
elif color_scheme is None:
color_scheme = 'element'
#view.add_spacefill(radius_type='vdw', color_scheme=color_scheme, radius=particle_size)
for elem, num in set(list(zip(parent_basis.get_chemical_symbols(), parent_basis.get_atomic_numbers()))):
view.add_spacefill(selection='#'+elem, radius_type='vdw', color_scheme='element', radius=particle_size*(0.2+0.1*np.sqrt(num)))
# view.add_spacefill(radius=1.0)
view.remove_ball_and_stick()
else:
view.add_ball_and_stick()
if show_cell:
if parent_basis.cell is not None:
view.add_unitcell()
if vector_color is None and vector_field is not None:
link_ax2wdg_kwargs: dictionary of named arguments, optional
named arguments for the function :any:`_link_ax_w_pos_2_nglwidget`, which is the one that internally
provides the interactivity. Non-expert users can safely ignore this option.
Returns
--------
iwd : :obj:`nglview.NGLWidget`
"""
# Create ngl_viewer widget
if widget is None:
iwd = _nglview.show_mdtraj(geom)
else:
iwd = widget
if clear_lines == True:
[ax.lines.pop() for ii in range(len(ax.lines))]
# Plot the path on top of it
if plot_path:
ax.plot(positions[:,0], positions[:,1], '-g', lw=3)
# Link the axes widget with the ngl widget
ax_wdg = _link_ax_w_pos_2_nglwidget(ax,
positions,
iwd,
**link_ax2wdg_kwargs
)
# somehow returning the ax_wdg messes the displaying of both widgets
def visualize_sample(sample, geom,
ax,
plot_path=False,
clear_lines=True,
widget=None,
**link_ax2wdg_kwargs
):
r"""
TODO
"""
# Create ngl_viewer widget
if widget is None:
iwd = _nglview.show_mdtraj(geom)
else:
iwd = widget
if clear_lines == True:
[ax.lines.pop() for ii in range(len(ax.lines))]
# Plot the path on top of it
if plot_path:
ax.plot(sample[:,0], sample[:,1], '-g', lw=3)
# Link the axes widget with the ngl widget
_link_ax_w_pos_2_nglwidget(ax,
sample,
iwd,
**link_ax2wdg_kwargs
)
return iwd
ngl_wdg : an already instantiated widget to add the geom, default is None
n_small : if the geometry has less than n_small residues, force a "ball and stick" represenation
:return: :nglview.widget object
"""
if isinstance(geom, str):
geom = _md.load(geom)
if ngl_wdg is None:
if geom is None:
ngl_wdg = _nglview.NGLWidget()
else:
ngl_wdg = _nglview.show_mdtraj(geom)
else:
ngl_wdg.add_trajectory(geom)
# Let' some customization take place
## Do we need a ball+stick representation?
if geom is not None:
if geom.top.n_residues < n_small:
for ic in range(len(ngl_wdg._ngl_component_ids)):
# TODO FIND OUT WHY THIS FAILS FOR THE LAST REPRESENTATION
#print("removing reps for component",ic)
ngl_wdg.remove_cartoon(component=ic)
ngl_wdg.clear_representations(component=ic)
ngl_wdg.add_ball_and_stick(component=ic)
return ngl_wdg
def view_structure(self, snapshot=-1, spacefill=True, show_cell=True):
"""
Args:
snapshot (int): Snapshot of the trajectory one wants
spacefill (bool):
show_cell (bool):
Returns:
view: nglview IPython widget
"""
import nglview
atoms = self.get_structure(snapshot)
picture = nglview.show_ase(atoms)
if spacefill:
picture.add_spacefill(radius_type="vdw", scale=0.5)
picture.remove_ball_and_stick()
else:
picture.add_ball_and_stick()
if show_cell:
if atoms.cell is not None:
picture.add_unitcell()
return picture
def view_structure(self, snapshot=-1, spacefill=True, show_cell=True):
"""
Args:
snapshot (int): Snapshot of the trajectory one wants
spacefill (bool):
show_cell (bool):
Returns:
view: nglview IPython widget
"""
import nglview
atoms = self.get_structure(snapshot)
picture = nglview.show_ase(atoms)
if spacefill:
picture.add_spacefill(radius_type='vdw', scale=0.5)
picture.remove_ball_and_stick()
else:
picture.add_ball_and_stick()
if show_cell:
if atoms.cell is not None:
picture.add_unitcell()
return picture