Esempio n. 1
0
    def addCharges(self, atoms):
        """
        compute gasteiger charges, add them to atoms, return list of new
        charges
        NB: assumes MolKit atoms have bonds
        NB: calls type atoms if all the atoms haven't been babel typed. 
        if babel_types have been set by hand, they will be ok IF every
        atom has a babel type

        """
        #print 'in computeGasteiger'
        #check that atoms have babel_types
        w_babel_types = atoms.get(lambda x: hasattr(x, 'babel_type'))
        if w_babel_types is None or len(w_babel_types)!=len(atoms):
            babel = AtomHybridization()
            #have to have bonds for this
            babel.assignHybridization(atoms)
        Gast = Gasteiger()
        Gast.compute(atoms)
        gastCharges = []
        for c in atoms.gast_charge:
            gastCharges.append(round(c, 4))
        #NB THIS adds entry 'gasteiger' to atom._charges dict
        atoms.addCharges('gasteiger', gastCharges)
        atoms.chargeSet = 'gasteiger'
        #clean-up
        delattr(atoms, 'gast_charge')
        return gastCharges
def getHBAtoms(mol):
    """
    Function to identify donor and acceptor atoms for hydrogen bonds

    d2, d3, a2, a3 <- getHBAtoms(mol)

    The function will first build bonds then assign atom hybridization
    and bond orders. Next it will use a HydrogenBondBuilder to identify and'
    report donor and acceptor atoms in sets corresponding to Sp2 and Sp3
    hybridization.
    A .hbstatus is added to all atoms. The value can be:
      NE: NEutral
      D2: Sp2 donor 
      D3: Sp3 donor 
      A2: Sp2 acceptor
      A3: Sp3 acceptor
      B2: Sp2 acceptor and donor
      B3: Sp3 acceptor and donor
    """
    # add bonds
    mol.buildBondsByDistance()
    atoms = mol.allAtoms

    # assign .babel_type
    from PyBabel.atomTypes import AtomHybridization
    atyper = AtomHybridization()
    atyper.assignHybridization(atoms)

    # assign bond order
    from PyBabel.bo import BondOrder
    bond_orderer = BondOrder()
    bond_orderer.assignBondOrder(atoms, atoms.bonds[0])

    # get donors
    from MolKit.hydrogenBondBuilder import HydrogenBondBuilder
    hbbuilder = HydrogenBondBuilder()
    donorTypes = hbbuilder.paramDict['donorTypes']
    donorsp2Ats, donorsp3Ats = hbbuilder.getHBDonors(atoms, donorTypes)

    # get acceptors
    acceptorTypes = hbbuilder.paramDict['acceptorTypes']
    acceptorsp2Ats, acceptorsp3Ats = hbbuilder.getHBAcceptors(atoms, acceptorTypes)
    # create hbstatus attribute
    atoms.hbstatus = 'NE'
    for a in donorsp2Ats:
        a.hbstatus = 'D2'
    for a in donorsp3Ats:
        a.hbstatus = 'D3'
    for a in acceptorsp2Ats:
        a.hbstatus = 'A2'
    for a in acceptorsp3Ats:
        a.hbstatus = 'A3'

    # handle atoms that are both donors and acceptor
    for a in donorsp2Ats.inter(acceptorsp2Ats):
        a.hbstatus = 'B2'
    for a in donorsp3Ats.inter(acceptorsp3Ats):
        a.hbstatus = 'B3'

    return donorsp2Ats, donorsp3Ats, acceptorsp2Ats, acceptorsp3Ats
 def setAutoDockElements(self, mol, typeAtoms=0, reassign=False):
     if os.path.splitext(mol.parser.filename)[-1]=='.pdbqt' and reassign is False:
         if self.verbose:
             print 'setAutoDockElements unnecessary:\n', mol.name, ' already has AD4 atomtypes: not reassigned!'
         return
     #check that the types have already been set, first
     if self.set_aromatic_carbons:
         #this sets the autodock_element for the planar cyclic carbons to 'A'
         aromatic_carbons = self.acm.setAromaticCarbons(mol)
     d = {}
     ah = AtomHybridization()
     if not len(mol.allAtoms.bonds[0]):
         mol.buildBondsByDistance()
     ats_with_babel_type = filter(lambda x: hasattr(x, 'babel_type'), mol.allAtoms)
     if typeAtoms or len(ats_with_babel_type)!=len(mol.allAtoms):
         if self.verbose:
             print "assigning babel_types"
         ah = AtomHybridization()
         ah.assignHybridization(mol.allAtoms)
     for item in mol.allAtoms:
         if not hasattr(item, 'autodock_element'):
             #item.element = item.element.upper()
             item.autodock_element = item.element
         if item.element=='H':
             if len(item.bonds):
                 n = item.bonds[0].neighborAtom(item)
                 if n.element not in ['C','A']:
                     item.autodock_element = 'HD'
             else:
                 #note: if there are no bonds, assume HD 
                 item.autodock_element = 'HD'
         elif item.element=='N':
             #this has already been done at beginning of for loop
             #if item.babel_type in ['N3+','Ntr', 'Nox']:
             #    item.autodock_element = 'N'
             if item.babel_type in ['N3','N2','N1']:
                 item.autodock_element = item.element + 'A'
             elif item.babel_type in ['Nam', 'Npl', 'Ng+']:
                 if len(item.bonds)==2:
                     item.autodock_element = item.element + 'A'
         elif item.element=='O':
             item.autodock_element = item.element + 'A'
         elif item.element=='S':
             #possible sulphur babel_types->['S3+','S3','S2','Sac','Sox','S']
             if item.babel_type not in ['Sox', 'Sac']:
                 item.autodock_element = item.element + 'A'
         elif item.element=='C':
             if item.parent.type+'_' + item.name in self.pep_aromList:
                 item.autodock_element = 'A'
                 if self.renameAtoms:  # 
                     if len(item.name)==1:
                         item.name = 'A'
                     else:
                         item.name = 'A' + item.name[1:]
             elif hasattr(item, 'autodock_element'):
                 item.autodock_element = item.autodock_element
         d[item.autodock_element] = 1
     type_list = d.keys()
     type_list.sort()
     mol.types = type_list
