Exemple #1
0
 def visualize(self, show_ports=False, shader='lambert',
               drawing_type='ball and stick', camera_type='perspective',
               element_properties=None):
     """Visualize the Compound using imolecule. """
     json_mol = self._to_json(show_ports)
     imolecule.draw(json_mol, format='json', shader=shader,
                    drawing_type=drawing_type, camera_type=camera_type,
                    element_properties=element_properties)
Exemple #2
0
 def draw(self, method: str = 'imolecule', **kwargs: Any) -> None:
     bond = self.bondmatrix(1.3)
     if method == 'imolecule':
         import imolecule  # type: ignore
         obj = {
             'atoms': [{
                 'element': atom.specie,
                 'location': atom.coord.tolist()
             } for atom in self],
             'bonds': [{
                 'atoms': [i, j],
                 'order': 1
             } for i in range(len(self)) for j in range(i) if bond[i, j]]
         }
         imolecule.draw(obj, 'json', **kwargs)
def visualize_Molecules(molecules, angstroms=False):
    '''
    Returns a 3D representation of a list of molecules
    INPUTS:
     molecules --> a list of Pyquante molecules
     angstroms --> a True or False value indicating if it is in angstroms.
    '''

    renders = []
    for mol in molecules:
        mol = mol.copy()
        # convert angstrom to bohr
        if angstroms:
            for atom in mol:
                coords = [a / ang2bohr for a in atom.pos()]
                atom.update_coords(coords)
        # create as xyz string
        xyz_str = mol.as_string()
        renders.append(
            imolecule.draw(xyz_str,
                           size=(200, 150),
                           format='xyz',
                           shader="phong",
                           display_html=False))
    columns = ('<div class="col-xs-6 col-sm-3">{}</div>'.format(r)
               for r in renders)
    return display(HTML('<div class="row">{}</div>'.format("".join(columns))))
Exemple #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)
                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.')
def renderPolymorphs(polymorphs, shader='basic'):
    """ Displays geometries of all polymorphs in the current generation """
    renders = (imolecule.draw(p.gzmat_string, format='gzmat', size=(200, 150),
                              shader=shader, display_html=False, resizeable=False) \
               for p in polymorphs)
    columns = ('<div class="col-xs-6 col-sm-3">{}</div>'.format(r)
               for r in renders)
    display(HTML('<div class="row">{}</div>'.format("".join(columns))))
Exemple #6
0
    def _repr_html_(self):
        """For IPython notebook, renders 3D pybel.Molecule webGL objects."""

        # Returning None defers to _repr_svg_
        if not ipython_3d:
            return None

        try:
            import imolecule
        except ImportError:
            raise ImportError("Cannot import 3D rendering. Please install " "with `pip install imolecule`.")
        return imolecule.draw(self.clone, format="pybel", display_html=False)
Exemple #7
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.')
Exemple #8
0
    def _repr_html_(self):
        """For IPython notebook, renders 3D pybel.Molecule webGL objects."""

        # Returning None defers to _repr_svg_
        if not ipython_3d:
            return None

        try:
            import imolecule
        except ImportError:
            raise ImportError("Cannot import 3D rendering. Please install "
                              "with `pip install imolecule`.")
        return imolecule.draw(self.clone, format="pybel", display_html=False)
Exemple #9
0
def _toJSON(mol):
    """For IPython notebook, renders 3D webGL objects."""

    if not ipython_3d or not mol.GetNumConformers():
        return None

    try:
        import imolecule
    except ImportError:
        raise ImportError("Cannot import 3D rendering. Please install "
                          "with `pip install imolecule`.")

    conf = mol.GetConformer()
    if not conf.Is3D():
        return None

    mol = Chem.Mol(mol)
    try:
        Chem.Kekulize(mol)
    except Exception:
        mol = Chem.Mol(mol)
    size = molSize_3d

    # center the molecule:
    atomps = numpy.array(
        [list(conf.GetAtomPosition(x)) for x in range(mol.GetNumAtoms())])
    avgP = numpy.average(atomps, 0)
    atomps -= avgP

    # Convert the relevant parts of the molecule into JSON for rendering
    atoms = [{
        "element": atom.GetSymbol(),
        "location": list(atomps[atom.GetIdx()])
    } for atom in mol.GetAtoms()]
    bonds = [{
        "atoms": [bond.GetBeginAtomIdx(),
                  bond.GetEndAtomIdx()],
        "order": int(bond.GetBondTypeAsDouble())
    } for bond in mol.GetBonds()]
    mol = {"atoms": atoms, "bonds": bonds}
    return imolecule.draw({
        "atoms": atoms,
        "bonds": bonds
    },
                          format="json",
                          size=molSize_3d,
                          drawing_type=drawing_type_3d,
                          camera_type=camera_type_3d,
                          shader=shader_3d,
                          display_html=False)
