Exemplo n.º 1
0
    def __init__(self, text, xyz, color='red'):
        """ Displays a text in VMD.

        The function returns an instance of VMDGraphicsObject. To delete it, use the delete() method.

        Parameters
        ----------
        text : str
            The text
        xyz : list
            The position of the text
        color : str
            Color of the text
        """
        super().__init__(xyz)
        self._remember('draw materials off')
        self._remember('draw color {}'.format(color))

        self._remember('draw text "{} {} {}" "{}"\n'.format(
            xyz[0], xyz[1], xyz[2], text))
        self.script.write("\n")
        self.script.write("set htmd_graphics_mol({:d}) [molinfo top]".format(
            self.n))
        cmd = self.script.getvalue()
        vmd = getCurrentViewer()
        vmd.send(cmd)
Exemplo n.º 2
0
    def __init__(self, xyz, color='red', radius=1):
        """ Displays a sphere in VMD.

        The function returns an instance of VMDGraphicsObject. To delete it, use the delete() method.

        Parameters
        ----------
        xyz : list
            The center of the sphere
        color : str
            Color of the sphere
        radius : float
            The radius of the sphere
        """
        super().__init__(xyz)
        #self._remember('draw materials off')
        self._remember('draw color {}'.format(color))

        self._remember('draw sphere "{} {} {}" radius {}\n'.format(
            xyz[0], xyz[1], xyz[2], radius))
        self.script.write("\n")
        self.script.write("set htmd_graphics_mol({:d}) [molinfo top]".format(
            self.n))
        cmd = self.script.getvalue()
        vmd = getCurrentViewer()
        vmd.send(cmd)
Exemplo n.º 3
0
    def __init__(self, start, end, color='red', radius=1):
        """ Displays a cylinder in VMD.

        The function returns an instance of VMDGraphicsObject. To delete it, use the delete() method.

        Parameters
        ----------
        start : list
            The starting coordinates of the cylinder
        end : list
            The ending coordinates of the cylinder
        color : str
            Color of the cylinder
        radius : float
            The radius of the cylinder
        """
        super().__init__([start, end])
        #self._remember('draw materials off')
        self._remember('draw color {}'.format(color))
        self._remember('draw cylinder {{ {} }} {{ {} }} radius {}\n'.format(
            ' '.join(map(str, start)), ' '.join(map(str, end)), radius))
        self.script.write("\n")
        self.script.write("set htmd_graphics_mol({:d}) [molinfo top]".format(
            self.n))
        cmd = self.script.getvalue()
        vmd = getCurrentViewer()
        vmd.send(cmd)
Exemplo n.º 4
0
    def __init__(self, xyz, color="red", radius=1):
        """Displays a sphere in VMD.

        The function returns an instance of VMDGraphicsObject. To delete it, use the delete() method.

        Parameters
        ----------
        xyz : list
            The center of the sphere
        color : str
            Color of the sphere
        radius : float
            The radius of the sphere
        """
        super().__init__(xyz)
        # self._remember('draw materials off')
        self._remember(f"draw color {color}")

        self._remember(
            f'draw sphere "{xyz[0]} {xyz[1]} {xyz[2]}" radius {radius}\n')
        self.script.write("\n")
        self.script.write(f"set htmd_graphics_mol({self.n}) [molinfo top]")
        cmd = self.script.getvalue()
        vmd = getCurrentViewer()
        vmd.send(cmd)
