Example #1
0
    def visualize(self, show_ports=False, backend='py3dmol',
            color_scheme={}, show_atomistic=False, scale=1.0): # pragma: no cover
        """
        Visualize the Compound using py3dmol (default) or nglview.
        Allows for visualization of a Compound within a Jupyter Notebook.
        Parameters
        ----------
        show_ports : bool, optional, default=False
            Visualize Ports in addition to Particles
        backend : str, optional, default='py3dmol'
            Specify the backend package to visualize compounds
            Currently supported: py3dmol, nglview
        color_scheme : dict, optional
            Specify coloring for non-elemental particles
            keys are strings of the particle names
            values are strings of the colors
            i.e. {'_CGBEAD': 'blue'}
        NOTE!: Only py3dmol will work with CG_Compounds
        """
        viz_pkg = {'nglview': self._visualize_nglview,
                'py3dmol': self._visualize_py3dmol}
        if run_from_ipython():
            if backend.lower() in viz_pkg:
                return viz_pkg[backend.lower()](show_ports=show_ports,
                        color_scheme=color_scheme, show_atomistic=show_atomistic, scale=scale)
            else:
                raise RuntimeError("Unsupported visualization " +
                        "backend ({}). ".format(backend) +
                        "Currently supported backends include nglview and py3dmol")

        else:
            raise RuntimeError('Visualization is only supported in Jupyter '
                               'Notebooks.')
Example #2
0
 def visualize(self, show_ports=False):
     """Visualize the Compound using nglview. """
     if run_from_ipython():
         structure = self.to_parmed(show_ports)
         return nglview.show_parmed(structure)
     else:
         raise RuntimeError('Visualization is only supported in Jupyter '
                            'Notebooks.')
Example #3
0
 def visualize(self, show_ports=False):
     """Visualize the Compound using nglview. """
     nglview = import_('nglview')
     if run_from_ipython():
         structure = self.to_trajectory(show_ports)
         return nglview.show_mdtraj(structure)
     else:
         raise RuntimeError('Visualization is only supported in Jupyter '
                            'Notebooks.')
Example #4
0
    def visualize(self, show_ports=False):
        """Visualize the Compound using nglview. """
        if run_from_ipython():
            structure = self.to_trajectory(show_ports)
            return nglview.show_mdtraj(structure)
        else:
            try:
                """Visualize the Compound using imolecule. """
                import imolecule
                json_mol = self._to_json(show_ports)
                return imolecule.draw(json_mol, format='json', shader='lambert',
                                      drawing_type='ball and stick', camera_type='perspective',
                                      element_properties=None)

            except ImportError:
                raise RuntimeError('Visualization is only supported in Jupyter '
                                   'Notebooks.')
Example #5
0
    def visualize(self, show_ports=False):
        """Visualize the Compound using nglview. """
        nglview = import_('nglview')
        if run_from_ipython():
            structure = self.to_trajectory(show_ports)
            return nglview.show_mdtraj(structure)
        else:
            try:
                """Visualize the Compound using imolecule. """
                import imolecule
                json_mol = self._to_json(show_ports)
                imolecule.draw(json_mol,
                               format='json',
                               shader='lambert',
                               drawing_type='ball and stick',
                               camera_type='perspective',
                               element_properties=None)

            except ImportError:
                raise RuntimeError(
                    'Visualization is only supported in Jupyter '
                    'Notebooks.')
Example #6
0
 def test_has_ipython(self):
     __IPYTHON__ = None
     assert run_from_ipython() is False
Example #7
0
    def visualize(self,
                  show_ports=False,
                  color_scheme={},
                  show_atomistic=False,
                  scale=1.0):  # pragma: no cover
        """Visualize the Compound using py3dmol.

        Allows for visualization of a Compound within a Jupyter Notebook.
        Modified to from :py:meth:`mbuild.Compound.visualize` to show atomistic
        elements (translucent) with larger CG beads.

        Parameters
        ----------
        show_ports : bool, default False
            Visualize Ports in addition to Particles
        color_scheme : dict, default {}
            Specify coloring for non-elemental particles keys are strings of
            the particle names values are strings of the colors::

                {'_CGBEAD': 'blue'}

        show_atomistic : bool, default False
            Show the atomistic structure stored in
            :py:attr:`CG_Compound.atomistic`
        scale : float, default 1.0
            Scaling factor to modify the size of objects in the view.

        Returns
        -------
        view : py3Dmol.view
        """
        if not run_from_ipython():
            raise RuntimeError(
                "Visualization is only supported in Jupyter Notebooks.")
        import py3Dmol

        atom_names = []

        if self.atomistic is not None and show_atomistic:
            atomistic = clone(self.atomistic)
            for particle in atomistic:
                if not particle.name:
                    particle.name = "UNK"
                else:
                    if particle.name not in ("Compound", "CG_Compound"):
                        atom_names.append(particle.name)

        coarse = clone(self)
        modified_color_scheme = {}
        for name, color in color_scheme.items():
            # Py3dmol does some element string conversions,
            # first character is as-is, rest of the characters are lowercase
            new_name = name[0] + name[1:].lower()
            modified_color_scheme[new_name] = color
            modified_color_scheme[name] = color

        cg_names = []
        for particle in coarse:
            if not particle.name:
                particle.name = "UNK"
            else:
                if particle.name not in ("Compound", "CG_Compound"):
                    cg_names.append(particle.name)

        tmp_dir = tempfile.mkdtemp()

        view = py3Dmol.view()

        if atom_names:
            atomistic.save(
                os.path.join(tmp_dir, "atomistic_tmp.mol2"),
                show_ports=show_ports,
                overwrite=True,
            )

            # atomistic
            with open(os.path.join(tmp_dir, "atomistic_tmp.mol2"), "r") as f:
                view.addModel(f.read(), "mol2", keepH=True)

            if cg_names:
                opacity = 0.6
            else:
                opacity = 1.0

            view.setStyle({
                "stick": {
                    "radius": 0.2 * scale,
                    "opacity": opacity,
                    "color": "grey",
                },
                "sphere": {
                    "scale": 0.3 * scale,
                    "opacity": opacity,
                    "colorscheme": modified_color_scheme,
                },
            })

        # coarse
        if cg_names:
            # silence warning about No element found for CG bead
            with catch_warnings():
                simplefilter("ignore")
                coarse.save(
                    os.path.join(tmp_dir, "coarse_tmp.mol2"),
                    show_ports=show_ports,
                    overwrite=True,
                )
            with open(os.path.join(tmp_dir, "coarse_tmp.mol2"), "r") as f:
                view.addModel(f.read(), "mol2", keepH=True)

            if self.atomistic is None:
                scale = 0.3 * scale
            else:
                scale = 0.7 * scale

            view.setStyle(
                {"atom": cg_names},
                {
                    "stick": {
                        "radius": 0.2 * scale,
                        "opacity": 1,
                        "color": "grey",
                    },
                    "sphere": {
                        "scale": scale,
                        "opacity": 1,
                        "colorscheme": modified_color_scheme,
                    },
                },
            )

        view.zoomTo()

        return view