Пример #1
0
def build_molecule(smi, return_bonds=False, relax=True):
    """Build molecule from SMILES string.

    Parameters
    ==========
    smi: str
        SMILES string specifying the molecule to build
    return_bonds: bool
        If True, a list of list of 3xint describing the bonds will be returned.
    relax: bool
        If True, the geometry will be relaxed.

    See the wikipedia article for info:
        http://en.wikipedia.org/wiki/Simplified_molecular_input_line_entry_specification
    """

    obconv = ob.OBConversion()
    obconv.SetInAndOutFormats("smi", "mol")

    mol = ob.OBMol()
    obconv.ReadString(mol, smi)

    # Create 3D geometry
    obbuild = ob.OBBuilder()
    obbuild.Build(mol)

    mol.AddHydrogens()

    if relax:
        ff = ob.OBForceField.FindForceField('UFF')
        ff.Setup(mol)
        ff.ConjugateGradients(250, 1.0e-4)
        ff.UpdateCoordinates(mol)

    return obmol_to_atoms(mol, return_bonds=return_bonds)
def SimlesToMol2(string,file):
   obConversion = openbabel.OBConversion()
   obConversion.SetInAndOutFormats("smi", "mol2")

   mol = openbabel.OBMol()
   obConversion.ReadString(mol, string)

   mol.AddHydrogens()
   #mol.AddOption("gen3D",GENOPTIONS)
   # get the charges of the atoms
   # Reimplemented in OpenBabel::EEMCharges, OpenBabel::GasteigerCharges, OpenBabel::MMFF94Charges, and OpenBabel::NoCharges.
   #charge_model = openbabel.OBChargeModel.FindType("MMFF94")
   #openbabel.OBBuilder().Build(mol.OBMol)
   builder = openbabel.OBBuilder()
   builder.Build(mol)
   charge_model = openbabel.OBChargeModel.FindType("Gasteiger")
   charge_model.ComputeCharges(mol)
   partial_charges = charge_model.GetPartialCharges() 
   #print partial_charges

   print "charge = %f" % (sum(partial_charges))

   obConversion.WriteFile(mol, file)
 
   return
Пример #3
0
def createMolDict(mol_dict, steps=500, verbose=0, with_hydrogens=True):
    """
    Creates 3d coordinates from InChI using openbabel mmff94
    mol_dict [in] - dict where values - InChI strings
    steps [in] - steps for openbabel optimizer
    return: dictionary, key = <key from mol_dict>, value = <openbabel.OBMol>
    """
    #mol_dict[<mol_id>]=<InChI string>

    conv = openbabel.OBConversion()
    conv.SetInFormat("inchi")
    #conv.SetInAndOutFormats("inchi","mol")

    #create builder
    builder = openbabel.OBBuilder()

    #find Force Field
    ff = openbabel.OBForceField.FindForceField("mmff94")
    if ff is None:
        raise Exception("Cannot find Force Field mmff94")
        return None

    new_dict = {}

    for key in mol_dict:
        if verbose > 0:
            sys.stdout.write("\rProcess: " + str(key))
            sys.stdout.flush()

        mol = openbabel.OBMol()
        conv.ReadString(mol, mol_dict[key])

        # create 3D
        builder.Build(mol)

        # add hydrogens
        if with_hydrogens:
            mol.AddHydrogens()

        ff.Setup(mol)
        ff.SteepestDescent(steps)
        ff.GetCoordinates(mol)

        new_dict[key] = mol

    #conv.SetOutFormat("mol")
    #conv.WriteFile(mol,"test.mol")

    if verbose > 0:
        print " "

    return new_dict