Exemplo n.º 5
0
    def __init__(self, mol, style="", preamble="", solid=False):
        """Display the convex hull of the given molecule.

        For preamble and color, see http://www.ks.uiuc.edu/Research/vmd/vmd-1.9.2/ug/node129.html

        The function returns an instance of VMDGraphicsObject. To delete it, use the delete() method.

        Parameters
        ----------
        m: Molecule
            The object of which to show the hull (only 1 frame)
        style: str
            Style for wireframe lines
        preamble: str
            Commands (material, color) to be prefixed to the output.
            E.g.: "draw color red; graphics top materials on; graphics top material Transparent".
            Note that this affects later preamble-less commands.
        solid: bool
            Solid or wireframe

        Examples
        --------
        >>> from moleculekit.vmdgraphics import VMDConvexHull
        >>> m=Molecule("3PTB")
        >>> m.view()
        >>> mf=m.copy()
        >>> _ = mf.filter("protein ")
        >>> gh=VMDConvexHull(mf)  # doctest: +ELLIPSIS
        >>> gh.delete()
        """

        from scipy.spatial import ConvexHull

        if mol.coords.shape[2] != 1:
            raise Exception("Only one frame is supported")

        cc = mol.coords[:, :, 0]
        hull = ConvexHull(cc)

        super().__init__(hull)
        self.script.write(preamble + "\n")

        for i in range(hull.nsimplex):
            v1, v2, v3 = hull.simplices[i, :]
            c1s = VMDGraphicObject.tq(cc[v1, :])
            c2s = VMDGraphicObject.tq(cc[v2, :])
            c3s = VMDGraphicObject.tq(cc[v3, :])
            if solid:
                self._remember(f"draw triangle {c1s} {c2s} {c3s}")
            else:
                self._remember(f"draw line {c1s} {c2s} {style}")
                self._remember(f"draw line {c1s} {c3s} {style}")
                self._remember(f"draw line {c2s} {c3s} {style}")
                self.script.write("\n")

        self.script.write(f"set htmd_graphics_mol({self.n}) [molinfo top]")
        cmd = self.script.getvalue()
        vmd = getCurrentViewer()
        vmd.send(cmd)
Exemplo n.º 6
0
def _prepareViewer(mol, ligandsel):
    mol.view(sel="protein", style="lines", hold=True)
    mol.view(sel=ligandsel, style="licorice", hold=True)
    mol.view()

    viewer = getCurrentViewer()
    viewer.send("draw color red")
    viewer.send("color Display Background black")
    viewer.send("draw materials off")
    return viewer
Exemplo n.º 7
0
def _prepareViewer(mol, ligandsel):
    mol.view(sel='protein', style='lines', hold=True)
    mol.view(sel=ligandsel, style='licorice', hold=True)
    mol.view()

    viewer = getCurrentViewer()
    viewer.send('draw color red')
    viewer.send('color Display Background black')
    viewer.send('draw materials off')
    return viewer
Exemplo n.º 8
0
    def __init__(self, box, color='red'):
        """ Displays a box in VMD as lines of its edges.

        The function returns an instance of VMDGraphicsObject. To delete it, use the delete() method.

        Parameters
        ----------
        box : list
            The min and max positions of the edges. Given as [xmin, xmax, ymin, ymax, zmin, zmax]
        color : str
            Color of the lines
        """
        super().__init__(box)
        xmin, xmax, ymin, ymax, zmin, zmax = box
        mi = [xmin, ymin, zmin]
        ma = [xmax, ymax, zmax]

        self._remember('draw materials off')
        self._remember('draw color {}'.format(color))

        self._remember('draw line "{} {} {}" "{} {} {}"\n'.format(
            mi[0], mi[1], mi[2], ma[0], mi[1], mi[2]))
        self._remember('draw line "{} {} {}" "{} {} {}"\n'.format(
            mi[0], mi[1], mi[2], mi[0], ma[1], mi[2]))
        self._remember('draw line "{} {} {}" "{} {} {}"\n'.format(
            mi[0], mi[1], mi[2], mi[0], mi[1], ma[2]))

        self._remember('draw line "{} {} {}" "{} {} {}"\n'.format(
            ma[0], mi[1], mi[2], ma[0], ma[1], mi[2]))
        self._remember('draw line "{} {} {}" "{} {} {}"\n'.format(
            ma[0], mi[1], mi[2], ma[0], mi[1], ma[2]))

        self._remember('draw line "{} {} {}" "{} {} {}"\n'.format(
            mi[0], ma[1], mi[2], ma[0], ma[1], mi[2]))
        self._remember('draw line "{} {} {}" "{} {} {}"\n'.format(
            mi[0], ma[1], mi[2], mi[0], ma[1], ma[2]))

        self._remember('draw line "{} {} {}" "{} {} {}"\n'.format(
            mi[0], mi[1], ma[2], ma[0], mi[1], ma[2]))
        self._remember('draw line "{} {} {}" "{} {} {}"\n'.format(
            mi[0], mi[1], ma[2], mi[0], ma[1], ma[2]))

        self._remember('draw line "{} {} {}" "{} {} {}"\n'.format(
            ma[0], ma[1], ma[2], ma[0], ma[1], mi[2]))
        self._remember('draw line "{} {} {}" "{} {} {}"\n'.format(
            ma[0], ma[1], ma[2], mi[0], ma[1], ma[2]))
        self._remember('draw line "{} {} {}" "{} {} {}"\n'.format(
            ma[0], ma[1], ma[2], ma[0], mi[1], ma[2]))
        self.script.write("\n")
        self.script.write("set htmd_graphics_mol({:d}) [molinfo top]".format(
            self.n))
        cmd = self.script.getvalue()
        vmd = getCurrentViewer()
        vmd.send(cmd)