Esempio n. 4
0
    def addCharges(self, atoms):
        """
        compute gasteiger charges, add them to atoms, return list of new
        charges
        NB: assumes MolKit atoms have bonds
        NB: calls type atoms if all the atoms haven't been babel typed. 
        if babel_types have been set by hand, they will be ok IF every
        atom has a babel type

        """
        #print 'in computeGasteiger'
        #check that atoms have babel_types
        w_babel_types = atoms.get(lambda x: hasattr(x, 'babel_type'))
        if w_babel_types is None or len(w_babel_types) != len(atoms):
            babel = AtomHybridization()
            #have to have bonds for this
            babel.assignHybridization(atoms)
        Gast = Gasteiger()
        Gast.compute(atoms)
        gastCharges = []
        for c in atoms.gast_charge:
            gastCharges.append(round(c, 4))
        #NB THIS adds entry 'gasteiger' to atom._charges dict
        atoms.addCharges('gasteiger', gastCharges)
        atoms.chargeSet = 'gasteiger'
        #clean-up
        delattr(atoms, 'gast_charge')
        return gastCharges
 def check_babel_types(self, ats):
     try:
         ats.babel_type
         ats._bndtyped
     except AttributeError:
         babel = AtomHybridization()
         bond_orderer = BondOrder()
         tops = ats.top.uniq()
         for mol in tops:
             babel.assignHybridization(mol.allAtoms)
             bond_orderer.assignBondOrder(mol.allAtoms, mol.allAtoms.bonds[0])
             mol.allAtoms._bndtyped = 1
 def check_babel_types(self, ats):
     num_ats = len(ats)
     num_babel_type = len(ats.get(lambda x: hasattr(x, 'babel_type')))
     num_bnd_type = len(ats.get(lambda x: hasattr(x, 'bnd_type')))
     if (num_babel_type!=num_ats) or (num_bnd_type!=num_ats):
         babel = AtomHybridization()
         bond_orderer = BondOrder()
         tops = ats.top.uniq()
         for mol in tops: 
             babel.assignHybridization(mol.allAtoms)
             bond_orderer.assignBondOrder(mol.allAtoms, mol.allAtoms.bonds[0])
             mol.allAtoms._bndtyped = 1
Esempio n. 7
0
 def check_babel_types(self, ats):
     num_ats = len(ats)
     num_babel_type = len(ats.get(lambda x: hasattr(x, 'babel_type')))
     num_bnd_type = len(ats.get(lambda x: hasattr(x, 'bnd_type')))
     if (num_babel_type != num_ats) or (num_bnd_type != num_ats):
         babel = AtomHybridization()
         bond_orderer = BondOrder()
         tops = ats.top.uniq()
         for mol in tops:
             babel.assignHybridization(mol.allAtoms)
             bond_orderer.assignBondOrder(mol.allAtoms,
                                          mol.allAtoms.bonds[0])
             mol.allAtoms._bndtyped = 1
Esempio n. 8
0
 def select(self, bnds, bondOrder=1):
     ats = self.getAtoms(bnds)
     mols = ats.top.uniq()
     atype = AtomHybridization()
     for m in mols:
         if not m.chains[0].hasBonds:
             m.buildBondsByDistance()
         allAts = m.chains.residues.atoms
         atype.assignHybridization(allAts)
         rf = RingFinder()
         rf.findRings2(allAts, allAts.bonds[0])
         bo = BondOrder()
         bo.assignBondOrder(allAts, allAts.bonds[0], rf)
     return BondSet(bnds.get(lambda x, ord=bondOrder: x.bondOrder == ord))
 def select(self, bnds, bondOrder=1):
     ats = self.getAtoms(bnds)
     mols = ats.top.uniq()
     atype = AtomHybridization()
     for m in mols:
         if not m.chains[0].hasBonds:
             m.buildBondsByDistance()
         allAts = m.chains.residues.atoms
         atype.assignHybridization(allAts)
         rf = RingFinder()
         rf.findRings2(allAts, allAts.bonds[0])
         bo = BondOrder()
         bo.assignBondOrder(allAts, allAts.bonds[0], rf)
     return BondSet(bnds.get(lambda x, ord=bondOrder: x.bondOrder==ord))
