def _create_view(self, system=None, view=None, gui=True): """Helper function to create the NGLview object. Parameters ---------- system : Sire.System.System A Sire molecular system. view : int The index of an existing view. gui : bool Whether to display the gui. """ if system is None and view is None: raise ValueError("Both 'system' and 'view' cannot be 'None'.") elif system is not None and view is not None: raise ValueError("One of 'system' or 'view' must be 'None'.") # Make sure gui flag is valid. if gui not in [True, False]: gui = True # Default to the most recent view. if view is None: index = self._num_views else: index = view # Create the file name. filename = "%s/view_%04d.pdb" % (self._work_dir, index) # Increment the number of views. if view is None: self._num_views += 1 # Create a PDB object and write to file. if system is not None: try: pdb = _SireIO.PDB2(system) pdb.writeToFile(filename) except Exception as e: msg = "Failed to write system to 'PDB' format." if _isVerbose(): print(msg) raise IOError(e) from None else: raise IOError(msg) from None # Import NGLView when it is used for the first time. import nglview as _nglview # Create the NGLview object. view = _nglview.show_file(filename) # Return the view and display it. return view.display(gui=gui)
def view_presets_multiple(struct, traj): #print(f'Image for {concentration} and state {state_name} ({iterable}), iso {iso}.') if os.path.exists(struct): view = nglview.show_file(struct, default=False) else: print(f'Structure file not found: {struct}') view.add_component(traj) #Set color schemes colors = { 'normal': 'whitesmoke', 'helix5': 'royalblue', 'helix10': 'mediumspringgreen', 'density': 'plum', 'activeSite': 'darkorange' } #Set residues ranges normal = ['1-101', '109-139', '148-223', '226-266', '288-317'] activeSite = ['103-107', '223-226'] muts = ['140', '285', '278'] #Representations for res in normal: view.add_cartoon(res, color=colors['normal'], opacity=1) for res in activeSite: view.add_cartoon(res, color=colors['activeSite']) view.add_cartoon('139-148', color=colors['helix5']) view.add_cartoon('266-288', color=colors['helix10']) view.add_licorice('224') #, color=colors['activeSite']) view.add_licorice('105') #, color=colors['activeSite']) view.add_ball_and_stick('MeO') #, color=colors['activeSite']) for res in muts: view.add_licorice(res) #, color=colors['density']) view.center() view.stage.set_parameters( **{ "clipNear": 0, "clipFar": 100, "clipDist": 10, "fogNear": 20, "fogFar": 100, "backgroundColor": "white", }) return view
def view_presets_density(self, struct, dens, iso): view = nglview.show_file(struct, default=False) view.add_component(dens) #Set color schemes colors = { 'normal': 'whitesmoke', 'helix5': 'royalblue', 'helix10': 'mediumspringgreen', 'density': 'plum', 'activeSite': 'darkorange' } #Set residues ranges normal = ['1-101', '109-139', '148-223', '226-266', '288-317'] activeSite = ['103-107', '223-226'] #Representations for res in normal: view.add_cartoon(res, color=colors['normal'], opacity=0.3) for res in activeSite: view.add_cartoon(res, color=colors['activeSite']) view.add_cartoon('139-148', color=colors['helix5']) view.add_cartoon('266-288', color=colors['helix10']) view.add_licorice('224', color=colors['activeSite']) view.add_licorice('105', color=colors['activeSite']) ##surface density view.clear_representations(component=1) view.add_surface(component=1, color=colors['density'], isolevelType='level', isolevel=iso) view.center() view.stage.set_parameters( **{ "clipNear": 0, "clipFar": 100, "clipDist": 10, "fogNear": 20, "fogFar": 100, "backgroundColor": "white", }) return view
def __init__(self, filename, atom_index=39): self.atom_index = atom_index self.view = nv.show_file(filename, default=False) self.u = mda.Universe(filename) self.cutoff = widgets.FloatText(value=0, description='Cutoff (nm):') self._n = widgets.Label(value='0') self._atom = widgets.Label(value='atoms within cutoff') self.natom_label = widgets.HBox(children=[self._n, self._atom]) self.cutoff.observe(self.update, names='value') self.hbox = widgets.HBox(children=[self.cutoff, self.natom_label]) self.widget = widgets.VBox( children=[self.cutoff, self.natom_label, self.view]) self.update()
def _show_structure(pdb_path): """ Show the ligand-bound structure that belongs to the dynophore. Could be the starting frame of the MD simulation. Parameters ---------- pdb_path : str or pathlib.Path Path to PDB file (structure/topology) Returns ------- nglview.widget.NGLWidget Visualization with the NGL Viewer. """ view = nv.show_file(str(pdb_path), ext="pdb") return view
def show_file(fp, **kwargs): """ Return a structure view. Parameters ---------- fp : filename or list of filenames kwargs : dict Molecular representation of selections, e.g. protein='cartoon' Returns ------- View object """ view = nglview.show_file(fp) setup_view(view, **kwargs) return view
def viewer(self, base_name='superposed', stride=1): import nglview c = input('Value of parameter: ') it = input('Value of iterable: ') base_name = f'{self.results}/{base_name}' print(f'{base_name}_{c}-it{it}-s{stride}.xtc') view = nglview.show_file(f'{base_name}_{c}-it{it}-s{stride}.pdb') view.add_component(f'{base_name}_{c}-it{it}-s{stride}-Molar.dx') view.add_component(f'{base_name}_{c}-it{it}-s{stride}.xtc') view.clear_representations() view.add_representation('cartoon') view.add_representation('licorice', selection='not hydrogen') return view
def protein(input_type, input_value, output_image_filename=None): """ Visualizing protein data. Parameters ---------- input_type : str Either "pdb_code" or a file extension e.g. "pdb". input_value: str or pathlib.Path Either the PDB code of the protein or a local filepath. output_image_filename : str Optional; default: None. Filename to save a static image of the protein. Returns ------- nglview.widget.NGLWidget Interactive NGL viewer visualizing a given protein and (if available) its co-crystallized ligand. """ if input_type == "pdb_code": viewer = nv.show_pdbid(input_value, height="600px") else: with open(input_value) as f: viewer = nv.show_file(f, ext=input_type, height="600px", default_representation=False) viewer.add_representation("cartoon", selection="protein") viewer.add_representation(repr_type="ball+stick", selection="hetero and not water") viewer.center("protein") if output_image_filename is not None: viewer.render_image(trim=True, factor=2) viewer._display_image() viewer.download_image(output_image_filename) return viewer
def test_show_file(): view = nv.show_file(nv.datafiles.PDB)
def visualize(self, show_pocket_centroid=True, show_anchor_residues=True): """ Visualize the pocket (subpockets, regions, and anchor residues). Parameters ---------- show_pocket_centroid : bool Show the pocket centroid as sphere (default) or not. show_anchor_residues : bool Show the anchor residues as spheres (default) or not. Returns ------- nglview.widget.NGLWidget Pocket visualization. """ filepath = str(self._filepath) # Load structure from file in nglview # TODO in the future: show_file > show_text? view = nglview.show_file(filepath) view._remote_call("setSize", target="Widget", args=["1000px", "600px"]) view.clear() # Get file format (this is important to know how nglview will index residues) file_format = filepath.split(".")[-1] # Get residue ID > nglview index mapping residue_id2ix = self._map_residue_id2ix(file_format) # Show regions scheme_regions_list = [] for index, region in self.regions.iterrows(): color = region["region.color"] residue_id = region["residue.id"] residue_ngl_ix = residue_id2ix.loc[residue_id] scheme_regions_list.append([color, residue_ngl_ix]) scheme_regions = nglview.color._ColorScheme(scheme_regions_list, label="scheme_regions") view.add_representation("cartoon", selection="protein", color=scheme_regions) # Show pocket centroids if show_pocket_centroid: view.shape.add_sphere(list(self.centroid), [0, 0, 1], 2, "centroid") # Show subpockets for index, subpocket in self.subpockets.iterrows(): center = list(subpocket["subpocket.center"]) name = subpocket["subpocket.name"] color_rgb = colors.to_rgb(subpocket["subpocket.color"]) view.shape.add_sphere(center, color_rgb, 2, name) # Show anchor points if show_anchor_residues: for index, anchor_residue in self.anchor_residues.iterrows(): center = list(anchor_residue["anchor_residue.center"]) color_rgb = colors.to_rgb(anchor_residue["subpocket.color"]) view.shape.add_sphere(center, color_rgb, 0.5) # Show return view