Exemplo n.º 9
0
def _drawForce(start, vec):
    assert start.ndim == 1 and vec.ndim == 1
    from moleculekit.vmdviewer import getCurrentViewer
    vmd = getCurrentViewer()
    vmd.send("""
    proc vmd_draw_arrow {start end} {
        # an arrow is made of a cylinder and a cone
        draw color green
        set middle [vecadd $start [vecscale 0.9 [vecsub $end $start]]]
        graphics top cylinder $start $middle radius 0.15
        graphics top cone $middle $end radius 0.25
    }
    """)
    vmd.send('vmd_draw_arrow {{ {} }} {{ {} }}'.format(
        ' '.join(map(str, start)), ' '.join(map(str, start + vec))))
Exemplo n.º 10
0
    def viewStates(self, protein=None, ligand=None, nsamples=20):
        from htmd.projections.metric import _singleMolfile
        from moleculekit.molecule import Molecule
        from moleculekit.vmdviewer import getCurrentViewer

        (single, molfile) = _singleMolfile(self.data.simlist)
        if not single:
            raise RuntimeError("Can"
                               "t visualize states without unique molfile")

        viewer = getCurrentViewer()
        colors = [0, 1, 3, 4, 5, 6, 7, 9]

        print("Active set includes macrostates: {}".format(
            self.hmm.active_set))

        # dtraj = np.vstack(self.hmm.discrete_trajectories_full)
        res = self.hmm.sample_by_observation_probabilities(nsamples)
        refmol = Molecule(molfile)

        for i, s in enumerate(self.hmm.active_set):
            mol = Molecule(molfile)
            mol.coords = []
            mol.box = []
            # idx = np.where(dtraj == i)[0]
            # samples = np.random.choice(idx, 20)
            # frames = self.data.abs2sim(samples)

            frames = self.data.rel2sim(res[i])
            for f in frames:
                mol._readTraj(f.sim.trajectory[f.piece],
                              frames=[f.frame],
                              append=True)
            mol.wrap("protein")
            mol.align("protein", refmol=refmol)
            viewer.loadMol(mol, name="hmm macro " + str(s))
            if ligand is not None:
                viewer.rep("ligand",
                           sel=ligand,
                           color=colors[np.mod(i, len(colors))])
            if protein is not None:
                viewer.rep("protein")
            viewer.send("start_sscache")
Exemplo n.º 11
0
    def __init__(self,
                 mol,
                 selection,
                 molid="top",
                 textsize=0.5,
                 textcolor="green"):
        """Displays labels on atoms in VMD.

        Examples
        --------
        >>> from moleculekit.molecule import Molecule  # doctest: +ELLIPSIS
        >>> from moleculekit.vmdgraphics import VMDLabels
        >>> mol = Molecule('3ptb')
        >>> mol.view()
        >>> x = VMDLabels(mol, 'resid 40')
        >>> y = VMDLabels(mol, 'resid 50')
        >>> y.delete()
        >>> x.delete()
        """
        # TODO: After deleting labels it breaks. Better don't delete or fix the code
        super().__init__(None)
        idx = mol.atomselect(selection, indexes=True)
        cmd = """label textsize {s}
color Labels Atoms {c}
set molnum [molinfo {molid}]
set i {start}
foreach n [list {idx}] {{
    label add Atoms $molnum/$n
    label textformat Atoms $i {{%a}}
    incr i
}}""".format(
            s=textsize,
            c=textcolor,
            sel=selection,
            molid=molid,
            idx=" ".join(map(str, idx)),
            start=VMDLabels.count,
        )
        self.labelidx = list(range(VMDLabels.count,
                                   VMDLabels.count + len(idx)))
        VMDLabels.count += len(idx)
        vmd = getCurrentViewer()
        vmd.send(cmd)
Exemplo n.º 12
0
    def __init__(self, text, xyz, color="red"):
        """Displays a text in VMD.

        The function returns an instance of VMDGraphicsObject. To delete it, use the delete() method.

        Parameters
        ----------
        text : str
            The text
        xyz : list
            The position of the text
        color : str
            Color of the text
        """
        super().__init__(xyz)
        self._remember("draw materials off")
        self._remember(f"draw color {color}")

        self._remember(f'draw text "{xyz[0]} {xyz[1]} {xyz[2]}" "{text}"\n')
        self.script.write("\n")
        self.script.write(f"set htmd_graphics_mol({self.n}) [molinfo top]")
        cmd = self.script.getvalue()
        vmd = getCurrentViewer()
        vmd.send(cmd)