Esempio n. 10
0
 def getLigandBondDict(self):
     ats = self.allAtoms
     babel = AtomHybridization()
     babel.assignHybridization(self.allAtoms)
     #typeBonds???
     #typeAtoms(ats)
     rf = RingFinder()
     rf.findRings2(ats, ats.bonds[0])
     ct = 1
     bondDict = {}
     for ring in rf.rings:
         bondDict[ct] = ring['bonds']
         for b in ring['bonds']:
             b.cyclenum = ct
         ct = ct + 1
     self.cyclecount = rf.ringCount
     self.bondDict = bondDict
 def select(self, bnds):
     ats = self.getAtoms(bnds)
     rf = RingFinder()
     #nb maxSize of ring is 20 by default
     rf.findRings2(ats, bnds, maxSize=len(ats))
     ats = self.getAtoms(rf.allRingBonds)
     allAts = ats.top.uniq().allAtoms
     atype = AtomHybridization()
     atype.assignHybridization(allAts)
     bo = BondOrder()
     bo.assignBondOrder(allAts, allAts.bonds[0], rf)
     arom = Aromatic(rf)
     arom.find_aromatic_atoms(ats)
     aromatic_bnds = ats.bonds[0].get(lambda x: x.bondOrder=='aromatic')
     aromatic_ats = self.getAtoms(aromatic_bnds)
     aromatic_ats.aromatic = 1
     return aromatic_bnds
Esempio n. 12
0
 def getLigandBondDict(self):
     ats = self.allAtoms
     babel = AtomHybridization()
     babel.assignHybridization(self.allAtoms)
     #typeBonds???
     #typeAtoms(ats)
     rf = RingFinder()
     rf.findRings2(ats, ats.bonds[0])
     ct = 1
     bondDict = {}
     for ring in rf.rings:
         bondDict[ct] = ring['bonds']
         for b in ring['bonds']:
             b.cyclenum = ct
         ct = ct + 1
     self.cyclecount = rf.ringCount
     self.bondDict = bondDict
Esempio n. 13
0
 def select(self, bnds):
     ats = self.getAtoms(bnds)
     rf = RingFinder()
     #nb maxSize of ring is 20 by default
     rf.findRings2(ats, bnds, maxSize=len(ats))
     ats = self.getAtoms(rf.allRingBonds)
     allAts = ats.top.uniq().allAtoms
     atype = AtomHybridization()
     atype.assignHybridization(allAts)
     bo = BondOrder()
     bo.assignBondOrder(allAts, allAts.bonds[0], rf)
     arom = Aromatic(rf)
     arom.find_aromatic_atoms(ats)
     aromatic_bnds = ats.bonds[0].get(lambda x: x.bondOrder == 'aromatic')
     aromatic_ats = self.getAtoms(aromatic_bnds)
     aromatic_ats.aromatic = 1
     return aromatic_bnds
Esempio n. 14
0
 def computeGasteiger(self):
     #to compute Gasteiger need to:
     #   create an AtomHybridization()
     #   call its assignHybridization method on self.allAtoms
     #   create a Gasteiger()
     #   call its compute method on self.allAtoms
     # THEN move gast_charge into _charges with gasteiger key
     #   set allAtoms.chargeSet to 'gasteiger'
     # THEN delattr gast_charge from allAtoms
     allAts = self.allAtoms
     ah = AtomHybridization()
     ah.assignHybridization(allAts)
     Gast = Gasteiger()
     Gast.compute(allAts)
     gastCharges = []
     for c in allAts.gast_charge:
         gastCharges.append(round(c, 3))
     allAts.addCharges('gasteiger', gastCharges)
     del allAts.gast_charge
     allAts.chargeSet = 'gasteiger'
Esempio n. 15
0
 def computeGasteiger(self):
     #to compute Gasteiger need to:
     #   create an AtomHybridization()
     #   call its assignHybridization method on self.allAtoms
     #   create a Gasteiger()
     #   call its compute method on self.allAtoms
     # THEN move gast_charge into _charges with gasteiger key
     #   set allAtoms.chargeSet to 'gasteiger'
     # THEN delattr gast_charge from allAtoms
     allAts = self.allAtoms
     ah = AtomHybridization()
     ah.assignHybridization(allAts)
     Gast = Gasteiger()
     Gast.compute(allAts)
     gastCharges = []
     for c in allAts.gast_charge:
         gastCharges.append(round(c, 3))
     allAts.addCharges('gasteiger', gastCharges)
     del allAts.gast_charge
     allAts.chargeSet = 'gasteiger'
