def test_write_html(mock_unset): traj0 = pt.datafiles.load_trpcage() traj1 = pt.datafiles.load_tz2() view = nv.NGLWidget() view.add_trajectory(traj0) view.add_trajectory(traj1) view fp = StringIO() nv.write_html(fp, [view], frame_range=(0, 3)) mock_unset.assert_called_with() assert len(view._ngl_coordinate_resource[0]) == 3 assert len(view._ngl_coordinate_resource[1]) == 3
def test_handling_n_components_changed(): view = nv.NGLWidget() n_traj = nv.PyTrajTrajectory(pt.load(nv.datafiles.PDB)) view.add_trajectory(n_traj) # fake updating n_components and _repr_dict from front-end view._ngl_repr_dict = REPR_DICT view.n_components = 1 view.player.widget_repr = view.player._make_widget_repr() view.remove_component(n_traj.id) # fake updating n_components from front-end view._ngl_repr_dict = {'c0': {}} view.n_components = 0
def __init__( self, configure_view=True, configuration_tabs=["Selection", "Appearance", "Cell", "Download"], default_camera="orthographic", **kwargs, ): # Defining viewer box. # Nglviwer self._viewer = nglview.NGLWidget() self._viewer.camera = default_camera self._viewer.observe(self._on_atom_click, names="picked") self._viewer.stage.set_parameters(mouse_preset="pymol") view_box = ipw.VBox([self._viewer]) configuration_tabs_map = { "Selection": self._selection_tab(), "Appearance": self._appearance_tab(), "Cell": self._cell_tab(), "Download": self._download_tab(), } if configure_view is not True: warnings.warn( "`configure_view` is deprecated, please use `configuration_tabs` instead.", DeprecationWarning, ) if not configure_view: configuration_tabs.clear() # Constructing configuration box if len(configuration_tabs) != 0: configuration_box = ipw.Tab( layout=ipw.Layout(flex="1 1 auto", width="auto")) configuration_box.children = [ configuration_tabs_map[tab_title] for tab_title in configuration_tabs ] for i, title in enumerate(configuration_tabs): configuration_box.set_title(i, title) children = [ipw.HBox([view_box, configuration_box])] view_box.layout = {"width": "60%"} else: children = [view_box] if "children" in kwargs: children += kwargs.pop("children") super().__init__(children, **kwargs)
def test_loaded_attribute(): traj = pt.datafiles.load_tz2() structure = nv.FileStructure(nv.datafiles.PDB) # False, empty constructor view = nv.NGLWidget() view.loaded = False view.add_structure(structure) view.add_trajectory(traj) view # False, constructor with a single Structure view = nv.NGLWidget(structure) view.loaded = False view.add_trajectory(traj) view # True view = nv.NGLWidget() view.loaded = True view.add_structure(structure) view.add_trajectory(traj) view # False then True, empty constructor view = nv.NGLWidget() view.loaded = False view.add_structure(structure) view.loaded = True view.add_trajectory(traj) view # False then True, constructor with a Trajectory view = nv.NGLWidget(nv.PyTrajTrajectory(traj)) view.loaded = False view.add_structure(structure) view.loaded = True view.add_trajectory(traj) view
def view(self, indices='all'): """3D spatial view of alpha-spheres and points An NGLview view is returned with alpha-spheres (gray color) and points (red color). Parameters ---------- indices : numpy.ndarray, list or tuple (dtype:ints) List, tuple or numpy.ndarray with the alpha-sphere indices defining the subset. Returns ------- view : nglview View object of NGLview. Examples -------- >>> import openpocket as opoc >>> points = ([[-1., 2., 0.], >>> [ 0., 2., 1.], >>> [ 1., -2., 1.], >>> [ 0., 1., 1.], >>> [ 0., 0., 0.], >>> [-1., -1., 0.]]) >>> aspheres = opoc.alpha_spheres.AlphaSpheresSet(points) >>> view = aspheres.view([1,3]) >>> view """ import nglview as nv view = nv.NGLWidget() point_indices = [] if indices == 'all': indices = range(self.n_alpha_spheres) point_indices = range(self.n_points) else: point_indices = self.get_points_of_alpha_spheres(indices) for index in point_indices: atom_coordinates = self.points[index, :] view.shape.add_sphere(list(atom_coordinates), [0.8, 0.0, 0.0], 0.2) for index in indices: sphere_coordinates = self.centers[index, :] sphere_radius = self.radii[index] view.shape.add_sphere(list(sphere_coordinates), [0.8, 0.8, 0.8], sphere_radius) return view
def get_nglview(pharmacophore, receptor=True, ligand=True, arrow_norm=2.0, arrow_radius=0.2): view_with_ligand = False view_with_receptor = False tmp_view = nglview.NGLWidget() arrow_norm = np.sqrt(arrow_norm) if pharmacophore.with_receptor and receptor: view_with_receptor = True tmp_receptor_file = tempfile.NamedTemporaryFile(mode='w+', delete=False, suffix='.pdb') tmp_receptor_file.write(pharmacophore.receptor) tmp_receptor_file.close() rec = tmp_view.add_component(tmp_receptor_file.name) rec.add_line('protein') if pharmacophore.with_ligand and ligand: view_with_ligand = True tmp_ligand_file = tempfile.NamedTemporaryFile(mode='w+', delete=False, suffix='.mol2') tmp_ligand_file.write(pharmacophore.ligand) tmp_ligand_file.close() tmp_view.add_component(tmp_ligand_file.name) for point in pharmacophore.points: color = color_code[point.name] tmp_sphere = tmp_view.shape.add_sphere(point.position.tolist(), color, point.radius, point.name) if point.svector is not None: source_array = point.position end_array = (point.position + arrow_norm * point.svector) tmp_view.shape.add_arrow(source_array.tolist(), end_array.tolist(), color, arrow_radius) if view_with_receptor: tmp_receptor_file.close() os.unlink(tmp_receptor_file.name) if view_with_ligand: tmp_ligand_file.close() os.remove(tmp_ligand_file.name) return tmp_view
def show(self, palette: str = 'openpharmacophore') -> nv.NGLWidget: """ Show the pharmacophore model together with the molecular system from with it was extracted. Parameters ---------- palette : str, dict Color palette name or dictionary. (Default='openpharmacophore') Returns ------- nglview.NGLWidget An nglview.NGLWidget is returned with the 'view' of the pharmacophoric model and the molecular system used to elucidate it. """ view = nv.NGLWidget() if self.molecular_system is not None: view.add_component(self.molecular_system) if self.ligand: view.representations = [ { "type": "cartoon", "params": { "sele": "protein", "color": "residueindex" } }, ] view.add_component(self.ligand) else: view.representations = [ { "type": "cartoon", "params": { "sele": "protein", "color": "residueindex" } }, { "type": "ball+stick", "params": { "sele": "( not polymer or hetero ) and not ( water or ion )" # Show ligand } } ] self.add_to_NGLView(view, palette=palette) return view
def __init__(self): self.viewer = nglview.NGLWidget() self.viewer._remote_call("setSize", target="Widget", args=["1000px", "600px"]) self.pockets_residue_ngl_ixs = {} self.structure_names = [] self._residue_ids_to_ngl_ixs = {} self._component_counter = 0 self._components_structures = {} self._components_pocket_center = {} self._components_subpockets = {} self._components_anchor_residues = {}
def test_add_new_shape(): view = nv.NGLWidget() sphere = ('sphere', [0, 0, 9], [1, 0, 0], 1.5) arrow = ('arrow', [1, 2, 7], [30, 3, 3], [1, 0, 1], 1.0) c0 = view._add_shape([sphere, arrow], name='my_shape') # Shape c1 = view.shape.add_arrow([1, 2, 7], [30, 3, 3], [1, 0, 1], 1.0) assert len(view._ngl_component_ids) == 2 view.remove_component(c0) assert len(view._ngl_component_ids) == 1 view.remove_component(c1) assert len(view._ngl_component_ids) == 0
def __init__(self, structure, *args, **kwargs): self._viewer = nglview.NGLWidget() self._viewer.camera = "orthographic" self._viewer.stage.set_parameters(mouse_preset="pymol") ipw.link((self, "background"), (self._viewer, "background")) self.structure = structure super().__init__( children=[ self._viewer, ], *args, **kwargs, )
def test_queuing_messages(): view = nv.NGLWidget() view.add_component(nv.datafiles.PDB) view.download_image() view assert [f._method_name for f in view._ngl_displayed_callbacks_before_loaded] == \ ['setUnSyncCamera', 'setSelector', 'setUnSyncFrame', 'setDelay', 'loadFile', '_downloadImage'] assert [f._method_name for f in view._ngl_displayed_callbacks_after_loaded] == \ ['loadFile'] # display 2nd time view.sync_view() assert [f._method_name for f in view._ngl_displayed_callbacks_after_loaded] == \ ['loadFile']
def test_queuing_messages(): view = nv.NGLWidget() view.add_component(nv.datafiles.PDB) view.download_image() view assert [f._method_name for f in view._ngl_displayed_callbacks_before_loaded] == \ [ 'loadFile', '_downloadImage'] assert [f['methodName'] for f in view._ngl_msg_archive] == \ ['loadFile'] # display 2nd time view assert [f['methodName'] for f in view._ngl_msg_archive] == \ ['loadFile']
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
def __init__(self, configure_view=True, **kwargs): # Defining viewer box. # 1. Nglviwer self._viewer = nglview.NGLWidget() self._viewer.camera = 'orthographic' self._viewer.observe(self._on_atom_click, names='picked') self._viewer.stage.set_parameters(mouse_preset='pymol') # 2. Camera type. camera_type = ipw.ToggleButtons(options={ 'Orthographic': 'orthographic', 'Perspective': 'perspective' }, description='Camera type:', value='orthographic', layout={"align_self": "flex-end"}, style={'button_width': '115.5px'}, orientation='vertical') def change_camera(change): self._viewer.camera = change['new'] camera_type.observe(change_camera, names="value") view_box = ipw.VBox([self._viewer, camera_type]) # Constructing configuration box if configure_view: configuration_box = ipw.Tab( layout=ipw.Layout(flex='1 1 auto', width='auto')) configuration_box.children = [ self._selection_tab(), self._appearance_tab(), self._download_tab() ] for i, title in enumerate(["Selection", "Appearance", "Download"]): configuration_box.set_title(i, title) children = [ipw.HBox([view_box, configuration_box])] view_box.layout = {'width': "60%"} else: children = [view_box] if 'children' in kwargs: children += kwargs.pop('children') super().__init__(children, **kwargs)
def show_(*args, **kwargs): print(f'Executing {func.__name__} \n', end='\r') widget = nglview.NGLWidget() out = func(*args, **kwargs) ref = md.load_pdb(out) widget.add_trajectory(ref, default=True) widget.camera = 'perspective' widget.stage.set_parameters( **{ "clipNear": 0, "clipFar": 100, "clipDist": 1, "backgroundColor": "white", }) return widget
def show(self, palette: str = 'openpharmacophore'): """ Show the pharmacophore model. Parameters ---------- palette : str or dict. Color palette name or dictionary. (Default: 'openpharmacophore') Returns ------- nglview.NGLWidget A nglview.NGLWidget with the 'view' of the pharmacophoric model. """ view = nv.NGLWidget() self.add_to_NGLView(view, palette=palette) return view
def __init__(self, text="Upload Structure", node_class=None, **kwargs): """ Upload a structure and store it in AiiDA database. :param text: Text to display before upload button :type text: str :param node_class: AiiDA node class for storing the structure. Possible values: 'StructureData', 'CifData' or None (let the user decide). Note: If your workflows require a specific node class, better fix it here. """ self.file_upload = FileUploadWidget(text) self.viewer = nglview.NGLWidget() self.btn_store = ipw.Button(description='Store in AiiDA', disabled=True) self.structure_description = ipw.Text( placeholder="Description (optional)") self.structure_ase = None self.structure_node = None self.data_format = ipw.RadioButtons( options=['StructureData', 'CifData'], description='Data type:') if node_class is None: store = ipw.HBox( [self.btn_store, self.data_format, self.structure_description]) else: self.data_format.value = node_class store = ipw.HBox([self.btn_store, self.structure_description]) children = [self.file_upload, self.viewer, store] super(StructureUploadWidget, self).__init__(children=children, **kwargs) self.file_upload.observe(self._on_file_upload, names='data') self.btn_store.on_click(self._on_click_store) from aiida import load_dbenv, is_dbenv_loaded from aiida.backends import settings if not is_dbenv_loaded(): load_dbenv(profile=settings.AIIDADB_PROFILE)
def view_conformers(molecule: Chem.Mol) -> nv.NGLWidget: """ Generate a view of the conformers of a molecule. Parameters ----------- molecule : rdkit.Chem.Mol The molecule which conformers will be visualized. Returns ---------- view : nglview.widget.NGLWidget """ view = nv.NGLWidget() for conformer in range(molecule.GetNumConformers()): mol_string = Chem.MolToMolBlock(molecule, confId=conformer) temp_mol = Chem.MolFromMolBlock(mol_string, removeHs=False) component = view.add_component(temp_mol) component.clear() component.add_ball_and_stick(multipleBond=True) return view
def _nglwidget_wrapper(geom, ngl_wdg=None, n_small=10): r""" Wrapper to nlgivew.show_geom's method that allows for some other automatic choice of representation Parameters ---------- 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) return ngl_wdg
def view_ligands(molecules: Molecule) -> nv.NGLWidget: """ Generate a view of a set of ligands Parameters ----------- molecules : rdkit.Chem.Mol or list of rdkit.Chem.rdchem.Mol The molecules that will be visualized. Returns ---------- view: nglview.widget.NGLWidget """ if not isinstance(molecules, list): molecules = [molecules] view = nv.NGLWidget() for molecule in molecules: component = view.add_component(molecule) component.clear() component.add_ball_and_stick(multipleBond=True) return view
def __init__(self, **kwargs): self._current_view = None self.viewer = nglview.NGLWidget() self.viewer.camera = "orthographic" self.viewer.stage.set_parameters(mouse_preset="pymol") self.viewer_box = ipw.Box( children=(self.viewer, ), layout={ "width": "auto", "height": "auto", "border": "solid 0.5px darkgrey", "margin": "0px", "padding": "0.5px", }, ) button_style = kwargs.pop("button_style", None) self.download = DownloadChooser(button_style=button_style, **kwargs) layout = kwargs.pop( "layout", { "width": "auto", "height": "auto", "margin": "0px 0px 0px 0px", "padding": "0px 0px 10px 0px", }, ) super().__init__( children=(self.viewer_box, self.download), layout=layout, **kwargs, ) self.observe(self._on_change_structure, names="structure") traitlets.dlink((self, "structure"), (self.download, "structure"))
def view_with_nglview(parsed_file, **kwargs): """Render ESIgenReport with nglview (for Jupyter Notebooks)""" import nglview as nv structure = nv.TextStructure(parsed_file.data.pdb_block, ext='pdb') parameters = { "clipNear": 0, "clipFar": 100, "clipDist": 0, "fogNear": 1000, "fogFar": 100 } representations = [{ 'type': 'ball+stick', 'params': { 'sele': 'not #H', 'radius': 0.2, 'nearClip': False } }, { 'type': 'ball+stick', 'params': { 'sele': 'not #C and not #H and not #O and not #N and not #P and not #S', 'aspectRatio': 5, 'nearClip': False } }, { 'type': 'ball+stick', 'params': { 'sele': '#H or #C or #N or #O or #P or #S', 'radius': 0.1, 'aspectRatio': 1.5, 'nearClip': False } }] return nv.NGLWidget(structure, parameters=parameters, representations=representations, **kwargs)
def chimera_view(*molecules): """ Depicts the requested molecules with NGLViewer in a Python notebook. This method does not require a headless Chimera build, however. Parameters ---------- molecules : tuple of chimera.Molecule Molecules to display. If none is given, all present molecules in Chimera canvas will be displayed. """ try: import nglview as nv except ImportError: raise ImportError('You must install nglview!') import chimera class _ChimeraStructure(nv.Structure): def __init__(self, *molecules): if not molecules: raise ValueError('Please supply at least one chimera.Molecule.') self.ext = "pdb" self.params = {} self.id = str(id(molecules[0])) self.molecules = molecules def get_structure_string(self): s = StringIO() chimera.pdbWrite(self.molecules, self.molecules[0].openState.xform, s) return s.getvalue() if not molecules: molecules = chimera.openModels.list(modelTypes=[chimera.Molecule]) structure = _ChimeraStructure(*molecules) return nv.NGLWidget(structure)
# loop through all atoms in given resid and give same tempfactor according to prediction temp_factors = [] for index,res in enumerate(u.atoms.residues): resid = res.resid pred = correct_pos[resid] for atom in u.atoms.residues[index].atoms: temp_factors.append(pred) # add b-factors u.atoms.tempfactors = temp_factors protein = u.select_atoms("segid A") # only have chain A # load universe object in nglview t = nv.MDAnalysisTrajectory(protein) w = nv.NGLWidget(t) # define represention w.representations = [ {"type": "cartoon", "params": { "sele": "protein", "color": "bfactor" }}, {"type": "ball+stick", "params": { "sele": "hetero" }} ] # w.download_image(filename='str2_ks5.png', factor=4, antialias=True, trim=False, transparent=True) if cam_orient != None: try: w._set_camera_orientation(cam_orient) except:
def test_camelize_parameters(): view = nv.NGLWidget() view.parameters = dict(background_color='black') nt.assert_true('backgroundColor' in view._parameters)
def test_add_structure(): view = nv.NGLWidget() with pytest.raises(ValueError): # raise if not is instance of nv.Structure view.add_structure(nv.datafiles.PDB)
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)
def setup(self, file_path, atoms, mode, details=None): a, freq, vibr_displacements = read_molden(file_path) trajectory_mol = get_trajectory(mode, atoms, freq, vibr_displacements) trajectory_slab = get_trajectory(mode, atoms, freq, vibr_displacements) if details is None: mol_inds = list(np.arange(0, len(atoms))) rest_inds = [] else: mol_inds = [ item for sublist in details['all_molecules'] for item in sublist ] rest_inds = details['slabatoms'] + details['bottom_H'] + details[ 'adatoms'] + details['unclassified'] #trajectory_mol = trajectory for i in range(0, len(trajectory_mol)): del trajectory_mol[i][rest_inds] #trajectory_slab = trajectory for i in range(0, len(trajectory_slab)): del trajectory_slab[i][mol_inds] ase_traj_mol = nglview.ASETrajectory(trajectory_mol) ase_traj_slab = nglview.ASETrajectory(trajectory_slab) #viewer = nglview.show_asetraj(trajectory, gui=True) #viewer[0].add_representation('ball_and_stick',selection=list(np.arange(0, 46))) #viewer.add_component(nglview.ASEStructure(atoms), default_representation=False) #viewer.add_ball_and_stick(aspectRatio=MOL_ASPECT, opacity=1.0,component=1) viewer = nglview.NGLWidget(gui=True) viewer.add_trajectory(ase_traj_slab, default_representation=False) viewer.add_trajectory(ase_traj_mol, default_representation=False) viewer.add_representation('ball+stick', aspectRatio=REST_ASPECT, opacity=1.0, component=0) viewer.add_representation('ball+stick', aspectRatio=MOL_ASPECT, opacity=1.0, component=1) com = atoms.get_center_of_mass() cell_z = atoms.cell[2, 2] #top_z_orientation = [1.0, 0.0, 0.0, 0, # 0.0, 1.0, 0.0, 0, # 0.0, 0.0, np.max([cell_z, 30.0]) , 0, # -com[0], -com[1], -com[2], 1] cell_x = atoms.cell[1, 1] top_z_orientation = [ 0.0, np.max([cell_x, 40]) * np.sin(np.pi * 1 / 25), np.max([cell_x, 40]) * np.cos(np.pi * 1 / 25), 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, np.max([cell_x, 40]) * np.cos(np.pi * 1 / 25), -np.max([cell_x, 40]) * np.sin(np.pi * 1 / 25), 0.0, -com[0], -com[1], -com[2], 1.0 ] viewer._set_camera_orientation(top_z_orientation) with self.vib_viewer: clear_output() display(viewer) def f(): plt.figure(figsize=(10, 5)) plt.vlines(freq, np.zeros(len(freq)), np.ones(len(freq))) #for i, f in enumerate(freq): # print(i,f) plt.hlines(0, *plt.xlim()) plt.xlabel('Energy [cm$^{-1}$]', fontsize=12) interactive_plot = ipw.interactive(f) with self.spec_viewer: clear_output() display(interactive_plot) def f(): plt.figure(figsize=(10, 5)) plt.vlines(freq, np.zeros(len(freq)), np.ones(len(freq))) #for i, f in enumerate(freq): # print(i,f) plt.hlines(0, *plt.xlim()) plt.xlabel('Energy [cm$^{-1}$]', fontsize=12)
def _plot3d(self, show_cell=True, show_axes=True, camera="orthographic", spacefill=True, particle_size=1.0, select_atoms=None, background="white", color_scheme=None, colors=None, scalar_field=None, scalar_start=None, scalar_end=None, scalar_cmap=None, vector_field=None, vector_color=None, magnetic_moments=False, view_plane=np.array([0, 0, 1]), distance_from_camera=1.0): """ Plot3d relies on NGLView to visualize atomic structures. Here, we construct a string in the "protein database" ("pdb") format, then turn it into an NGLView "structure". PDB is a white-space sensitive format, so the string snippets are carefully formatted. The final widget is returned. If it is assigned to a variable, the visualization is suppressed until that variable is evaluated, and in the meantime more NGL operations can be applied to it to modify the visualization. Args: show_cell (bool): Whether or not to show the frame. (Default is True.) show_axes (bool): Whether or not to show xyz axes. (Default is True.) camera (str): 'perspective' or 'orthographic'. (Default is 'perspective'.) spacefill (bool): Whether to use a space-filling or ball-and-stick representation. (Default is True, use space-filling atoms.) particle_size (float): Size of the particles. (Default is 1.) select_atoms (numpy.ndarray): Indices of atoms to show, either as integers or a boolean array mask. (Default is None, show all atoms.) background (str): Background color. (Default is 'white'.) color_scheme (str): NGLView color scheme to use. (Default is None, color by element.) colors (numpy.ndarray): A per-atom array of HTML color names or hex color codes to use for atomic colors. (Default is None, use coloring scheme.) scalar_field (numpy.ndarray): Color each atom according to the array value (Default is None, use coloring scheme.) scalar_start (float): The scalar value to be mapped onto the low end of the color map (lower values are clipped). (Default is None, use the minimum value in `scalar_field`.) scalar_end (float): The scalar value to be mapped onto the high end of the color map (higher values are clipped). (Default is None, use the maximum value in `scalar_field`.) scalar_cmap (matplotlib.cm): The colormap to use. (Default is None, giving a blue-red divergent map.) vector_field (numpy.ndarray): Add vectors (3 values) originating at each atom. (Default is None, no vectors.) vector_color (numpy.ndarray): Colors for the vectors (only available with vector_field). (Default is None, vectors are colored by their direction.) magnetic_moments (bool): Plot magnetic moments as 'scalar_field' or 'vector_field'. view_plane (numpy.ndarray): A Nx3-array (N = 1,2,3); the first 3d-component of the array specifies which plane of the system to view (for example, [1, 0, 0], [1, 1, 0] or the [1, 1, 1] planes), the second 3d-component (if specified, otherwise [1, 0, 0]) gives the horizontal direction, and the third component (if specified) is the vertical component, which is ignored and calculated internally. The orthonormality of the orientation is internally ensured, and therefore is not required in the function call. (Default is np.array([0, 0, 1]), which is view normal to the x-y plane.) distance_from_camera (float): Distance of the camera from the structure. Higher = farther away. (Default is 14, which also seems to be the NGLView default value.) Possible NGLView color schemes: " ", "picking", "random", "uniform", "atomindex", "residueindex", "chainindex", "modelindex", "sstruc", "element", "resname", "bfactor", "hydrophobicity", "value", "volume", "occupancy" Returns: (nglview.NGLWidget): The NGLView widget itself, which can be operated on further or viewed as-is. Warnings: * Many features only work with space-filling atoms (e.g. coloring by a scalar field). * The colour interpretation of some hex codes is weird, e.g. 'green'. """ 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!" ) if magnetic_moments is True and hasattr(self._ref_atoms, 'spin'): if len(self._ref_atoms.get_initial_magnetic_moments().shape) == 1: scalar_field = self._ref_atoms.get_initial_magnetic_moments() else: vector_field = self._ref_atoms.get_initial_magnetic_moments() parent_basis = self._ref_atoms.get_parent_basis() elements = parent_basis.get_chemical_symbols() atomic_numbers = parent_basis.get_atomic_numbers() positions = self._ref_atoms.positions # If `select_atoms` was given, visualize only a subset of the `parent_basis` if select_atoms is not None: select_atoms = np.array(select_atoms, dtype=int) elements = elements[select_atoms] atomic_numbers = atomic_numbers[select_atoms] positions = positions[select_atoms] if colors is not None: colors = np.array(colors) colors = colors[select_atoms] if scalar_field is not None: scalar_field = np.array(scalar_field) scalar_field = scalar_field[select_atoms] if vector_field is not None: vector_field = np.array(vector_field) vector_field = vector_field[select_atoms] if vector_color is not None: vector_color = np.array(vector_color) vector_color = vector_color[select_atoms] # Write the nglview protein-database-formatted string struct = nglview.TextStructure( _ngl_write_structure(elements, positions, self._ref_atoms.cell)) # Parse the string into the displayable widget view = nglview.NGLWidget(struct) if spacefill: # Color by scheme if color_scheme is not None: if colors is not None: warnings.warn("`color_scheme` is overriding `colors`") if scalar_field is not None: warnings.warn( "`color_scheme` is overriding `scalar_field`") view = _add_colorscheme_spacefill(view, elements, atomic_numbers, particle_size, color_scheme) # Color by per-atom colors elif colors is not None: if scalar_field is not None: warnings.warn("`colors` is overriding `scalar_field`") view = _add_custom_color_spacefill(view, atomic_numbers, particle_size, colors) # Color by per-atom scalars elif scalar_field is not None: # Color by per-atom scalars colors = _scalars_to_hex_colors(scalar_field, scalar_start, scalar_end, scalar_cmap) view = _add_custom_color_spacefill(view, atomic_numbers, particle_size, colors) # Color by element else: view = _add_colorscheme_spacefill(view, elements, atomic_numbers, particle_size) view.remove_ball_and_stick() else: view.add_ball_and_stick() if show_cell: if parent_basis.cell is not None: if all(np.max(parent_basis.cell, axis=0) > 1e-2): view.add_unitcell() if vector_color is None and vector_field is not None: vector_color = ( 0.5 * np.array(vector_field) / np.linalg.norm(vector_field, axis=-1)[:, np.newaxis] + 0.5) elif (vector_field is not None and vector_field is not None): # WARNING: There must be a bug here... try: if vector_color.shape != np.ones( (len(self._ref_atoms), 3)).shape: vector_color = np.outer( np.ones(len(self._ref_atoms)), vector_color / np.linalg.norm(vector_color)) except AttributeError: vector_color = np.ones( (len(self._ref_atoms), 3)) * vector_color if vector_field is not None: for arr, pos, col in zip(vector_field, positions, vector_color): view.shape.add_arrow(list(pos), list(pos + arr), list(col), 0.2) if show_axes: # Add axes axes_origin = -np.ones(3) arrow_radius = 0.1 text_size = 1 text_color = [0, 0, 0] arrow_names = ["x", "y", "z"] for n in [0, 1, 2]: start = list(axes_origin) shift = np.zeros(3) shift[n] = 1 end = list(start + shift) color = list(shift) # We cast as list to avoid JSON warnings view.shape.add_arrow(start, end, color, arrow_radius) view.shape.add_text(end, text_color, text_size, arrow_names[n]) if camera != "perspective" and camera != "orthographic": warnings.warn( "Only perspective or orthographic is (likely to be) permitted for camera" ) view.camera = camera view.background = background orientation = _get_flattened_orientation( view_plane=view_plane, distance_from_camera=distance_from_camera * 14) view.control.orient(orientation) return view
def show_ref_frames(bp_frames, view=None, spheres=True, arrows=False, diamonds=False, boxes=True, bp_colors_mask=None): if view is None: view = nv.NGLWidget() dx = 2 dy = 4 dz = 1 if spheres: if bp_colors_mask is None: view.shape.add_buffer('sphere', position=bp_frames[:, 3, :3].flatten().tolist(), color=[1, 1, 0] * bp_frames.shape[0], radius=[3] * bp_frames.shape[0]) else: bp_colors = np.ones((bp_frames.shape[0], 3)) bp_colors[bp_colors_mask, 1] = 0 bp_colors[bp_colors_mask != 1, 2] = 0 view.shape.add_buffer('sphere', position=bp_frames[:, 3, :3].flatten().tolist(), color=bp_colors.flatten().tolist(), radius=[3] * bp_frames.shape[0]) view.shape.add_buffer( 'cylinder', position1=bp_frames[:, 3, :3][:-1].flatten().tolist(), position2=bp_frames[:, 3, :3][1:].flatten().tolist(), color=[1, 1, 0] * (bp_frames.shape[0] - 1), radius=[0.5] * (bp_frames.shape[0] - 1)) if arrows: view.shape.add_buffer( 'arrow', position1=bp_frames[:, 3, :3].flatten().tolist(), position2=(bp_frames[:, 3, :3] + 3 * bp_frames[:, :3, 0]).flatten().tolist(), color=[1, 0, 0] * bp_frames.shape[0], radius=[0.3] * bp_frames.shape[0]) view.shape.add_buffer( 'arrow', position1=bp_frames[:, 3, :3].flatten().tolist(), position2=(bp_frames[:, 3, :3] + 3 * bp_frames[:, :3, 1]).flatten().tolist(), color=[0, 1, 0] * bp_frames.shape[0], radius=[0.3] * bp_frames.shape[0]) view.shape.add_buffer( 'arrow', position1=bp_frames[:, 3, :3].flatten().tolist(), position2=(bp_frames[:, 3, :3] + 3 * bp_frames[:, :3, 2]).flatten().tolist(), color=[0, 0, 1] * bp_frames.shape[0], radius=[0.3] * bp_frames.shape[0]) if diamonds: z0 = bp_frames[:, 3, :3] - dz * bp_frames[:, :3, 2] z1 = bp_frames[:, 3, :3] + dz * bp_frames[:, :3, 2] y0 = bp_frames[:, 3, :3] - dy * bp_frames[:, :3, 1] y1 = bp_frames[:, 3, :3] + dy * bp_frames[:, :3, 1] x0 = bp_frames[:, 3, :3] - dx * bp_frames[:, :3, 0] x1 = bp_frames[:, 3, :3] + dx * bp_frames[:, :3, 0] coords = np.hstack(( x0, y0, z0, x0, y0, z1, x0, y1, z0, x0, y1, z1, x1, y0, z0, x1, y0, z1, x1, y1, z0, x1, y1, z1, )).flatten() color = [1, 1, 0] * (coords.size // 3) view.shape.add_mesh( coords.tolist(), color, ) if boxes: p1 = bp_frames[:, 3, : 3] - dx * bp_frames[:, :3, 0] - dy * bp_frames[:, :3, 1] - dz * bp_frames[:, : 3, 2] p2 = bp_frames[:, 3, : 3] - dx * bp_frames[:, :3, 0] - dy * bp_frames[:, :3, 1] + dz * bp_frames[:, : 3, 2] p3 = bp_frames[:, 3, : 3] - dx * bp_frames[:, :3, 0] + dy * bp_frames[:, :3, 1] - dz * bp_frames[:, : 3, 2] p4 = bp_frames[:, 3, : 3] - dx * bp_frames[:, :3, 0] + dy * bp_frames[:, :3, 1] + dz * bp_frames[:, : 3, 2] p5 = bp_frames[:, 3, : 3] + dx * bp_frames[:, :3, 0] - dy * bp_frames[:, :3, 1] - dz * bp_frames[:, : 3, 2] p6 = bp_frames[:, 3, : 3] + dx * bp_frames[:, :3, 0] - dy * bp_frames[:, :3, 1] + dz * bp_frames[:, : 3, 2] p7 = bp_frames[:, 3, : 3] + dx * bp_frames[:, :3, 0] + dy * bp_frames[:, :3, 1] - dz * bp_frames[:, : 3, 2] p8 = bp_frames[:, 3, : 3] + dx * bp_frames[:, :3, 0] + dy * bp_frames[:, :3, 1] + dz * bp_frames[:, : 3, 2] coords = np.hstack((p1, p2, p3, p2, p3, p4, p5, p6, p7, p6, p7, p8, p1, p2, p5, p2, p5, p6, p3, p4, p7, p4, p7, p8, p1, p3, p5, p3, p5, p7, p2, p4, p6, p4, p6, p8)).flatten() color = [1, 1, 0] * (coords.size // 3) view.shape.add_mesh( coords.tolist(), color, ) view.camera = 'orthographic' view._remote_call('setSize', target='Widget', args=['800px', '600px']) return view