def visualize_Mol(molecule, angstroms=True):
    '''
    Returns a 3D representation of a molecule
    INPUTS:
     molecule --> a Pyquante molecule
     angstroms --> a True or False value indicating if it is in angstroms.
    '''

    mol = molecule.copy()
    # convert angstrom to bohr
    if angstroms:
        for atom in mol:
            coords = [a / ang2bohr for a in atom.pos()]
            atom.update_coords(coords)
    # create as xyz string
    xyz_str = mol.as_string()
    return imolecule.draw(xyz_str, format='xyz', shader="phong")
    def renderGeneration(self, generation_number=-1, shader='lambert'):
        """ Displays geometries of all polymorphs in the current generation """
        if generation_number > self.current_generation_number:
            raise ValueError(
                f"Generation {generation_number} does not exist (yet)")

        if generation_number == -1:
            generation = self.current_generation
        else:
            generation = self.population_timeline[generation_number]

        renders = (imolecule.draw(p.gzmat_string, format='gzmat', size=(200, 150),
                                  shader=shader, display_html=False, resizeable=False) \
                   for p in generation.values())
        columns = ('<div class="col-xs-6 col-sm-3">{}</div>'.format(r)
                   for r in renders)
        display(HTML('<div class="row">{}</div>'.format("".join(columns))))
Exemple #12
0
def _toJSON(mol):
    """For IPython notebook, renders 3D webGL objects."""

    if not ipython_3d or not mol.GetNumConformers():
        return None

    try:
        import imolecule
    except ImportError:
        raise ImportError("Cannot import 3D rendering. Please install "
                          "with `pip install imolecule`.")

    conf = mol.GetConformer()
    if not conf.Is3D():
        return None

    mol = Chem.Mol(mol)
    try:
        Chem.Kekulize(mol)
    except:
        mol = Chem.Mol(mol)
    size = molSize_3d

    # center the molecule:
    atomps = numpy.array([list(conf.GetAtomPosition(x))
                          for x in range(mol.GetNumAtoms())])
    avgP = numpy.average(atomps, 0)
    atomps -= avgP

    # Convert the relevant parts of the molecule into JSON for rendering
    atoms = [{"element": atom.GetSymbol(),
              "location": list(atomps[atom.GetIdx()])}
             for atom in mol.GetAtoms()]
    bonds = [{"atoms": [bond.GetBeginAtomIdx(),
                        bond.GetEndAtomIdx()],
              "order": int(bond.GetBondTypeAsDouble())}
             for bond in mol.GetBonds()]
    mol = {"atoms": atoms, "bonds": bonds}
    return imolecule.draw({"atoms": atoms, "bonds": bonds}, format="json",
                          size=molSize_3d, drawing_type=drawing_type_3d,
                          camera_type=camera_type_3d, shader=shader_3d,
                          display_html=False)
Exemple #13
0
    def viewms(objs, molSize=(160, 160), nmr=6):

        if not isinstance(objs, (tuple, list)):
            objs = [objs]

        # convert to a file format recognizable by imolecule, i.e., sdf
        ms = []
        for obj in objs:
            typ = type(obj)
            if typ is Chem.rdchem.Mol:
                ms.append(Chem.MolToMolBlock(obj))
            elif typ is str:  #oechem.OEGraphMol:
                if os.path.exists(obj):
                    assert obj[-3:] in ['sdf', 'mol'
                                        ], '#ERROR: file format not supported'
                    ms.append(''.join(open(obj).readlines()))
                else:
                    print(' ** assume smiles string ')
                    ms.append(Chem.MolToMolBlock(Chem.MolFromSmiles(obj)))
        if len(ms) == 1:
            return [imol.draw(ms[0], 'sdf', size=molSize)]
        else:
            return draw_imol.html(ms, 'sdf', size=molSize, nmr=nmr)
Exemple #14
0
 def draw(self, method='imolecule', **kwargs):
     if method == 'imolecule':
         import imolecule
         imolecule.draw(self.to_json(), 'json', **kwargs)
Exemple #15
0
 def html(ms, fmt, size=(240, 240), nmr=6):
     renders = (imol.draw(m, fmt, size=size, display_html=False)
                for m in ms)
     columns = ('<div class="col-xs-8 col-sm-4">{}</div>'.format(r)
                for r in renders)
     return HTML('<div class="row">{}</div>'.format("".join(columns)))
Exemple #16
0
import imolecule

from IPython.display import display, HTML
carbons = ("c1{}c1".format("c" * i) for i in range(3, 5))
renderer = imolecule.draw(next(carbons), size=(200, 150), shader='lambert', display_html=False)
Exemple #17
0
def visualize(smiles):
    imolecule.draw(smiles)
Exemple #18
0
 def draw(self, method='imolecule', **kwargs):
     if method == 'imolecule':
         import imolecule
         imolecule.draw(self.to_json(), 'json', **kwargs)
Exemple #19
0
def fig_Structure(execution):
    pdbFile = execution.read("PDBview", raw=True)
    return imolecule.draw(pdbFile[7:])