Esempio n. 16
0
    def addHydrogens(self, mol):
        #check for bonds
        if len(mol.allAtoms.bonds[0]) == 0:
            mol.buildBondsByDistance()
        bonds = mol.allAtoms.bonds[0]
        #could have preset babel_types
        #so check if allAtoms are already typed
        try:
            t = mol.allAtoms.babel_type
        except:
            #if all are not pretyped, type them
            babel = AtomHybridization()
            babel.assignHybridization(mol.allAtoms)

        if self.method == 'withBondOrder':
            mol.rings = RingFinder()
            mol.rings.findRings2(mol.allAtoms, mol.allAtoms.bonds[0])
            mol.rings.bondRings = {}
            for ind in xrange(len(mol.rings.rings)):
                r = mol.rings.rings[ind]
                for b in r['bonds']:
                    if not mol.rings.bondRings.has_key(b):
                        mol.rings.bondRings[b] = [
                            ind,
                        ]
                    else:
                        mol.rings.bondRings[b].append(ind)
            bo = BondOrder()
            bo.assignBondOrder(mol.allAtoms, bonds, mol.rings)
            mol.allAtoms._bndtyped = 1
            # do aromatic here
            arom = Aromatic(mol.rings)
            arom.find_aromatic_atoms(mol.allAtoms)

        hat = AddHydrogens().addHydrogens(mol.allAtoms, method=self.method)
        bondedAtomDict = {}  # key is heavy atom
        for a in hat:
            if bondedAtomDict.has_key(a[1]):
                bondedAtomDict[a[1]].append(a)
            else:
                bondedAtomDict[a[1]] = [a]

        # now create Atom object for hydrogens
        # and add the to the residues's atom list
        molNewHs = AtomSet([])  # list of created H atoms for this molecule
        heavyAtoms = AtomSet([])  # list of atoms that need new radii

        for heavyAtom, HatmsDscr in bondedAtomDict.items():
            #don't add hydrogens to carbons: polar Only!!!
            if self.htype != 'all' and heavyAtom.element == 'C':
                continue
            res = heavyAtom.parent
            # find where to insert H atom
            childIndex = res.children.index(heavyAtom) + 1

            # loop over H atoms description to be added
            # start at the end to number correctly
            l = len(HatmsDscr)
            for i in range(l - 1, -1, -1):
                a = HatmsDscr[i]
                # build H atom's name
                if len(heavyAtom.name) == 1:
                    name = 'H' + heavyAtom.name
                else:
                    name = 'H' + heavyAtom.name[1:]

                # if more than 1 H atom, add H atom index
                # for instance HD11, HD12, Hd13 (index is 1,2,3)
                if l > 1:
                    name = name + str(i + 1)

                # create the H atom object
                atom = Atom(name,
                            res,
                            top=heavyAtom.top,
                            chemicalElement='H',
                            childIndex=childIndex,
                            assignUniqIndex=0)

                # set atoms attributes
                atom._coords = [a[0]]
                if hasattr(a[1], 'segID'): atom.segID = a[1].segID
                atom.hetatm = 0
                atom.alternate = []
                #atom.element = 'H'
                atom.occupancy = 1.0
                atom.conformation = 0
                atom.temperatureFactor = 0.0
                atom.babel_atomic_number = a[2]
                atom.babel_type = a[3]
                atom.babel_organic = 1
                atom.radius = 1.2

                # create the Bond object bonding Hatom to heavyAtom
                bond = Bond(a[1], atom, bondOrder=1)

                # add the created atom the the list
                molNewHs.append(atom)
                # in case this new hydrogen atom ever ends up in pmv
                # HAVE TO CREATE THESE ENTRIES
                # create the color entries for all geoemtries
                # available for the heavyAtom
                for key, value in heavyAtom.colors.items():
                    atom.colors[key] = (0.0, 1.0, 1.0)
                    atom.opacities[key] = 1.0

        mol.allAtoms = mol.chains.residues.atoms
        if self.renumber:
            mol.allAtoms.number = range(1, len(mol.allAtoms) + 1)
        return len(molNewHs)
    def add_oxt(self, catom):
        if catom.element != 'C':
            return
        mol = catom.top
        ##check for bonds
        #if len(mol.allAtoms.bonds[0])==0:
        #    mol.buildBondsByDistance()
        #check whether residue already has OXT
        res = catom.parent
        if 'OXT' in res.atoms.name:
            print('not adding OXT to ', res.full_name(), '\n',
                  'it already has an OXT atom')
            return
        #check whether catom has a hydrogen to delete
        hatoms = catom.parent.atoms.get(lambda x: x.name == 'HC')
        if len(hatoms):
            hatom = hatoms[0]
            #check for hbonds
            if hasattr(hatom, 'hbonds'):
                #remove hbonds
                for b in hatom.hbonds:
                    atList = [b.donAt, b.accAt]
                    if b.hAt is not None:
                        atList.append(b.hAt)
                    for at in atList:
                        #hbonds might already be gone
                        if not hasattr(at, 'hbonds'):
                            continue
                        okhbnds = []
                        for hb in at.hbonds:
                            if hb != b:
                                okhbnds.append(hb)
                        if len(okhbnds):
                            at.hbonds = okhbnds
                        else:
                            delattr(at, 'hbonds')
            #remove covalent bonds
            for b in hatom.bonds:
                at2 = b.atom1
                if at2 == hatom: at2 = b.atom2
                at2.bonds.remove(b)
            hatom.parent.remove(hatom, cleanup=1)

        #have to type atoms before call to add_sp2_hydrogen:
        if not hasattr(catom, 'babel_type'):
            print('catom has no babel_type: calling typeAtoms')
            #self.warningMsg(msg)
            #typeAtoms does whole molecule
            babel = AtomHybridization()
            babel.assignHybridization(mol.allAtoms)

        #NB: bond_length 1.28 measured from OXT-C bond in 1crn
        tup1 = self.addh.add_sp2_hydrogen(catom, 1.28)
        res = catom.parent

        # find where to insert H atom
        childIndex = res.children.index(catom) + 1
        name = 'OXT'

        # create the OXT atom object
        atom = Atom(name,
                    res,
                    top=mol,
                    childIndex=childIndex,
                    assignUniqIndex=0)

        # set atoms attributes
        atom._coords = [tup1[0][0]]
        if hasattr(catom, 'segID'): atom.segID = catom.segID
        atom.hetatm = 0
        atom.alternate = []
        atom.element = 'O'
        atom.occupancy = 1.0
        atom.conformation = 0
        atom.temperatureFactor = 0.0
        atom.babel_atomic_number = 8
        atom.babel_type = 'O-'
        atom.babel_organic = 1

        # create the Bond object bonding Hatom to heavyAtom
        bond = Bond(catom, atom, bondOrder=2)

        # create the color entries for all geometries
        # available for the other oxygen atom attached to 'C'
        oatom = res.atoms.get(lambda x: x.name == 'O')[0]
        if oatom is not None:
            for key, value in list(oatom.colors.items()):
                atom.colors[key] = value
                #atom.opacities[key] = oatom.opacities[key]

                # update the allAtoms set in the molecule
        mol.allAtoms = mol.chains.residues.atoms

        # update numbers of allAtoms
        fst = mol.allAtoms[0].number
        mol.allAtoms.number = list(range(fst, len(mol.allAtoms) + fst))

        # update _uniqIndex of this residues atoms
        res.assignUniqIndex()
        #return AtomSet([atom])
        return atom