Exemplo n.º 13
0
 def delete(self):
     vmd = getCurrentViewer()
     for i in self.labelidx[::-1]:
         vmd.send(f"label delete Atoms {i}")
         VMDLabels.count -= 1
Exemplo n.º 14
0
 def delete(self):
     vmd = getCurrentViewer()
     vmd.send(f"mol delete htmd_graphics_mol({self.n})")
Exemplo n.º 15
0
def generateCrystalPacking(pdbid, hexagonal=False, visualize=False, viewerhandle=None):
    """
    Generates the crystal packing of a PDB protein.

    It is possible to inspect it immediately with the visualize option. It can only be generated if there is
    crystallographic information in the PDB entry.

    Parameters
    ----------
    pdbid : str
        ID from the Protein Databank
    hexagonal : bool
        # TODO: Undocumented
    visualize : bool
        If True, this function also visualizes the crystal packing
    viewerhandle : :class:`VMD <moleculekit.vmdviewer.VMD>` object, optional
        A specific viewer in which to visualize the molecule. If None it will use the current default viewer.
    Returns
    -------
    mol : :class:`Molecule`
        Molecule object with the crystal packing
    """

    if not isinstance(pdbid, str):
        raise ValueError('pdbid should be a string')

    filename, _ = _getPDB(pdbid)

    mol = Molecule(filename)

    if viewerhandle is not None and not visualize:
        logger.warning('A viewerhandle was passed. Setting visualize to True.')
        visualize = True
    if visualize and viewerhandle is None:
        from moleculekit.vmdviewer import getCurrentViewer
        viewerhandle = getCurrentViewer()

    if mol.crystalinfo is None or 'numcopies' not in mol.crystalinfo:
        raise RuntimeError('No crystallography data found in Molecule.')
    ci = mol.crystalinfo

    alpha, beta, gamma, a, b, c = ci['alpha'], ci['beta'], ci['gamma'], ci['a'], ci['b'], ci['c']
    alpha = np.deg2rad(float(alpha))
    beta = np.deg2rad(float(beta))
    gamma = np.deg2rad(float(gamma))

    caux = (np.cos(alpha) - np.cos(beta) * np.cos(gamma)) / np.sin(gamma)
    axes = np.array([[a, 0, 0], [b * np.cos(gamma), b * np.sin(gamma), 0], [c * np.cos(beta), c * caux,
                    c * np.sqrt(1 - np.cos(beta) ** 2 - caux ** 2)]])
    size = np.array([axes[0][0], axes[1][1], axes[2][2]])

    molunit = Molecule()

    # Creates copies of the molecule and places them correctly inside the complete Unit Cell
    hexagonal_molunit = None
    for i in tqdm(range(ci['numcopies']), desc='Generating symmetry mates'):
        molecule = mol.copy()
        molecule.segid[:] = str(i+1)
        # apply SMTRY (Crystal Symmetry) operations
        molecule.rotateBy(ci['rotations'][i])
        molecule.moveBy(ci['translations'][i])
        # apply translation to inside of same Unit Cell.
        _place_crystal(molecule, size, [alpha, beta, gamma], axes)
        # pack copies to target Unit Cell
        molunit.append(molecule)
    if ci['sGroup'][0] == 'H' and hexagonal:
        hexagonal_molunit = Molecule()
        _build_hexagon(molunit, hexagonal_molunit)

    if hexagonal_molunit is not None:
        if visualize:
            hexagonal_molunit.view(style='NewCartoon', viewerhandle=viewerhandle)
        else:
            return hexagonal_molunit
    else:
        if visualize:
            molunit.view(style='NewCartoon', viewerhandle=viewerhandle)
        else:
            return molunit

    if visualize:
        _draw_cell(axes, ci['sGroup'], viewerhandle, hexagonal=hexagonal)
Exemplo n.º 16
0
    def test_crystalpacking_visualization(self):
        from moleculekit.vmdviewer import getCurrentViewer

        viewer = getCurrentViewer(dispdev='text')
        generateCrystalPacking('3ptb', visualize=True, viewerhandle=viewer)