Пример #4
0
def exchangeAtom(C, H, molTS, molFG, outfile, bondLength):
    # read write xyz file
    convTS, convFG = [ob.OBConversion() for i in range(2)]
    convTS.SetInAndOutFormats("xyz", "xyz")
    convFG.SetInAndOutFormats("xyz", "xyz")

    # builder
    builder = ob.OBBuilder()

    # define molecules, atoms and bond classes
    TS, FG = [ob.OBMol() for i in range(2)]
    atomH = ob.OBAtom()
    atomC = ob.OBAtom()
    bond = ob.OBBond()

    # read in xyz files
    convTS.ReadFile(TS, molTS)
    convFG.ReadFile(FG, molFG)

    # number of atoms in TS molecule
    numAtoms = TS.NumAtoms()

    # get hydrogen atom and its vector
    atomH = TS.GetAtom(H)
    atomC = TS.GetAtom(C)
    vec = ob.vector3(float(atomH.GetX()), float(atomH.GetY()),
                     float(atomH.GetZ()))

    # delete hydrogen atom
    TS.DeleteAtom(atomH)

    # put both molecules together (same coord system)
    TS += FG

    # making the bond
    builder.Connect(TS, C, numAtoms, vec, 1)

    bond = TS.GetBond(C, numAtoms)
    bond.SetLength(atomC, bondLength)

    # call opimizer
    #opt_mmff_FG(TS, numAtoms, outfile)

    convTS.WriteFile(TS, "single/" + outfile)

    # clear TS and FG molecule classes
    TS.Clear()
    FG.Clear()
Пример #5
0
def get_best_conformation(smiles=str):
    import openbabel
    mol = openbabel.OBMol()
    obConversion = openbabel.OBConversion()
    obConversion.SetInAndOutFormats("smi", "xyz")
    obConversion.ReadString(mol, smiles)
    mol.AddHydrogens()
    builder = openbabel.OBBuilder()
    builder.Build(mol)
    ff = openbabel.OBForceField.FindForceField("MMFF94")
    ff.Setup(mol)
    ff.SteepestDescent(250)
    ff.WeightedRotorSearch(200, 25)
    ff.ConjugateGradients(200)
    raw_xyz = obConversion.WriteString(mol)
    #print raw_xyw
    raw_string = str.split(raw_xyz, '\n')
    return raw_xyz, ff.Energy()
Пример #6
0
 def getOBMol(self, fst, convtype, ffclean=False):
     obConversion = openbabel.OBConversion()
     OBMol = openbabel.OBMol()
     if convtype == 'smistring':
         obConversion.SetInFormat('smi')
         obConversion.ReadString(OBMol, fst)
     else:
         obConversion.SetInFormat(convtype[:-1])
         obConversion.ReadFile(OBMol, fst)
     if 'smi' in convtype:
         OBMol.AddHydrogens()
         b = openbabel.OBBuilder()
         b.Build(OBMol)
     if ffclean:
         forcefield = openbabel.OBForceField.FindForceField('mmff94')
         forcefield.Setup(OBMol)
         forcefield.ConjugateGradients(200)
         forcefield.GetCoordinates(OBMol)
     self.OBMol = OBMol
     return OBMol
