예제 #1
0
 def filereader():
     obmol = ob.OBMol()
     notatend = obconversion.ReadFile(obmol, filename)
     while notatend:
         yield Molecule(obmol)
         obmol = ob.OBMol()
         notatend = obconversion.Read(obmol)
예제 #2
0
파일: jybel.py 프로젝트: ostrokach/cinfony
def readstring(format, string):
    """Read in a molecule from a string.

    Required parameters:
       format - see the informats variable for a list of available
                input formats
       string

    Example:
    >>> input = "C1=CC=CS1"
    >>> mymol = readstring("smi", input)
    >>> len(mymol.atoms)
    5
    """
    obmol = ob.OBMol()
    obconversion = ob.OBConversion()

    formatok = obconversion.SetInFormat(format)
    if not formatok:
        raise ValueError("%s is not a recognised OpenBabel format" % format)

    success = obconversion.ReadString(obmol, string)
    if not success:
        raise IOError("Failed to convert '%s' to format '%s'" %
                      (string, format))
    return Molecule(obmol)
예제 #3
0
파일: jybel.py 프로젝트: ostrokach/cinfony
def readfile(format, filename):
    """Iterate over the molecules in a file.

    Required parameters:
       format - see the informats variable for a list of available
                input formats
       filename

    You can access the first molecule in a file using the next() method
    of the iterator:
        mol = readfile("smi", "myfile.smi").next()
        
    You can make a list of the molecules in a file using:
        mols = list(readfile("smi", "myfile.smi"))
        
    You can iterate over the molecules in a file as shown in the
    following code snippet:
    >>> atomtotal = 0
    >>> for mol in readfile("sdf", "head.sdf"):
    ...     atomtotal += len(mol.atoms)
    ...
    >>> print atomtotal
    43
    """
    obconversion = ob.OBConversion()
    formatok = obconversion.SetInFormat(format)
    if not formatok:
        raise ValueError("%s is not a recognised OpenBabel format" % format)
    if not os.path.isfile(filename):
        raise IOError("No such file: '%s'" % filename)
    obmol = ob.OBMol()
    notatend = obconversion.ReadFile(obmol, filename)
    while notatend:
        yield Molecule(obmol)
        obmol = ob.OBMol()
        notatend = obconversion.Read(obmol)
예제 #4
0
def readstring(format, string, opt=None):
    """Read in a molecule from a string.

    Required parameters:
       format - see the informats variable for a list of available
                input formats
       string

    Optional parameters:
       opt    - a dictionary of format-specific options
                For format options with no parameters, specify the
                value as None.

    Example:
    >>> input = "C1=CC=CS1"
    >>> mymol = readstring("smi", input)
    >>> len(mymol.atoms)
    5
    """
    if opt is None:
        opt = {}

    obmol = ob.OBMol()
    obconversion = ob.OBConversion()

    formatok = obconversion.SetInFormat(format)
    if not formatok:
        raise ValueError("%s is not a recognised Open Babel format" % format)
    for k, v in opt.items():
        if v is None:
            obconversion.AddOption(k, obconversion.INOPTIONS)
        else:
            obconversion.AddOption(k, obconversion.INOPTIONS, str(v))

    success = obconversion.ReadString(obmol, string)
    if not success:
        raise IOError("Failed to convert '%s' to format '%s'" %
                      (string, format))
    return Molecule(obmol)
예제 #5
0
    def draw(self, show=True, filename=None, update=False, usecoords=False):
        """Create a 2D depiction of the molecule.

        Optional parameters:
          show -- display on screen (default is True)
          filename -- write to file (default is None)
          update -- update the coordinates of the atoms to those
                    determined by the structure diagram generator
                    (default is False)
          usecoords -- don't calculate 2D coordinates, just use
                       the current coordinates (default is False)

        Tkinter and Python Imaging Library are required for image display.
        """
        obconversion = ob.OBConversion()
        formatok = obconversion.SetOutFormat("_png2")
        if not formatok:
            raise ImportError("PNG depiction support not found. You should "
                              "compile Open Babel with support for Cairo. See "
                              "installation instructions for more "
                              "information.")

        # Need to copy to avoid removing hydrogens from self
        workingmol = Molecule(ob.OBMol(self.OBMol))
        workingmol.removeh()

        if not usecoords:
            _operations['gen2D'].Do(workingmol.OBMol)
        if update:
            if workingmol.OBMol.NumAtoms() != self.OBMol.NumAtoms():
                raise RuntimeError("It is not possible to update the original "
                                   "molecule with the calculated coordinates, "
                                   "as the original molecule contains "
                                   "explicit hydrogens for which no "
                                   "coordinates have been calculated.")
            else:
                for i in range(workingmol.OBMol.NumAtoms()):
                    self.OBMol.GetAtom(i + 1).SetVector(
                        workingmol.OBMol.GetAtom(i + 1).GetVector())
        if filename:
            filedes = None
        else:
            if sys.platform[:3] == "cli" and show:
                raise RuntimeError("It is only possible to show the molecule "
                                   "if you provide a filename. The reason for "
                                   "this is that I kept having problems "
                                   "when using temporary files.")

            filedes, filename = tempfile.mkstemp()

        workingmol.write("_png2", filename=filename, overwrite=True)

        if show:
            if sys.platform[:4] == "java":
                image = javax.imageio.ImageIO.read(java.io.File(filename))
                frame = javax.swing.JFrame(visible=1)
                frame.getContentPane().add(
                    javax.swing.JLabel(javax.swing.ImageIcon(image)))
                frame.setSize(300, 300)
                frame.setDefaultCloseOperation(
                    javax.swing.WindowConstants.DISPOSE_ON_CLOSE)
                frame.show()
            elif sys.platform[:3] == "cli":
                form = _MyForm()
                form.setup(filename, self.title)
                Application.Run(form)
            else:
                if not tk:
                    raise ImportError("Tkinter or Python Imaging Library not "
                                      "found, but is required for image "
                                      "display. See installation instructions "
                                      "for more information.")
                root = tk.Tk()
                root.title((hasattr(self, "title") and self.title)
                           or self.__str__().rstrip())
                frame = tk.Frame(root, colormap="new",
                                 visual='truecolor').pack()
                image = PIL.open(filename)
                imagedata = piltk.PhotoImage(image)
                tk.Label(frame, image=imagedata).pack()
                tk.Button(root, text="Close",
                          command=root.destroy).pack(fill=tk.X)
                root.mainloop()
        if filedes:
            os.close(filedes)
            os.remove(filename)
예제 #6
0
 def clone(self):
     return Molecule(ob.OBMol(self.OBMol))