Esempio n. 18
0
def arrange_hydrogens(inputfile, outputfile, path=None):

    if path and path not in sys.path:
        sys.path.append(path)

    from MolKit import Read
    from PyBabel.atomTypes import AtomHybridization

    from babel import ArrangeHydrogens

    mol = Read(inputfile)
    base, ext = os.path.splitext(inputfile)

    # remove hydrogens from structure
    inputfile_noH = base + '_noH' + ext
    subprocess.check_output('babel -imol2 %s -omol2 %s -d &>/dev/null' %
                            (inputfile, inputfile_noH),
                            shell=True,
                            executable='/bin/bash')
    molnoH = Read(inputfile_noH)

    allAtoms = mol.allAtoms
    allAtomsNoH = molnoH.allAtoms

    babel = AtomHybridization()

    babel.assignHybridization(allAtoms)
    babel.assignHybridization(allAtomsNoH)

    # get mol2 ids of all atoms and all hydrogens
    ff = Reader(inputfile)
    struct = ff.next()
    hat_mol2_ids = []
    at_mol2_ids = []
    for line in struct['ATOM']:
        atom_name = line[5]
        #print line[2]
        if atom_name[0] in ['H', 'h']:
            hat_mol2_ids.append(line[0])
        at_mol2_ids.append(line[0])

    hat_mol2_ids = map(int, hat_mol2_ids)
    at_mol2_ids = map(int, at_mol2_ids)

    # find out the heavy atom each hydrogen is bound with
    at_with_hat_mol2_ids = []
    for id in hat_mol2_ids:
        for line in struct['BOND']:
            line_s = line.split()
            origin_atom_id = int(line_s[1])
            target_atom_id = int(line_s[2])
            #print origin_atom_id
            if id == origin_atom_id:
                at_with_hat_mol2_ids.append(target_atom_id)
            elif id == target_atom_id:
                at_with_hat_mol2_ids.append(origin_atom_id)

    if len(at_with_hat_mol2_ids) != len(hat_mol2_ids):
        raise ValueError(
            "Each hydrogen should have only one bound! Check you .mol2 file")

    addh = ArrangeHydrogens()
    # at_with_hat_idxs are the indices of atoms related to each hydrogen of hat
    hat, at_with_hat_idxs = addh.addHydrogens(allAtoms, allAtomsNoH)

    hat_coords = []
    hat_done_mol2_ids = []
    for idx, at_with_hat_idx in enumerate(at_with_hat_idxs):
        at_with_hat_mol2_id = at_mol2_ids[at_with_hat_idx]
        hat_mol2_ids_cur = [hat_mol2_ids[jdx] for jdx, id in enumerate(at_with_hat_mol2_ids) \
            if id == at_with_hat_mol2_id]
        kdx = 0
        while hat_mol2_ids_cur[kdx] in hat_done_mol2_ids:
            kdx += 1
        hat_done_mol2_ids.append(hat_mol2_ids_cur[kdx])
        hat_coords.append(hat[idx][0])

    for line in struct['ATOM']:
        id = int(line[0])
        if id in hat_done_mol2_ids:
            idx = hat_done_mol2_ids.index(id)
            line[2:5] = ["%.4f" % coords for coords in hat_coords[idx]]

    Writer().write(outputfile, struct)
    os.remove(inputfile_noH)
        raise msg
    if len(resPSet) > 1:
        msg = resP.name + " specifies more than one residue:" + resP.full_name(
        )
        raise msg
    resP = resPSet[0]
    if verbose:
        print "receptor residue is %s which has %d atoms" % (resP.full_name(),
                                                             len(resP.atoms))

    #initialize the ligand
    lM = Read(ligand_filename)[0]
    if verbose: print 'read ', ligand_filename
    lM.buildBondsByDistance()  # try to assign bond order;set to 1 if exception
    #lM.allAtoms.bonds[0].bondOrder = 1   #@@@@@@@@CHECK THIS!!!!@@@@@@@@@
    ah = AtomHybridization()
    ah.assignHybridization(lM.allAtoms)

    #process the ligand:
    #(1)locate specified atom1, atom2 and atom3  SD-CG-CB
    #NB: it is assumed that atom3 has exactly 2 bonds
    at_names = atom1_atom2_atom3.split('_')
    assert len(at_names) == 3
    at1Set = lM.allAtoms.get(at_names[0])
    if not len(at1Set):
        msg = at_names[0] + " is not in " + ligand_filename
        raise msg
    at1 = at1Set[0]  #SD, closest to ligand, farthest from receptor
    if verbose:
        print "first ligand atom to superimpose is %s" % (at1.full_name())
    at2Set = lM.allAtoms.get(at_names[1])
    resPSet = rM.chains.residues.get(res_in_receptor)
    if not len(resPSet):
        msg= resP.name + " is not a residue in " + receptor_filename
        raise msg
    if len(resPSet)>1:
        msg= resP.name + " specifies more than one residue:" + resP.full_name()
        raise msg
    resP = resPSet[0]
    if verbose: print "receptor residue is %s which has %d atoms" %(resP.full_name(), len(resP.atoms))

    #initialize the ligand
    lM = Read(ligand_filename)[0]
    if verbose: print 'read ', ligand_filename
    lM.buildBondsByDistance()            # try to assign bond order;set to 1 if exception
    #lM.allAtoms.bonds[0].bondOrder = 1   #@@@@@@@@CHECK THIS!!!!@@@@@@@@@
    ah = AtomHybridization()
    ah.assignHybridization(lM.allAtoms)

    #process the ligand:
    #(1)locate specified atom1, atom2 and atom3  SD-CG-CB
    #NB: it is assumed that atom3 has exactly 2 bonds
    at_names = atom1_atom2_atom3.split('_')
    assert len(at_names)==3
    at1Set = lM.allAtoms.get(at_names[0])
    if not len(at1Set):
        msg= at_names[0] + " is not in " + ligand_filename
        raise msg
    at1 = at1Set[0] #SD, closest to ligand, farthest from receptor
    if verbose: print "first ligand atom to superimpose is %s" %(at1.full_name())
    at2Set = lM.allAtoms.get(at_names[1])
    if not len(at2Set):