Пример #7
0
def make_structure(request):
    def makeResidue(mol, idx, aaatoms):
        res = mol.NewResidue()
        res.SetNum(idx)
        for atom in ob.OBMolAtomIter(mol):
            if atom.GetIdx() not in aaatoms:
                res.AddAtom(atom)

    aminoacids = request.GET.getlist("as")
    color = request.GET.get("rescol", "#3EC1CD")

    mol = ob.OBMol()
    conv = ob.OBConversion()
    pattern = ob.OBSmartsPattern()
    pattern.Init("[NX3][$([CX4H1]([*])),$([CX4H2])][CX3](=[OX1])[OX2]")
    builder = ob.OBBuilder()
    conv.SetInAndOutFormats("sdf", "svg")
    conv.AddOption("d", ob.OBConversion.OUTOPTIONS)
    conv.AddOption("b", ob.OBConversion.OUTOPTIONS, "none")
    conv.ReadString(mol, str(Substrate.objects.get(pk=int(aminoacids[0])).structure))
    pattern.Match(mol)
    mollist = pattern.GetUMapList()[0]
    oatom = mol.GetAtom(mollist[4])
    catom = mol.GetAtom(mollist[2])
    firstnatom = mol.GetAtom(mollist[0])
    makeResidue(mol, 0, mollist)

    i = 1
    for aa in aminoacids[1:]:
        mol2 = ob.OBMol()
        conv.ReadString(mol2, str(Substrate.objects.get(pk=int(aa)).structure))
        pattern.Match(mol2)
        mollist = pattern.GetUMapList()[0]
        makeResidue(mol2, i, mollist)

        molnatoms = mol.NumAtoms()
        mol += mol2

        natom = mol.GetAtom(molnatoms + mol2.GetAtom(mollist[0]).GetIdx())

        builder.Connect(mol, catom.GetIdx(), natom.GetIdx())

        foatom = mol.GetAtom(molnatoms + mol2.GetAtom(mollist[4]).GetIdx())
        catom = mol.GetAtom(molnatoms + mol2.GetAtom(mollist[2]).GetIdx())
        mol.DeleteHydrogens(oatom)
        mol.DeleteAtom(oatom)

        natom.SetImplicitValence(3)
        mol.DeleteHydrogens(natom)
        mol.AddHydrogens(natom)
        oatom = foatom

        i += 1

    nidx = firstnatom.GetIdx()
    oidx =  oatom.GetIdx()
    builder.Build(mol)
    natom = mol.GetAtom(nidx)
    oatom = mol.GetAtom(oidx)
    for res in ob.OBResidueIter(mol):
        for atom in ob.OBResidueAtomIter(res):
            for bond in ob.OBAtomBondIter(atom):
                data = ob.OBPairData()
                data.SetAttribute("color")
                data.SetValue(color)
                bond.CloneData(data)
    mol.DeleteHydrogens()
    gen2d = ob.OBOp.FindType("gen2d")
    gen2d.Do(mol)

    opp = oatom.GetY() - natom.GetY()
    adj = oatom.GetX() - natom.GetX()
    angle = abs(math.atan(opp / adj))
    if opp > 0 and adj > 0:
        pass
    elif opp > 0 and adj < 0:
        angle = math.pi - angle
    elif opp < 0 and adj < 0:
        angle = math.pi + angle
    elif opp < 0 and adj > 0:
        angle = 2 * math.pi - angle
    angle = -angle
    mol.Rotate(ob.double_array([math.cos(angle), -math.sin(angle), 0,
                                math.sin(angle), math.cos(angle),  0,
                                0,               0,                1]))
    svg = conv.WriteString(mol)
    # need to get rid of square aspect ratio
    delstart = svg.find("width")
    delend = svg.find("svg", delstart)
    delend = svg.find("viewBox", delend)
    svgend = svg.rfind("</g>")
    svg = svg[0:delstart] + svg[delend:svgend]
    return HttpResponse(svg, mimetype="image/svg+xml")
Пример #8
0
except ImportError: #pragma: no cover
    oasa = None

try:
    import Tkinter as tk
    import Image as PIL
    import ImageTk as piltk
except ImportError: #pragma: no cover
    tk = None

def _formatstodict(list):
    broken = [x.replace("[Read-only]", "").replace("[Write-only]","").split(" -- ") for x in list]
    broken = [(x,y.strip()) for x,y in broken]
    return dict(broken)
_obconv = ob.OBConversion()
_builder = ob.OBBuilder()
informats = _formatstodict(_obconv.GetSupportedInputFormat())
"""A dictionary of supported input formats"""
outformats = _formatstodict(_obconv.GetSupportedOutputFormat())
"""A dictionary of supported output formats"""

def _getplugins(findplugin, names):
    plugins = dict([(x, findplugin(x)) for x in names if findplugin(x)])
    return plugins
def _getpluginnames(ptype):
    plugins = ob.vectorString()
    ob.OBPlugin.ListAsVector(ptype, None, plugins)
    return [x.split()[0] for x in plugins]

descs = _getpluginnames("descriptors")
"""A list of supported descriptors"""