Esempio n. 21
0
 def setAutoDockElements(self,
                         mol,
                         typeAtoms=0,
                         reassign=False,
                         splitAcceptors=False):
     if os.path.splitext(
             mol.parser.filename)[-1] == '.pdbqt' and reassign is False:
         if self.verbose:
             print 'setAutoDockElements unnecessary:\n', mol.name, ' already has AD4 atomtypes: not reassigned!'
         return
     #check that the types have already been set, first
     if self.set_aromatic_carbons:
         #this sets the autodock_element for the planar cyclic carbons to 'A'
         aromatic_carbons = self.acm.setAromaticCarbons(mol)
     d = {}
     ah = AtomHybridization()
     if not len(mol.allAtoms.bonds[0]):
         mol.buildBondsByDistance()
     ats_with_babel_type = filter(lambda x: hasattr(x, 'babel_type'),
                                  mol.allAtoms)
     if typeAtoms or len(ats_with_babel_type) != len(mol.allAtoms):
         if self.verbose:
             print "assigning babel_types"
         ah = AtomHybridization()
         ah.assignHybridization(mol.allAtoms)
     for item in mol.allAtoms:
         if not hasattr(item, 'autodock_element'):
             #item.element = item.element.upper()
             item.autodock_element = item.element
         if item.element == 'H':
             if len(item.bonds):
                 n = item.bonds[0].neighborAtom(item)
                 if n.element not in ['C', 'A']:
                     item.autodock_element = 'HD'
             else:
                 #note: if there are no bonds, assume HD
                 item.autodock_element = 'HD'
         elif item.element == 'N':
             #this has already been done at beginning of for loop
             #if item.babel_type in ['N3+','Ntr', 'Nox']:
             #    item.autodock_element = 'N'
             if item.babel_type in ['N3', 'N2', 'N1']:
                 item.autodock_element = item.element + 'A'
             elif item.babel_type in ['Nam', 'Npl', 'Ng+']:
                 if len(item.bonds) == 2:
                     item.autodock_element = item.element + 'A'
         elif item.element == 'O':
             item.autodock_element = item.element + 'A'
         elif item.element == 'S':
             #possible sulphur babel_types->['S3+','S3','S2','Sac','Sox','S']
             if item.babel_type not in ['Sox', 'Sac']:
                 item.autodock_element = item.element + 'A'
         elif item.element == 'C':
             if item.parent.type + '_' + item.name in self.pep_aromList:
                 item.autodock_element = 'A'
                 if self.renameAtoms:  #
                     if len(item.name) == 1:
                         item.name = 'A'
                     else:
                         item.name = 'A' + item.name[1:]
             elif hasattr(item, 'autodock_element'):
                 item.autodock_element = item.autodock_element
         if splitAcceptors and item.autodock_element in self.acceptorList:
             #if item has a bond to a hydrogen:
             #   change acceptor type 'XA' to 'XB' for 'B'oth 'A'cceptor and 'D'onor
             if 'H' in item.bonds.getAtoms().element:
                 #O->OB;N->NB;S->SB
                 item.autodock_element = item.element + 'B'
         d[item.autodock_element] = 1
     type_list = d.keys()
     type_list.sort()
     mol.types = type_list
    def addHydrogens(self, mol):
        #check for bonds
        if len(mol.allAtoms.bonds[0])==0:
            mol.buildBondsByDistance()
        bonds = mol.allAtoms.bonds[0]
        #could have preset babel_types
        #so check if allAtoms are already typed
        try:
            t = mol.allAtoms.babel_type
        except:
            #if all are not pretyped, type them
            babel = AtomHybridization()
            babel.assignHybridization(mol.allAtoms)

        if self.method=='withBondOrder':
            mol.rings = RingFinder()
            mol.rings.findRings2(mol.allAtoms, mol.allAtoms.bonds[0])
            mol.rings.bondRings = {}
            for ind in xrange(len(mol.rings.rings)):
                r = mol.rings.rings[ind]
                for b in r['bonds']:
                    if not mol.rings.bondRings.has_key(b):
                        mol.rings.bondRings[b] = [ind,]
                    else:
                        mol.rings.bondRings[b].append(ind)
            bo = BondOrder()
            bo.assignBondOrder(mol.allAtoms, bonds, mol.rings)
            mol.allAtoms._bndtyped = 1
            # do aromatic here
            arom = Aromatic(mol.rings)
            arom.find_aromatic_atoms(mol.allAtoms)
            
        hat = AddHydrogens().addHydrogens(mol.allAtoms, method=self.method)
        bondedAtomDict = {}  # key is heavy atom
        for a in hat:
            if bondedAtomDict.has_key(a[1]):
                bondedAtomDict[a[1]].append(a)
            else:
                bondedAtomDict[a[1]] = [a]

        # now create Atom object for hydrogens
        # and add the to the residues's atom list
        molNewHs = AtomSet([]) # list of created H atoms for this molecule
        heavyAtoms = AtomSet([]) # list of atoms that need new radii
        
        for heavyAtom, HatmsDscr in bondedAtomDict.items():
            #don't add hydrogens to carbons: polar Only!!!
            if self.htype!='all' and heavyAtom.element=='C': 
                continue
            res = heavyAtom.parent
            # find where to insert H atom
            childIndex = res.children.index(heavyAtom)+1

            # loop over H atoms description to be added
            # start at the end to number correctly
            l = len(HatmsDscr)
            for i in range(l-1,-1,-1):
                a = HatmsDscr[i]
                # build H atom's name
                if len(heavyAtom.name)==1:
                    name = 'H' + heavyAtom.name
                else:
                    name = 'H' + heavyAtom.name[1:]

                # if more than 1 H atom, add H atom index
                # for instance HD11, HD12, Hd13 (index is 1,2,3)
                if l > 1:
                    name = name + str(i+1)

                # create the H atom object
                atom = Atom(name, res, top=heavyAtom.top,
                            chemicalElement='H',
                            childIndex=childIndex, assignUniqIndex=0)

                # set atoms attributes
                atom._coords = [ a[0] ]
                if hasattr(a[1], 'segID'): atom.segID = a[1].segID
                atom.hetatm = 0
                atom.alternate = []
                #atom.element = 'H'
                atom.occupancy = 1.0
                atom.conformation = 0
                atom.temperatureFactor = 0.0
                atom.babel_atomic_number = a[2]
                atom.babel_type = a[3]
                atom.babel_organic = 1
                atom.radius = 1.2
                
                # create the Bond object bonding Hatom to heavyAtom
                bond = Bond( a[1], atom, bondOrder=1)

                # add the created atom the the list
                molNewHs.append(atom)
                # in case this new hydrogen atom ever ends up in pmv 
                # HAVE TO CREATE THESE ENTRIES 
                # create the color entries for all geoemtries
                # available for the heavyAtom
                for key, value in heavyAtom.colors.items():
                    atom.colors[key]=(0.0, 1.0, 1.0)
                    atom.opacities[key]=1.0

        mol.allAtoms = mol.chains.residues.atoms
        if self.renumber:
            mol.allAtoms.number = range(1, len(mol.allAtoms)+1)
        return len(molNewHs)
Esempio n. 23
0
def getHBAtoms(mol):
    """
    Function to identify donor and acceptor atoms for hydrogen bonds

    d2, d3, a2, a3 <- getHBAtoms(mol)

    The function will first build bonds then assign atom hybridization
    and bond orders. Next it will use a HydrogenBondBuilder to identify and'
    report donor and acceptor atoms in sets corresponding to Sp2 and Sp3
    hybridization.
    A .hbstatus is added to all atoms. The value can be:
      NE: NEutral
      D2: Sp2 donor 
      D3: Sp3 donor 
      A2: Sp2 acceptor
      A3: Sp3 acceptor
      B2: Sp2 acceptor and donor
      B3: Sp3 acceptor and donor
    """
    # add bonds
    mol.buildBondsByDistance()
    atoms = mol.allAtoms

    # assign .babel_type
    from PyBabel.atomTypes import AtomHybridization
    atyper = AtomHybridization()
    atyper.assignHybridization(atoms)

    # assign bond order
    from PyBabel.bo import BondOrder
    bond_orderer = BondOrder()
    bond_orderer.assignBondOrder(atoms, atoms.bonds[0])

    # get donors

    hbbuilder = HydrogenBondBuilder()
    donorTypes = hbbuilder.paramDict['donorTypes']
    donorsp2Ats, donorsp3Ats = hbbuilder.getHBDonors(atoms, donorTypes)

    # get acceptors
    acceptorTypes = hbbuilder.paramDict['acceptorTypes']
    acceptorsp2Ats, acceptorsp3Ats = hbbuilder.getHBAcceptors(
        atoms, acceptorTypes)
    # create hbstatus attribute
    atoms.hbstatus = 'NE'
    for a in donorsp2Ats:
        a.hbstatus = 'D2'
    for a in donorsp3Ats:
        a.hbstatus = 'D3'
    for a in acceptorsp2Ats:
        a.hbstatus = 'A2'
    for a in acceptorsp3Ats:
        a.hbstatus = 'A3'

    # handle atoms that are both donors and acceptor
    for a in donorsp2Ats.inter(acceptorsp2Ats):
        a.hbstatus = 'B2'
    for a in donorsp3Ats.inter(acceptorsp3Ats):
        a.hbstatus = 'B3'

    return donorsp2Ats, donorsp3Ats, acceptorsp2Ats, acceptorsp3Ats
Esempio n. 24
0
    def add_oxt(self, catom):       
        if catom.element!='C':
            return
        mol = catom.top    
        ##check for bonds 
        #if len(mol.allAtoms.bonds[0])==0:
        #    mol.buildBondsByDistance()
        #check whether residue already has OXT
        res = catom.parent
        if 'OXT' in res.atoms.name:
            print 'not adding OXT to ',res.full_name(),'\n', 'it already has an OXT atom'
            return
        #check whether catom has a hydrogen to delete
        hatoms = catom.parent.atoms.get(lambda x: x.name=='HC')
        if len(hatoms):
            hatom = hatoms[0]
            #check for hbonds
            if hasattr(hatom, 'hbonds'):
                #remove hbonds
                for b in hatom.hbonds:
                    atList = [b.donAt, b.accAt]
                    if b.hAt is not None:
                        atList.append(b.hAt)
                    for at in atList:
                        #hbonds might already be gone
                        if not hasattr(at, 'hbonds'):
                            continue
                        okhbnds = []
                        for hb in at.hbonds:
                            if hb!=b:
                                okhbnds.append(hb)
                        if len(okhbnds):
                            at.hbonds = okhbnds
                        else:
                            delattr(at, 'hbonds')
            #remove covalent bonds                
            for b in hatom.bonds:
                at2 = b.atom1
                if at2 == hatom: at2 = b.atom2
                at2.bonds.remove(b)
            hatom.parent.remove(hatom, cleanup=1)

        #have to type atoms before call to add_sp2_hydrogen:
        if not hasattr(catom,'babel_type'):
            print 'catom has no babel_type: calling typeAtoms'
            #self.warningMsg(msg)
            #typeAtoms does whole molecule
            babel = AtomHybridization()
            babel.assignHybridization(mol.allAtoms)

        #NB: bond_length 1.28 measured from OXT-C bond in 1crn
        tup1 = self.addh.add_sp2_hydrogen(catom, 1.28)
        res = catom.parent

        # find where to insert H atom
        childIndex = res.children.index(catom)+1
        name = 'OXT'

        # create the OXT atom object
        atom = Atom(name, res, top=mol,
                    childIndex=childIndex, assignUniqIndex=0)

        # set atoms attributes
        atom._coords = [ tup1[0][0] ]
        if hasattr(catom, 'segID'): atom.segID = catom.segID
        atom.hetatm = 0
        atom.alternate = []
        atom.element = 'O'
        atom.occupancy = 1.0
        atom.conformation = 0
        atom.temperatureFactor = 0.0
        atom.babel_atomic_number = 8
        atom.babel_type = 'O-'
        atom.babel_organic = 1

        # create the Bond object bonding Hatom to heavyAtom
        bond = Bond( catom, atom, bondOrder=2)

        # create the color entries for all geometries
        # available for the other oxygen atom attached to 'C'
        oatom = res.atoms.get(lambda x: x.name=='O')[0]
        if oatom is not None:
            for key, value in oatom.colors.items():
                atom.colors[key] = value
                #atom.opacities[key] = oatom.opacities[key]
                
                # update the allAtoms set in the molecule
        mol.allAtoms = mol.chains.residues.atoms

        # update numbers of allAtoms
        fst = mol.allAtoms[0].number
        mol.allAtoms.number = range(fst, len(mol.allAtoms)+fst)

        # update _uniqIndex of this residues atoms
        res.assignUniqIndex()
        #return AtomSet([atom])
        return atom