Ejemplo n.º 1
0
    def __init__(self, original_pdb, pqr_file, metals):
        self.ori_pdb = Read(original_pdb)[0]
        self.pqr = Read(pqr_file)[0]
        self.metals = metals
        self.new_pdb = pqr_file.split('.')[0] + '.pdb'

        uniq_list = {} # to avoid redundancy
        if self.metals:
            for met in self.metals:
                ele = met[1][:3].strip().lower()
                if ele not in uniq_list.keys():
                    uniq_list[ele] = met[2]
                else:
                    continue
            met_atoms = self.ori_pdb.allAtoms.get(lambda x: x.element.lower() in uniq_list)
            for atm in met_atoms:
                atm.charge = uniq_list[atm.element.lower()]
                print 'atoms charge', atm.element, uniq_list[atm.element.lower()]
            for met_atm in met_atoms:
                close_atoms = self.pqr.closerThan(met_atm.coords, self.pqr.allAtoms, 2.8)
            for a in close_atoms:
                if a.element == 'H':
                    for b in a.bonds:
                        at2 = b.atom1
                        if at2 == a: at2 = b.atom2
                        at2.bonds.remove(b)
                        a.bonds.remove(b)
                    a.parent.remove(a)
                    del a
                self.pqr.allAtoms = self.pqr.chains.residues.atoms
            self.pqr.allAtoms = self.pqr.chains.residues.atoms + met_atoms
        writer = PdbWriter()
        writer.write(self.new_pdb, self.pqr.allAtoms, records=['ATOM', 'HETATM'])
Ejemplo n.º 2
0
 def set_ligand(self, ligand_filename, center_on_ligand=False):
     self.ligand = Read(ligand_filename)[0]
     if self.ligand == None:
         print 'ERROR reading: ', ligand_filename
         return
     if self.verbose:
         print "read ", self.ligand.name
     ligand_types = self.getTypes(self.ligand)
     self.gpo.set_ligand4(ligand_filename, types=ligand_types)
     #this sets ligand_types, gpo.ligand_stem and gpo.ligand_filename
     if self.verbose:
         print "set gpo.ligand_stem to", self.gpo.ligand_stem
         print "set gpo.ligand_filename to", self.gpo.ligand_filename
         print "set gpo.ligand_types to", self.gpo['ligand_types'][
             'value'].__class__
     #need to get npts
     if self.size_box_to_include_ligand:
         self.getSideLengths(self.ligand)  #sets ligand.center
     #gridcenter IS NOT SET BY THIS!!!
     if center_on_ligand:
         cen = self.ligand.getCenter()
         self.gpo['gridcenter']['value'] =  [round(cen[0],4), round(cen[1],4),\
                                         round(cen[2],4)]
         self.gpo['gridcenterAuto']['value'] = 0
         if self.verbose:
             print "set gridcenter to ", self.gpo['gridcenter']['value']
     #only make the box bigger, do NOT make it smaller
     for ix, val in enumerate(self.gpo['npts']['value']):
         #npts
         if hasattr(self.ligand, 'npts'):
             npts = self.ligand.npts
             if npts[ix] > val:
                 self.gpo['npts']['value'][ix] = npts[ix]
     if self.verbose: print "set npts to ", self.gpo['npts']['value']
def test_simplestride():
    if haveStride:
        from MolKit import Read
        mol = Read("./Data/1crn.pdb")[0]
        mol.secondaryStructureFromStride()
        assert hasattr(mol.chains[0], 'secondarystructureset') and \
               len(mol.chains[0].secondarystructureset)==11
def test_getsecondarystructureChain():
    if haveStride:
        from MolKit import Read
        mol = Read("./Data/fxnohtatm.pdb")[0]
        from MolKit.getsecondarystructure import GetSecondaryStructureFromStride
        ssb = GetSecondaryStructureFromStride(mol)
        mol.secondaryStructure(ssb)
def test_getsecondarystructureChain():
    if haveStride:
        from MolKit import Read
        mol = Read("./Data/fxnohtatm.pdb")[0]
        from MolKit.getsecondarystructure import GetSecondaryStructureFromStride
        ssb = GetSecondaryStructureFromStride(mol)
        mol.secondaryStructure(ssb)
Ejemplo n.º 6
0
 def test_Write_6(self):
     
     if not haveStride: return
     from MolKit import Read
     self.mol = Read("Data/1crn.pdb")[0]
     self.mol.secondaryStructureFromStride()
     from MolKit.pdbWriter import PdbWriter
     writer = PdbWriter()
     writer.write('Data/1crn_writer.pdb', self.mol,
                  records=['ATOM', 'HETATM', 'CONECT',
                           'TURN','HELIX', 'SHEET'],
                  bondOrigin='all', ssOrigin='Stride')
     # Make sure that the ss information has been written out
     # properly.
     nmol = Read("Data/1crn_writer.pdb")[0]
     nmol.secondaryStructureFromFile()
     nsset = nmol.chains[0].secondarystructureset
     osset = self.mol.chains[0].secondarystructureset
     self.assertEqual(len(nsset), len(osset))
     for nss, oss in map(None, nsset, osset):
         self.assertEqual(nss.name, oss.name)
         self.assertEqual(nss.start.name,oss.start.name)
         self.assertEqual(nss.end.name, oss.end.name)
         self.assertEqual(len(nss.residues), len(oss.residues))
     os.system("rm Data/1crn_writer.pdb")
 def set_types_from_directory(self, directory):
     if self.verbose: 
         print "reading directory ", directory
     filelist = glob.glob(directory + "/*.pdb*")
     if self.verbose: 
         print "len(filelist)=", len(filelist)
     ad4_typer = AutoDock4_AtomTyper()
     type_dict = {}
     for f in filelist:
         m = Read(f)[0]
         m.buildBondsByDistance()
         ad4_typer.setAutoDockElements(m)
         for a in m.allAtoms:
             type_dict[a.autodock_element] = 1
         self.getSideLengths(m) #sets ligand.center
         npts = m.npts
         #only make the box bigger, do NOT make it smaller
         for ix, val in enumerate(self.gpo['npts']['value']):
             if npts[ix]>val:
                 self.gpo['npts']['value'][ix] =  npts[ix]
                 if self.verbose: 
                     print m.name, " increased grid dimension ", ix, " to ", npts[ix]
     d_types = type_dict.keys()
     if self.verbose: 
         print "found ", d_types, " atom types in directory ", directory
     self.gpo['ligand_types']['value'] =  string.join(d_types)
     if self.verbose: 
         print "now ligand_types is ", self.gpo['ligand_types']['value']
def test_simplestride():
    if haveStride:
        from MolKit import Read
        mol = Read("./Data/1crn.pdb")[0]
        mol.secondaryStructureFromStride()
        assert hasattr(mol.chains[0], 'secondarystructureset') and \
               len(mol.chains[0].secondarystructureset)==11
Ejemplo n.º 9
0
    def __init__(self, original_pdb, pqr_file, metal):
        self.ori_pdb = Read(original_pdb)[0]
        self.pqr = Read(pqr_file)[0]
        self.metal = metal
        self.new_pdb = pqr_file.split('.')[0] + '.pdb'

        if self.metal:
            zn = self.ori_pdb.allAtoms.get(lambda x: x.element == 'Zn')
            # remove hydrogens added to HYS residues near ZN atoms
            close_atoms = self.pqr.closerThan(zn[0].coords, self.pqr.allAtoms,
                                              2.3)
            # FIXME: only take the first atoms in list
            for a in close_atoms:
                if a.element == 'H':
                    # print a.name
                    for b in a.bonds:
                        at2 = b.atom1
                        if at2 == a: at2 = b.atom2
                        at2.bonds.remove(b)
                        a.bonds.remove(b)
                    a.parent.remove(a)
                    del a
            self.pqr.allAtoms = self.pqr.chains.residues.atoms + zn
        writer = PdbWriter()
        writer.write(self.new_pdb,
                     self.pqr.allAtoms,
                     records=['ATOM', 'HETATM'])
Ejemplo n.º 10
0
 def set_types_from_directory(self, directory):
     if self.verbose:
         print "reading directory ", directory
     filelist = glob.glob(directory + "/*.pdb*")
     if self.verbose:
         print "len(filelist)=", len(filelist)
     ad4_typer = AutoDock4_AtomTyper()
     type_dict = {}
     for f in filelist:
         m = Read(f)[0]
         m.buildBondsByDistance()
         ad4_typer.setAutoDockElements(m)
         for a in m.allAtoms:
             type_dict[a.autodock_element] = 1
         self.getSideLengths(m)  #sets ligand.center
         npts = m.npts
         #only make the box bigger, do NOT make it smaller
         for ix, val in enumerate(self.gpo['npts']['value']):
             if npts[ix] > val:
                 self.gpo['npts']['value'][ix] = npts[ix]
                 if self.verbose:
                     print m.name, " increased grid dimension ", ix, " to ", npts[
                         ix]
     d_types = type_dict.keys()
     if self.verbose:
         print "found ", d_types, " atom types in directory ", directory
     self.gpo['ligand_types']['value'] = string.join(d_types)
     if self.verbose:
         print "now ligand_types is ", self.gpo['ligand_types']['value']
Ejemplo n.º 11
0
 def setUp(self):
     self.mols1 = Read('Data/stringSel.pdb')
     self.mol1 = self.mols1[0]
     self.mols2 = Read('Data/protease.pdb')
     self.mol2 = self.mols2[0]
     self.mols = self.mols1 + self.mols2
     self.stringSel = StringSelector()
Ejemplo n.º 12
0
def test_buildBondsByDistance_1():
    """
    Test the buildBondsByDistance for 1crn.pdb with one chain
    
    """
    from MolKit import Read
    mol = Read('Data/1crn.pdb')[0]
    mol.buildBondsByDistance()
    bonds, nobonds = mol.allAtoms.bonds[0], mol.allAtoms.bonds[1]
    assert len(bonds) == 337 and len(nobonds) == 0
Ejemplo n.º 13
0
 def initMolecules(self):
     global molecules, molecules2
     from MolKit import Read
     if molecules is None:
         molecules = Read('Data/stringSel.pdb')
     if molecules2 is None:
         molecules2 = Read('Data/protease.pdb')
     self.mols1 = molecules
     self.mols2 = molecules2
     self.mols = molecules + molecules2
Ejemplo n.º 14
0
def test_parseTERRecord():
    from MolKit import Read

    # Protein with TER records specifying chain A and ChainB
    print "Testing 1bsr: protein with normal TER records"
    mol = Read("./Data/1bsr.pdb")[0]
    assert len(mol.chains) == 2
    assert mol.chains.name == ['A', 'B']
    print mol.chains.name

    # Protein with TER records specifying, 1- several chains and 2-
    # Gaps in chain E.
    # If chain ID is the same on each side of a TER records
    # this doesn't create a new chain but a gap information.
    #    print "Testing 1ACB.pdb: protein with TER specifying GAPS in chain E"
    #    mol = Read("./Data/1ACB.pdb")[0]
    #    assert len(mol.chains)==3, "Expecting 3 chains got %s"%len(mol.chains)
    #    assert mol.chains.gaps == [[('LEU13', 'ILE16'),('TYR146', 'ALA149')], [], []],"Expecting two gaps ('LEU13', 'ILE16'), ('TYR146', 'ALA149') in first chain and got %s"%mol.chains.gaps
    #    print mol.chains.name
    #    print mol.chains.gaps

    # Protein with incorrect TER record...Only TER record no information
    # on the chain ID.
    # TER record doesn't have the right information
    print "Testing ind.pdb: protein with INCORRECT TER record"
    mol = Read("./Data/ind.pdb")[0]
    assert len(mol.chains) == 1, "Expecting 1 chain I got %s %s" % (len(
        mol.chains), mol.chains.name)
    print mol.chains.name

    # Protein with No TER records at all and 1 chain
    print "Testing 1crn_Hs.pdbq: protein with no TER Record and 1 chain"
    mol = Read("Data/1crn_Hs.pdbq")[0]
    assert len(mol.chains) == 1, "Expecting 1 chain got %s" % len(mol.chains)
    assert mol.chains[
        0].name == " ", "Expecting chain name ' ', got %s" % mol.chains[0].name
    print mol.chains.name

    # Protein with 1 TER records and 2 chains A and B
    print "Testing 1crn2Chains.pdb: protein with only 1 TER record and 2 chains"
    mol = Read("Data/1crn2Chains.pdb")[0]
    assert len(mol.chains) == 2, "Expecting 1 chain got %s" % len(mol.chains)
    assert mol.chains.name == [
        'A', 'B'
    ], "Expecting chain name ' ', got %s" % mol.chains.name
    print mol.chains.name

    # Protein with No TER records at all and 2 chains
    print "Testing 1crn2Chains.pdb: protein with only 1 TER record at the end of the ATOM"
    mol = Read("Data/1crn2ChainsNOTER.pdb")[0]
    assert len(mol.chains) == 2, "Expecting 1 chain got %s" % len(mol.chains)
    assert mol.chains.name == [
        'A', 'B'
    ], "Expecting chain name ' ', got %s" % mol.chains.name
    print mol.chains.name
Ejemplo n.º 15
0
def test_merge():
    # merge mol2 into mol1.
    from MolKit import Read
    mol1 = Read("./Data/protease.pdb")[0]
    mol2 = Read("./Data/indinavir.pdb")[0]
    from MolKit.protein import ProteinSet
    pset = ProteinSet([mol1, mol2])
    chains = pset.chains[:]
    mol1.merge(mol2)
    mol1.chains.sort()
    chains.sort()
    assert mol1.chains == chains
Ejemplo n.º 16
0
def test_merge():
    # merge mol2 into mol1.
    from MolKit import Read
    mol1 = Read("./Data/protease.pdb")[0]
    mol2 = Read("./Data/indinavir.pdb")[0]
    from MolKit.protein import ProteinSet
    pset = ProteinSet([mol1,mol2])
    chains = pset.chains[:]
    mol1.merge(mol2)
    mol1.chains.sort()
    chains.sort()
    assert mol1.chains == chains
Ejemplo n.º 17
0
def autodock_scoring(receptor, ligand):
    receptorfilename = receptor
    ligandfilename = ligand
    write_file_mode = False
    parameter_library_filename = None
    exclude_torsFreeEnergy = False
    verbose = None
    ad_scorer = AutoDock41Scorer(exclude_torsFreeEnergy=exclude_torsFreeEnergy)
    supported_types = ad_scorer.supported_types
    receptor = Read(receptorfilename)[0]
    receptor.buildBondsByDistance()
    ligand = Read(ligandfilename)[0]
    ligand.buildBondsByDistance()

    ms = MolecularSystem()
    ms.add_entities(receptor.allAtoms)
    ms.add_entities(ligand.allAtoms)
    ad_scorer.set_molecular_system(ms)
    #get the scores, score per term:
    [estat, hb, vdw, dsolv] = ad_scorer.get_score_per_term()
    torsEnrg = ligand.TORSDOF * ad_scorer.tors_weight
    score = estat + hb + vdw + dsolv + torsEnrg
    output_score = {
        'score': score,
        'estat': estat,
        'hb': hb,
        'vdw': vdw,
        'dsolv,': dsolv,
        'torsEnrg': torsEnrg
    }

    return output_score
Ejemplo n.º 18
0
def get_best_energy_info(d, rms_tolerance, build_hydrogen_bonds=False, \
                                report_energy_breakdown=False,
                                report_unbound_energy=False,
                                receptor_filename=None, refCoords=None,
                                subtract_internal_energy=False):
    global be
    ostr = ""
    clust0 = d.clusterer.clustering_dict[rms_tolerance][0]
    c = clust0[0]
    #find the filename of the best result
    dlo_filename = get_filename(d, c)
    if verbose: print("set dlo_filename to ", dlo_filename)
    ostr = dlo_filename + ", "
    be = c.binding_energy
    if subtract_internal_energy:
        be = c.binding_energy - c.total_internal
    if refCoords:
        ostr += "%3d,%3d,%3d,% 8.4f,% 8.4f," % (len(
            d.clusterer.data), num_clusters, len(clust0), be,
                                                c.getRMSD(refCoords=refCoords))
        #ostr += "%3d,%3d,%3d,% 8.4f,% 8.4f," %(len(d.clusterer.data), num_clusters, len(clust0),  c.binding_energy, c.getRMSD(refCoords=refCoords))
    else:
        ostr += "%3d,%3d,%3d,% 8.4f,% 8.4f," % (len(
            d.clusterer.data), num_clusters, len(clust0), be, c.getRMSD())
        #ostr += "%3d,%3d,%3d,% 8.4f,% 8.4f," %(len(d.clusterer.data), num_clusters, len(clust0),  c.binding_energy, c.getRMSD())
    d.ch.set_conformation(c)
    receptor = None
    if build_hydrogen_bonds:
        if not receptor_filename:
            print(
                "receptor_filename must be specified in order to build_hydrogen_bonds"
            )
            return
        receptor = Read(receptor_filename)[0]
        receptor.buildBondsByDistance()
        d.ligMol.buildBondsByDistance()
        ostr += construct_hydrogen_bonds(receptor.allAtoms,
                                         d.ligMol.allAtoms,
                                         verbose=verbose)
    if report_energy_breakdown:
        if not receptor_filename:
            print(
                "receptor_filename must be specified in order to build_hydrogen_bonds"
            )
        if not receptor:
            receptor = Read(receptor_filename)[0]
            receptor.buildBondsByDistance()
        #build bonds if necessary
        d.ligMol.buildBondsByDistance()
        #ostr += get_energy_breakdown(receptor.allAtoms, d.ligMol.allAtoms, c)
        ostr += get_energy_breakdown(receptor.allAtoms, d.ligMol.allAtoms,
                                     c.getCoords()[:])
    if report_unbound_energy:
        if c.unbound_energy is not None:
            ostr += ",% 8.4f" % c.unbound_energy
        else:
            if verbose: print("conformation's unbound energy is None!")
            ostr += ", 0.0"
    return ostr
Ejemplo n.º 19
0
 def set_ligand(self, ligand_filename):
     self.ligand_filename = os.path.basename(ligand_filename)
     if verbose:
         print "set ligand_filename to", self.ligand_filename
     self.dpo.set_ligand(ligand_filename)
     #expect a filename like ind.out.pdbq: get 'ind' from it
     self.ligand_stem = string.split(self.ligand_filename, '.')[0]
     if verbose: print "set ligand_stem to", self.ligand_stem
     self.ligand = Read(ligand_filename)[0]
     if self.ligand == None:
         print 'ERROR reading: ', ligand_filename
         return
     if verbose:
         print "read ", self.ligand.name
     #set dpo:
     #move
     self.dpo['move']['value'] = self.ligand_filename
     if verbose: print "set move to ", self.dpo['move']['value']
     #ndihe
     #assumes ligand has torTree
     self.dpo['ndihe']['value'] = self.ligand.parser.keys.count("BRANCH")
     #self.dpo['ndihe']['value'] = len(self.ligand.torTree.torsionMap)
     if verbose: print "set ndihe to ", self.dpo['ndihe']['value']
     #torsdof
     #caution dpo['torsdof']['value'] is a list [ndihe, 0.3113]
     self.dpo['torsdof']['value'][0] = self.ligand.TORSDOF
     if verbose: print "set torsdof to ", self.dpo['torsdof']['value']
     #types
     d = {}
     for a in self.ligand.allAtoms:
         d[a.autodock_element] = 1
     sortKeyList = [
         'C', 'A', 'N', 'O', 'S', 'H', 'P', 'n', 'f', 'F', 'c', 'b', 'I',
         'M'
     ]
     lig_types = ""
     for t in sortKeyList:
         if t in d.keys():
             lig_types = lig_types + t
     self.ligand.types = lig_types
     self.dpo['types']['value'] = self.ligand.types
     if verbose: print "set types to ", self.dpo['types']['value']
     #about
     self.ligand.getCenter()
     cen = self.ligand.center
     self.dpo['about']['value'] =  [round(cen[0],4), round(cen[1],4),\
                                     round(cen[2],4)]
     if verbose: print "set about to ", self.dpo['about']['value']
Ejemplo n.º 20
0
def test_findType():
    from MolKit import Read

    mol = Read("./Data/1crn.pdb")[0]
    from MolKit.protein import Residue, Chain, Protein, ResidueSet
    from MolKit.molecule import Atom, AtomSet

    # FindType below from top of the tree
    res = mol.findType(Residue)
    res.sort()
    molres = mol.chains.residues
    molres.sort()
    assert res == molres

    # FindType above from bottom of the tree
    atms = mol.allAtoms
    chains = atms.findType(Chain)
    # Automatically does a uniq when going above
    assert len(chains) == 327

    # FindType above uniq from bottom of the tree
    chainsuniq = atms.findType(Chain, uniq=1)
    assert len(chainsuniq) == 1

    # FindType above from middle of the tree
    prot = res.findType(Protein, uniq=1)
    assert len(prot) == 1 and prot == mol.setClass([mol])

    # FindType below from middle of the tree
    atoms = chainsuniq.findType(Atom)
    assert len(atoms) == 327

    # FindType on empty set
    emptyres = ResidueSet([])
    atoms = emptyres.findType(Atom)
    assert len(atoms) == 0 and isinstance(atoms, AtomSet)

    # FindType on same type
    atoms = atms.findType(Atom)
    assert atoms == atms

    # Raise exception
    from MolKit.protein import Helix

    try:
        nodes = atms.findType(Helix)
    except RuntimeError:
        print "passed"
 def set_ligand(self, ligand_filename, center_on_ligand=False): 
     self.ligand = Read(ligand_filename)[0]
     if self.ligand==None:
         print 'ERROR reading: ', ligand_filename
         return 
     if self.verbose: 
         print "read ", self.ligand.name
     ligand_types = self.getTypes(self.ligand)
     self.gpo.set_ligand4(ligand_filename, types=ligand_types)
     #this sets ligand_types, gpo.ligand_stem and gpo.ligand_filename
     if self.verbose: 
         print "set gpo.ligand_stem to", self.gpo.ligand_stem
         print "set gpo.ligand_filename to", self.gpo.ligand_filename
         print "set gpo.ligand_types to", self.gpo['ligand_types']['value'].__class__
     #need to get npts
     if self.size_box_to_include_ligand:
         self.getSideLengths(self.ligand) #sets ligand.center
     #gridcenter IS NOT SET BY THIS!!!
     if center_on_ligand:
         cen = self.ligand.getCenter()
         self.gpo['gridcenter']['value'] =  [round(cen[0],4), round(cen[1],4),\
                                         round(cen[2],4)]
         self.gpo['gridcenterAuto']['value'] =  0
         if self.verbose: print "set gridcenter to ", self.gpo['gridcenter']['value']
     #only make the box bigger, do NOT make it smaller
     for ix, val in enumerate(self.gpo['npts']['value']):
         #npts
         if hasattr(self.ligand, 'npts'):
             npts = self.ligand.npts
             if npts[ix]>val:
                 self.gpo['npts']['value'][ix] =  npts[ix]
     if self.verbose: print "set npts to ", self.gpo['npts']['value']
Ejemplo n.º 22
0
 def __init__(self, pdb):
     # if not is valid
     self.exception = None
     try:
         self.mol = Read(pdb)[0]
     except Exception as inst:
         self.exception = inst  # the exception instance
     self.het = []
     self.zn_atoms = []
     self.size = None
     self.center = None
     self.selection_center = None
     self.prot = []
     if not self.exception:
         self.get_info()
         self.center = self.mol.getCenter()
Ejemplo n.º 23
0
 def __init__(self, filename):
     self.input_file = Read(filename)[0]
     self.output = filename.split('.')[0] + '.pdb'
     writer = PdbWriter()
     writer.write(self.output,
                  self.input_file.allAtoms,
                  records=['ATOM', 'HETATM'])
Ejemplo n.º 24
0
 def test_Write_2(self):
     """
     Test writing out CONECT records for the bonds described in
     the pdb file and built by distance.
     """
     from MolKit import Read
     self.mol = Read("Data/1crn.pdb")[0]
     self.mol.buildBondsByDistance()
     # instanciate a PdbWriter and call the write method with the
     # default arguments
     from MolKit.pdbWriter import PdbWriter
     writer = PdbWriter()
     writer.write('Data/1crn_writer.pdb', self.mol)
     from MolKit.pdbParser import PdbParser
     nmol = Read("Data/1crn_writer.pdb")[0]
     os.system("rm Data/1crn_writer.pdb")
Ejemplo n.º 25
0
 def set_types_from_directory(self, directory):
     if self.verbose:
         print("reading directory ", directory)
     filelist = glob.glob(directory + "/*.pdb*")
     if self.verbose:
         print("len(filelist)=", len(filelist))
     ad4_typer = AutoDock4_AtomTyper()
     type_dict = {}
     all_types = ""
     for f in filelist:
         ftype = os.path.splitext(f)[-1]
         if ftype != ".pdbqt":
             print("skipping ", f, " not in PDBQT format!")
             continue
         m = Read(f)[0]
         m_types = ""
         m_types = " ".join(list(set(m.allAtoms.autodock_element)))
         self.getSideLengths(m)  # sets ligand.center
         npts = m.npts
         # only make the box bigger, do NOT make it smaller
         for ix, val in enumerate(self.gpo['npts']['value']):
             if npts[ix] > val:
                 self.gpo['npts']['value'][ix] = npts[ix]
                 if self.verbose:
                     print(m.name, " increased grid dimension ", ix, " to ", npts[ix])
         all_types = all_types + m_types
         if self.verbose:
             print("added ", m_types, " atom types in directory ", directory)
     print("end: all_types = ", all_types)
     self.gpo['ligand_types']['value'] = all_types
     if self.verbose:
         print("all ligand_types for ", directory, "= ", self.gpo['ligand_types']['value'])
Ejemplo n.º 26
0
def ligand_preparation(ligand, output):
	ligand_filename =  None
	verbose = None
	add_bonds = False
	repairs = ""
	charges_to_add = 'gasteiger'
	preserve_charge_types=''
	cleanup  = "nphs_lps"
	allowed_bonds = "backbone"
	root = 'auto'
	outputfilename = output
	check_for_fragments = False
	bonds_to_inactivate = ""
	inactivate_all_torsions = False
	attach_nonbonded_fragments = False
	attach_singletons = False
	mode = 'automatic'
	dict = None

	mols = Read(ligand)
	mol = mols[0]
	mol.buildBondsByDistance()
	    
	LPO = AD4LigandPreparation(mol, mode, repairs, charges_to_add, 
			          cleanup, allowed_bonds, root, 
			  	  outputfilename=output,
                                  dict=dict, check_for_fragments=check_for_fragments,
				  bonds_to_inactivate=bonds_to_inactivate, 
				  inactivate_all_torsions=inactivate_all_torsions,
				  attach_nonbonded_fragments=attach_nonbonded_fragments,
				  attach_singletons=attach_singletons)
Ejemplo n.º 27
0
 def __init__(self, receptor_file, percentCutoff=1., detect_pi=False, dist_cutoff=6, verbose=False, 
                     distanceSelector=None, hydrogen_bond_builder=None, distanceSelectorWithCutoff=None,
                     aromatic_cycle_bond_selector=None): 
     self.receptor_file = receptor_file
     receptor = Read(receptor_file)
     assert(len(receptor)==1)
     assert isinstance(receptor, MoleculeSet)
     self.macro = receptor[0]
     self.macro_atoms = self.macro.allAtoms
     self.macro.buildBondsByDistance()
     self.verbose = verbose
     #??useful??
     self.percentCutoff = percentCutoff
     self.detect_pi = detect_pi
     self.distanceSelector = distanceSelector 
     if self.distanceSelector is None:
         self.distanceSelector = CloserThanVDWSelector(return_dist=0)
     self.hydrogen_bond_builder = hydrogen_bond_builder 
     if self.hydrogen_bond_builder is None:
         self.hydrogen_bond_builder = HydrogenBondBuilder()
     self.distanceSelectorWithCutoff = distanceSelectorWithCutoff 
     if self.distanceSelectorWithCutoff is None:
         self.distanceSelectorWithCutoff = DistanceSelector()
     self.dist_cutoff=float(dist_cutoff)
     self.results = d = {}
     self.report_list =['lig_hb_atoms','lig_close_atoms']
     self.aromatic_cycle_bond_selector = aromatic_cycle_bond_selector
     if self.aromatic_cycle_bond_selector is None:
         self.aromatic_cycle_bond_selector = AromaticCycleBondSelector()
     if detect_pi:
         self.report_list.extend(['pi_cation','pi_pi', 'cation_pi', 't_shaped'])
     if self.verbose: print("self.report_list=", self.report_list)
Ejemplo n.º 28
0
def test_parseNMRModel():
    from MolKit import Read
    mols = Read("./Data/2EZNsmall.pdb")
    assert len(mols) == 3, "Expecting 3 NMR models got %s" % len(mols)
    assert mols.chains.id == [
        ' ', ' ', ' '
    ], "Expecting chain id ' ' got %s" % mols.chains.id
Ejemplo n.º 29
0
def get_largest_cluster_info(d, rms_tolerance, build_hydrogen_bonds=False, \
                                    report_energy_breakdown=False,
                                    report_unbound_energy=False,
                                    receptor_filename=None, refCoords=None,
                                    subtract_internal_energy=False):
    global be_lc
    largest = d.clusterer.clustering_dict[rms_tolerance][0]
    if verbose: print "set largest to ", len(largest)
    for clust in d.clusterer.clustering_dict[rms_tolerance]:
        if verbose: print "current largest cluster len= ", len(clust)
        if len(clust) > len(largest):
            if verbose: print "resetting largest clust: now len=", len(clust)
            largest = clust
    c = largest[0]  #print info about the lowest energy member of this cluster
    ostr = " "
    dlo_filename = get_filename(d, c)
    ostr += dlo_filename + ","
    be_lc = c.binding_energy
    if subtract_internal_energy:
        be_lc = c.binding_energy - c.total_internal
    if refCoords:
        ostr += "%3d,%3d,%3d,% 8.4f,% 8.4f," % (len(
            d.clusterer.data), num_clusters, len(largest), be_lc,
                                                c.getRMSD(refCoords=refCoords))
    else:
        ostr += "%3d,%3d,%3d,% 8.4f,% 8.4f," % (len(
            d.clusterer.data), num_clusters, len(largest), be_lc, c.getRMSD())
    if verbose: print "set dlo_filename to ", dlo_filename
    #update the coords only if you need to?
    d.ch.set_conformation(c)
    receptor = None
    if build_hydrogen_bonds:
        if not receptor_filename:
            print "receptor_filename must be specified in order to build_hydrogen_bonds"
            return
        receptor = Read(receptor_filename)[0]
        receptor.buildBondsByDistance()
        ostr += construct_hydrogen_bonds(receptor.allAtoms,
                                         d.ligMol.allAtoms,
                                         verbose=verbose)
    if report_energy_breakdown:
        if not receptor_filename:
            print "receptor_filename must be specified in order to build_hydrogen_bonds"
            return
        if not receptor:
            receptor = Read(receptor_filename)[0]
            receptor.buildBondsByDistance()
        #ostr += get_energy_breakdown(receptor.allAtoms, d.ligMol.allAtoms, c)
        ostr += get_energy_breakdown(receptor.allAtoms, d.ligMol.allAtoms,
                                     c.getCoords()[:])
    if report_unbound_energy:
        if c.unbound_energy is not None:
            ostr += ",% 8.4f" % c.unbound_energy
        else:
            if verbose: print "conformation's unbound energy is None!"
            ostr += ", 0.0"
    return ostr
Ejemplo n.º 30
0
def test_findType():
    from MolKit import Read
    mol = Read("./Data/1crn.pdb")[0]
    from MolKit.protein import Residue, Chain, Protein, ResidueSet
    from MolKit.molecule import Atom, AtomSet
    # FindType below from top of the tree
    res = mol.findType(Residue)
    res.sort()
    molres = mol.chains.residues
    molres.sort()
    assert res == molres

    # FindType above from bottom of the tree
    atms = mol.allAtoms
    chains = atms.findType(Chain)
    # Automatically does a uniq when going above
    assert len(chains) == 327

    # FindType above uniq from bottom of the tree
    chainsuniq = atms.findType(Chain, uniq=1)
    assert len(chainsuniq) == 1

    # FindType above from middle of the tree
    prot = res.findType(Protein, uniq=1)
    assert len(prot) == 1 and prot == mol.setClass([
        mol,
    ])

    # FindType below from middle of the tree
    atoms = chainsuniq.findType(Atom)
    assert len(atoms) == 327

    # FindType on empty set
    emptyres = ResidueSet([])
    atoms = emptyres.findType(Atom)
    assert len(atoms) == 0 and isinstance(atoms, AtomSet)

    # FindType on same type
    atoms = atms.findType(Atom)
    assert atoms == atms

    # Raise exception
    from MolKit.protein import Helix
    try:
        nodes = atms.findType(Helix)
    except RuntimeError:
        print "passed"
Ejemplo n.º 31
0
 def test_3level_select_end_2(self):
     """
      test select with ':$'  returns molecule's last atom
     """
     new_mols = Read("Data/1crn.pdb")
     self.mols +=new_mols
     result, msg = self.stringSel.select(self.mols, ":::$")
     self.assertEquals(result[0], self.mols[-1:].allAtoms[-1])
class BaseTests(unittest.TestCase):
    def setUp(self):
        from MolKit import Read
        self.mol = Read('Data/1crn.pdb')[0]
        self.mol.buildBondsByDistance()
    

    def tearDown(self):
        """
        clean-up
        """
        del(self.mol)


    def test_constructor(self):
        """
        instantiate an HydrogenBuilder
        """
        h_builder = HydrogenBuilder()
        self.assertEquals(h_builder.__class__, HydrogenBuilder)


    def test_constructorOptions(self):
        """
         test possible constructor options
            options = htype, renumber, method
        """
    
        h_builder = HydrogenBuilder(htype='polarOnly')
        self.assertEquals(h_builder.__class__, HydrogenBuilder)
        h_builder = HydrogenBuilder(renumber=0)
        self.assertEquals(h_builder.__class__, HydrogenBuilder)
        h_builder = HydrogenBuilder(method='withBondOrder')
        self.assertEquals(h_builder.__class__, HydrogenBuilder)


    def test_addHydrogens(self):
        """
         test addHydrogens 
        """
        beforeLen = len(self.mol.allAtoms)
        h_builder = HydrogenBuilder()
        h_builder.addHydrogens(self.mol)
        afterLen = len(self.mol.allAtoms)
        #print "beforeLen=", beforeLen, ' afterLen=', afterLen
        self.assertEquals(beforeLen<afterLen, True)
Ejemplo n.º 33
0
 def test_3level_select_end(self):
     """
      test select with '$'  returns last molecule.atoms
     """
     new_mols = Read("Data/1crn.pdb")
     self.mols +=new_mols
     result, msg = self.stringSel.select(self.mols, "$:::")
     self.assertEquals(result, self.mols[-1:].allAtoms)
Ejemplo n.º 34
0
 def set_ligand(self, ligand_filename):
     self.ligand_filename = os.path.basename(ligand_filename)
     if self.verbose:
         print "set ligand_filename to", self.ligand_filename
     self.gpo.set_ligand(ligand_filename)
     #expect a filename like ind.out.pdbq: get 'ind' from it
     self.ligand_stem = string.split(self.ligand_filename, '.')[0]
     if self.verbose: print "set ligand_stem to", self.ligand_stem
     self.ligand = Read(ligand_filename)[0]
     #IS THIS USEFUL???
     self.gpo.ligand = self.ligand
     if self.verbose: print "read ", self.ligand.name
     #set gpo:
     #types
     d = {}
     for a in self.ligand.allAtoms:
         d[a.autodock_element] = 1
     sortKeyList = [
         'C', 'A', 'N', 'O', 'S', 'H', 'P', 'n', 'f', 'F', 'c', 'b', 'I',
         'M'
     ]
     lig_types = ""
     for t in sortKeyList:
         if t in d.keys():
             lig_types = lig_types + t
     self.ligand.types = lig_types
     self.gpo['types']['value'] = self.ligand.types
     if self.verbose: print "set types to ", self.gpo['types']['value']
     #gridcenter
     self.ligand.center = self.ligand.getCenter()
     if self.size_box_to_include_ligand:
         self.getSideLengths(self.ligand)  #sets ligand.center
     cen = self.ligand.center
     self.gpo['gridcenter']['value'] =  [round(cen[0],4), round(cen[1],4),\
                                     round(cen[2],4)]
     self.gpo['gridcenterAuto']['value'] = 0
     if self.verbose:
         print "set gridcenter to ", self.gpo['gridcenter']['value']
     #only make the box bigger from npts, do not make it smaller
     for ix, val in enumerate(self.gpo['npts']['value']):
         if hasattr(self.ligand, 'npts'):
             npts = self.ligand.npts
             if npts[ix] > val:
                 if self.verbose:
                     print "increasing ", ix, " grid dimension to ", val
                 self.gpo['npts']['value'][ix] = npts[ix]
Ejemplo n.º 35
0
 def test_select_end(self):
     """
      test select with '$'  returns last item
     """
     new_mols = Read("Data/1crn.pdb")
     self.mols +=new_mols
     result, msg = self.stringSel.select(self.mols, "$")
     self.assertEquals(result[-1], self.mols[-1])
Ejemplo n.º 36
0
    def test_Write_1(self):
        """
        Test the default option of the write method of a PdbWriter.
        Just write the ATOM, HETATM and CONECT records and bondOrigin
        is File.
        """
        # read a molecule
        from MolKit import Read
        self.mol = Read("Data/1crn.pdb")[0]

        # instanciate a PdbWriter and call the write method with the
        # default arguments
        from MolKit.pdbWriter import PdbWriter
        writer = PdbWriter()
        writer.write('Data/1crn_writer.pdb', self.mol)
        # This should write only the ATOM and CONECT records
        # The TER records are automatically created with the ATOM records

        # 1- Make sure that the file has been created
        import os
        self.failUnless(os.path.exists('Data/1crn_writer.pdb'))
        # 2- Make sure that the file created the proper records
        # Get the default records from the new pdb files
        from MolKit.pdbParser import PdbParser
        nmol = Read("Data/1crn_writer.pdb")[0]

        # COMPARE 
        ncoords = nmol.allAtoms.coords
        ocoords = self.mol.allAtoms.coords
        self.assertEqual(ncoords, ocoords)

        nname = nmol.allAtoms.name
        oname = nmol.allAtoms.name
        self.assertEqual(nname, oname)

        nbonds = nmol.allAtoms.bonds[0]
        obonds = self.mol.allAtoms.bonds[0]
        self.assertEqual(len(nbonds), len(obonds))
        nbatms = nbonds.atom1+nbonds.atom2
        nbatms = nbatms.uniq()
        nbatms.sort()
        
        nbatms = nbonds.atom1+nbonds.atom2
        nbatms = nbatms.uniq()
        nbatms.sort()
        os.system("rm Data/1crn_writer.pdb")
Ejemplo n.º 37
0
def setUpSuite():
    from mslib import msms
    print(("msms imported from: ", msms.__file__))
    newmol = Read("./Data/1crn.pdb")
    allatoms = newmol.chains.residues.atoms
    global coords
    coords = allatoms.coords
    global rad
    rad = newmol[0].defaultRadii(united=1)
class BaseTests(unittest.TestCase):
    def setUp(self):
        from MolKit import Read

        self.mol = Read("Data/2plv_no_oxt.pdb")[0]
        self.mol.buildBondsByDistance()

    def tearDown(self):
        """
        clean-up
        """
        del (self.mol)

    def test_constructor(self):
        """
        instantiate an HydrogenBuilder
        """
        oxt_builder = OxtBuilder()
        self.assertEquals(oxt_builder.__class__, OxtBuilder)

    #    def test_constructorOptions(self):
    #        """
    #         test possible constructor options
    #            options = NONE!!
    #        """
    #
    #        oxt_builder = OxtBuilder(???=???)
    #        self.assertEquals(oxt_builder.__class__, OxtBuilder)

    def test_add_oxt(self):
        """
         test add_oxt 
        """
        beforeLen = len(self.mol.allAtoms)
        oxt_builder = OxtBuilder()
        # the last chain is all waters so skip it
        for ch in self.mol.chains[:-1]:
            catom = ch.residues[-1].atoms[2]
            new_at = oxt_builder.add_oxt(catom)
            # print "added ", new_at.full_name()
        afterLen = len(self.mol.allAtoms)
        # print "beforeLen=", beforeLen, ' afterLen=', afterLen
        self.assertEquals(beforeLen + len(self.mol.chains[:-1]), afterLen)
 def set_ligand4(self, ligand_filename, types=None):
     #this should set ligand_types
     #print "in set_ligand4: types=", types
     if types is None:
         ligand = Read(ligand_filename)[0]
         ligand.buildBondsByDistance()
         ad4_typer = AutoDock4_AtomTyper()
         ad4_typer.setAutoDockElements(ligand)
         dict = {}
         for a in ligand.allAtoms:
             dict[a.autodock_element] = 1
         d_types = dict.keys()
         d_types.sort()
         types = d_types[0]
         for t in d_types[1:]:
             types = types + " " + t
     self['ligand_types']['value'] = types
     #print "set_ligand4: self['ligand_types']['value']=", self['ligand_types']['value']
     self.ligand_filename = os.path.basename(ligand_filename)
     #print "GPO: set ligand_filename to ", self.ligand_filename
     self.ligand_stem = os.path.splitext(self.ligand_filename)[0]
Ejemplo n.º 40
0
class PdbqtWriterAtomLinesTest(PdbWriterTest):

    def setUp(self):
        from MolKit import Read
        self.mol = Read('Data/hsg1.pdbqt')[0]
        self.mol.buildBondsByDistance()
    

    def tearDown(self):
        del(self.mol)


    def test_write(self):
        """
        test writing a pdbqs file
        """
        writer = PdbqtWriter()
        writer.write('test_pdbqtWriter.pdbqt', self.mol, bondOrigin=('File',))
        ans, errors = self.compare('Data/hsg1.pdbqt', 'test_pdbqtWriter.pdbqt') 
        self.assertEquals(errors, None)
        self.assertEquals(ans, True)
def get_best_energy_info(d, rms_tolerance, build_hydrogen_bonds=False, \
                                report_energy_breakdown=False,
                                report_unbound_energy=False,
                                receptor_filename=None):
    ostr = "" 
    clust0 = d.clusterer.clustering_dict[rms_tolerance][0]
    c = clust0[0]
    #find the filename of the best result
    dlo_filename = get_filename(d, c)
    if verbose: print "set dlo_filename to ", dlo_filename
    ostr = dlo_filename + ", "
    ostr += "%3d,%3d,%3d,% 8.4f,% 8.4f," %(len(d.clusterer.data), num_clusters, len(clust0),  c.binding_energy, c.getRMSD())
    d.ch.set_conformation(c)
    receptor = None
    if build_hydrogen_bonds:
        if not receptor_filename:
            print "receptor_filename must be specified in order to build_hydrogen_bonds"
            return 
        receptor = Read(receptor_filename)[0] 
        receptor.buildBondsByDistance()
        ostr += construct_hydrogen_bonds(receptor.allAtoms, d.ligMol.allAtoms)
    if report_energy_breakdown:
        if not receptor_filename:
            print "receptor_filename must be specified in order to build_hydrogen_bonds"
        if not receptor:
            receptor = Read(receptor_filename)[0] 
            receptor.buildBondsByDistance()
        ostr += get_energy_breakdown(receptor.allAtoms, d.ligMol.allAtoms, c)
    if report_unbound_energy:
        if c.unbound_energy is not None: 
            ostr += "% 8.4f," %c.unbound_energy
        else:
            if verbose: print "conformation's unbound energy is None!"
            ostr += "%    0.0," 
    return ostr
Ejemplo n.º 42
0
def autodock_scoring(receptor, ligand):
    receptorfilename =  receptor
    ligandfilename =  ligand
    write_file_mode = False
    parameter_library_filename = None
    exclude_torsFreeEnergy = False
    verbose = None
    ad_scorer = AutoDock41Scorer(exclude_torsFreeEnergy=exclude_torsFreeEnergy)
    supported_types = ad_scorer.supported_types
    receptor = Read(receptorfilename)[0]
    receptor.buildBondsByDistance()
    ligand = Read(ligandfilename)[0]
    ligand.buildBondsByDistance()

    ms = MolecularSystem()
    ms.add_entities(receptor.allAtoms)
    ms.add_entities(ligand.allAtoms)
    ad_scorer.set_molecular_system(ms)
    #get the scores, score per term:
    [estat, hb, vdw ,dsolv] = ad_scorer.get_score_per_term()
    torsEnrg = ligand.TORSDOF * ad_scorer.tors_weight
    score = estat +hb +vdw +dsolv +torsEnrg
    output_score = {'score':score, 'estat':estat, 'hb':hb, 'vdw':vdw, 'dsolv,':dsolv, 'torsEnrg':torsEnrg}
    
    return output_score
 def set_receptor4(self, receptor_filename, types=None):
     #this should set receptor_types
     if types is None:
         receptor = Read(receptor_filename)[0]
         receptor.buildBondsByDistance()
         ad4_typer = AutoDock4_AtomTyper()
         ad4_typer.setAutoDockElements(receptor)
         dict = {}
         for a in receptor.allAtoms:
             dict[a.autodock_element] = 1
         d_types = dict.keys()
         d_types.sort()
         types = d_types[0]
         for t in d_types[1:]:
             types = types + " " + t
     self['receptor_types']['value'] = types
     basename = os.path.basename(receptor_filename)
     self.receptor_filename = basename
     self.receptor_stem = os.path.splitext(basename)[0]
     if receptor_filename!='':
         self['receptor']['value'] = basename
         self['gridfld']['value'] = self.receptor_stem + '.maps.fld'
         self['elecmap']['value'] = self.receptor_stem + '.e.map'
         self['dsolvmap']['value'] = self.receptor_stem + '.d.map'
Ejemplo n.º 44
0
 def set_ligand(self, ligand_filename): 
     self.ligand_filename = os.path.basename(ligand_filename)
     if verbose:
         print "set ligand_filename to", self.ligand_filename
     self.dpo.set_ligand(ligand_filename)
     #expect a filename like ind.out.pdbq: get 'ind' from it
     self.ligand_stem = string.split(self.ligand_filename,'.')[0]
     if verbose: print "set ligand_stem to", self.ligand_stem
     self.ligand = Read(ligand_filename)[0]
     if self.ligand==None:
         print 'ERROR reading: ', ligand_filename
         return 
     if verbose: 
         print "read ", self.ligand.name
     #set dpo:
     #move
     self.dpo['move']['value'] = self.ligand_filename
     if verbose: print "set move to ", self.dpo['move']['value']
     #ndihe
     #assumes ligand has torTree
     self.dpo['ndihe']['value'] = self.ligand.parser.keys.count("BRANCH")
     #self.dpo['ndihe']['value'] = len(self.ligand.torTree.torsionMap)
     if verbose: print "set ndihe to ", self.dpo['ndihe']['value']
     #torsdof
     #caution dpo['torsdof']['value'] is a list [ndihe, 0.3113]
     self.dpo['torsdof']['value'][0] = self.ligand.TORSDOF
     if verbose: print "set torsdof to ", self.dpo['torsdof']['value']
     #types
     d = {}
     for a in self.ligand.allAtoms:
         d[a.autodock_element] = 1
     sortKeyList =  ['C','A','N','O','S','H','P','n','f','F','c','b','I','M']
     lig_types = ""
     for t in sortKeyList:
         if t in d.keys():
             lig_types = lig_types + t
     self.ligand.types = lig_types
     self.dpo['types']['value'] = self.ligand.types
     if verbose: print "set types to ", self.dpo['types']['value']
     #about
     self.ligand.getCenter()
     cen = self.ligand.center
     self.dpo['about']['value'] =  [round(cen[0],4), round(cen[1],4),\
                                     round(cen[2],4)]
     if verbose: print "set about to ", self.dpo['about']['value']
def get_largest_cluster_info(d, rms_tolerance, build_hydrogen_bonds=False, \
                                    report_energy_breakdown=False,
                                    report_unbound_energy=False,
                                    receptor_filename=None, refCoords=None,
                                    subtract_internal_energy=False):
    global be_lc
    largest = d.clusterer.clustering_dict[rms_tolerance][0]
    if verbose: print "set largest to ", len(largest)
    for clust in d.clusterer.clustering_dict[rms_tolerance]:
        if verbose: print "current largest cluster len= ", len(clust)
        if len(clust)>len(largest): 
            if verbose: print "resetting largest clust: now len=", len(clust)
            largest = clust
    c = largest[0]   #print info about the lowest energy member of this cluster
    ostr = " "
    dlo_filename = get_filename(d, c)
    ostr += dlo_filename + ","
    be_lc = c.binding_energy
    if subtract_internal_energy:
        be_lc = c.binding_energy - c.total_internal
    if refCoords:
        ostr += "%3d,%3d,%3d,% 8.4f,% 8.4f," %(len(d.clusterer.data), num_clusters, len(largest),  be_lc, c.getRMSD(refCoords=refCoords))
    else:
        ostr += "%3d,%3d,%3d,% 8.4f,% 8.4f," %(len(d.clusterer.data), num_clusters, len(largest),  be_lc, c.getRMSD())
    if verbose: print "set dlo_filename to ", dlo_filename
    #update the coords only if you need to?
    d.ch.set_conformation(c)
    receptor = None
    if build_hydrogen_bonds:
        if not receptor_filename:
            print "receptor_filename must be specified in order to build_hydrogen_bonds"
            return 
        receptor = Read(receptor_filename)[0] 
        receptor.buildBondsByDistance()
        ostr += construct_hydrogen_bonds(receptor.allAtoms, d.ligMol.allAtoms, verbose=verbose)
    if report_energy_breakdown:
        if not receptor_filename:
            print "receptor_filename must be specified in order to build_hydrogen_bonds"
            return 
        if not receptor:
            receptor = Read(receptor_filename)[0] 
            receptor.buildBondsByDistance()
        #ostr += get_energy_breakdown(receptor.allAtoms, d.ligMol.allAtoms, c)
        ostr += get_energy_breakdown(receptor.allAtoms, d.ligMol.allAtoms, c.getCoords()[:])
    if report_unbound_energy: 
        if c.unbound_energy is not None:
            ostr += ",% 8.4f" %c.unbound_energy
        else:
            if verbose: print "conformation's unbound energy is None!"
            ostr += ", 0.0" 
    return ostr
Ejemplo n.º 46
0
    def test_Write_4(self):
        """
        Test writing out the ATOM records and the CONECT records
        without the HETATM
        """
        from MolKit import Read
        self.mol = Read("Data/1bsr.pdb")[0]
        # instanciate a PdbWriter and call the write method with the
        # default arguments
        from MolKit.pdbWriter import PdbWriter
        writer = PdbWriter()
        writer.write('Data/1bsr_writer.pdb', self.mol,
                     records=['ATOM', 'CONECT'], bondOrigin=('File',))
        nmol = Read("Data/1bsr_writer.pdb")[0]

        nhoh = nmol.chains.residues.get(lambda x: x.type=="HOH")
        ohoh = self.mol.chains.residues.get(lambda x: x.type=="HOH")
        self.failUnless(len(nhoh)==0)
        os.system("rm Data/1bsr_writer.pdb")
def get_largest_cluster_info(
    d, rms_tolerance, build_hydrogen_bonds=False, report_energy_breakdown=False, receptor_filename=None, refCoords=None
):
    largest = d.clusterer.clustering_dict[rms_tolerance][0]
    if verbose:
        print "set largest to ", len(largest)
    for clust in d.clusterer.clustering_dict[rms_tolerance]:
        if verbose:
            print "current largest cluster len= ", len(clust)
        if len(clust) > len(largest):
            if verbose:
                print "resetting largest clust: now len=", len(clust)
            largest = clust
    c = largest[0]  # print info about the lowest energy member of this cluster
    ostr = " "
    dlo_filename = get_filename(d, c)
    ostr += dlo_filename + ","
    de = c.docking_energy
    if refCoords:
        ostr += "%3d,%3d,%3d,% 8.4f,% 8.4f," % (
            len(d.clusterer.data),
            num_clusters,
            len(largest),
            de,
            c.getRMSD(refCoords=refCoords),
        )
    else:
        ostr += "%3d,%3d,%3d,% 8.4f,% 8.4f," % (len(d.clusterer.data), num_clusters, len(largest), de, c.getRMSD())
    if verbose:
        print "set dlo_filename to ", dlo_filename
    # update the coords only if you need to?
    d.ch.set_conformation(c)
    receptor = None
    if build_hydrogen_bonds:
        if not receptor_filename:
            print "receptor_filename must be specified in order to build_hydrogen_bonds"
            return
        receptor = Read(receptor_filename)[0]
        receptor.buildBondsByDistance()
        ostr += construct_hydrogen_bonds(receptor.allAtoms, d.ligMol.allAtoms)
    if report_energy_breakdown:
        if not receptor_filename:
            print "receptor_filename must be specified in order to build_hydrogen_bonds"
            return
        if not receptor:
            receptor = Read(receptor_filename)[0]
            receptor.buildBondsByDistance()
        # ostr += get_energy_breakdown(receptor.allAtoms, d.ligMol.allAtoms, c)
        ostr += get_energy_breakdown(receptor.allAtoms, d.ligMol.allAtoms, c.getCoords()[:])
    return ostr
Ejemplo n.º 48
0
 def test_Write_4Char_AtomNames(self):
     """ check that atoms with names of 4+char are written properly"""
     from MolKit import Read
     self.mol = Read("Data/HTet.mol2")[0]
     from MolKit.pdbWriter import PdbWriter
     writer = PdbWriter()
     writer.write('Data/test_HTet.pdb', self.mol)
     testmol = Read("Data/test_HTet.pdb")[0]
     self.assertEqual(len(self.mol.allAtoms), len(testmol.allAtoms))
     #check the 4char atoms have correct element types
     self.assertEqual(testmol.allAtoms[0].element, 'C')
     self.assertEqual(testmol.allAtoms[1].element, 'Cl')
     self.assertEqual(testmol.allAtoms[22].element, 'N')
     self.assertEqual(testmol.allAtoms[23].element, 'H')
     #check the 4char atoms have reasonable names
     self.assertEqual(testmol.allAtoms[0].name, 'C11')
     self.assertEqual(testmol.allAtoms[1].name, 'Cl22')
     self.assertEqual(testmol.allAtoms[22].name, 'N61')
     self.assertEqual(testmol.allAtoms[23].name, 'HN61')
     os.system("rm Data/test_HTet.pdb")
def get_best_energy_info(d, rms_tolerance, build_hydrogen_bonds=False, \
                                report_energy_breakdown=False,
                                report_unbound_energy=False,
                                receptor_filename=None, refCoords=None,
                                subtract_internal_energy=False):
    global be
    ostr = "" 
    clust0 = d.clusterer.clustering_dict[rms_tolerance][0]
    c = clust0[0]
    #find the filename of the best result
    dlo_filename = get_filename(d, c)
    if verbose: print "set dlo_filename to ", dlo_filename
    ostr = dlo_filename + ", "
    be = c.binding_energy
    if subtract_internal_energy:
        be = c.binding_energy - c.total_internal
    if refCoords:
        ostr += "%3d,%3d,%3d,% 8.4f,% 8.4f," %(len(d.clusterer.data), num_clusters, len(clust0),  be, c.getRMSD(refCoords=refCoords))
        #ostr += "%3d,%3d,%3d,% 8.4f,% 8.4f," %(len(d.clusterer.data), num_clusters, len(clust0),  c.binding_energy, c.getRMSD(refCoords=refCoords))
    else:
        ostr += "%3d,%3d,%3d,% 8.4f,% 8.4f," %(len(d.clusterer.data), num_clusters, len(clust0),  be, c.getRMSD())
        #ostr += "%3d,%3d,%3d,% 8.4f,% 8.4f," %(len(d.clusterer.data), num_clusters, len(clust0),  c.binding_energy, c.getRMSD())
    d.ch.set_conformation(c)
    receptor = None
    if build_hydrogen_bonds:
        if not receptor_filename:
            print "receptor_filename must be specified in order to build_hydrogen_bonds"
            return 
        receptor = Read(receptor_filename)[0] 
        receptor.buildBondsByDistance()
        d.ligMol.buildBondsByDistance()
        ostr += construct_hydrogen_bonds(receptor.allAtoms, d.ligMol.allAtoms, verbose=verbose)
    if report_energy_breakdown:
        if not receptor_filename:
            print "receptor_filename must be specified in order to build_hydrogen_bonds"
        if not receptor:
            receptor = Read(receptor_filename)[0] 
            receptor.buildBondsByDistance()
        #build bonds if necessary 
        d.ligMol.buildBondsByDistance()
        #ostr += get_energy_breakdown(receptor.allAtoms, d.ligMol.allAtoms, c)
        ostr += get_energy_breakdown(receptor.allAtoms, d.ligMol.allAtoms, c.getCoords()[:])
    if report_unbound_energy:
        if c.unbound_energy is not None: 
            ostr += ",% 8.4f" %c.unbound_energy
        else:
            if verbose: print "conformation's unbound energy is None!"
            ostr += ", 0.0" 
    return ostr
Ejemplo n.º 50
0
 def set_ligand(self, ligand_filename): 
     self.ligand_filename = os.path.basename(ligand_filename)
     if verbose:
         print "set ligand_filename to", self.ligand_filename
     self.dpo.set_ligand(ligand_filename)
     #expect a filename like ind.out.pdbq: get 'ind' from it
     self.ligand_stem = string.split(self.ligand_filename,'.')[0]
     if verbose: print "set ligand_stem to", self.ligand_stem
     self.ligand = Read(ligand_filename)[0]
     if self.ligand==None:
         print 'ERROR reading: ', ligand_filename
         return 
     if verbose: 
         print "read ", self.ligand.name
     #set dpo:
     #move
     self.dpo['move']['value'] = self.ligand_filename
     if verbose: print "set move to ", self.dpo['move']['value']
     #ndihe
     #assumes ligand has torTree
     self.dpo['ndihe']['value'] = self.ligand.parser.keys.count("BRANCH")
     #self.dpo['ndihe']['value'] = len(self.ligand.torTree.torsionMap)
     if verbose: print "set ndihe to ", self.dpo['ndihe']['value']
     #torsdof
     #caution dpo['torsdof4']['value'] is a list [ndihe, 0.274]
     try:
         self.dpo['torsdof4']['value'][0] = self.ligand.TORSDOF
     except:
         print 'setting torsdof to ligand.ndihe=', self.ligand.ndihe
         self.dpo['torsdof4']['value'][0] = self.ligand.ndihe
     if verbose: print "set torsdof4 to ", self.dpo['torsdof4']['value']
     #types
     self.ligand.types = self.getTypes(self.ligand)
     self.dpo['ligand_types']['value'] = self.ligand.types
     if verbose: print "set types to ", self.dpo['ligand_types']['value']
     #about
     self.ligand.getCenter()
     cen = self.ligand.center
     self.dpo['about']['value'] =  [round(cen[0],4), round(cen[1],4),\
                                     round(cen[2],4)]
     if verbose: print "set about to ", self.dpo['about']['value']
 def set_ligand(self, ligand_filename): 
     self.ligand_filename = os.path.basename(ligand_filename)
     if self.verbose:
         print "set ligand_filename to", self.ligand_filename
     self.gpo.set_ligand(ligand_filename)
     #expect a filename like ind.out.pdbq: get 'ind' from it
     self.ligand_stem = string.split(self.ligand_filename,'.')[0]
     if self.verbose: print "set ligand_stem to", self.ligand_stem
     self.ligand = Read(ligand_filename)[0]
     #IS THIS USEFUL???
     self.gpo.ligand = self.ligand
     if self.verbose: print "read ", self.ligand.name
     #set gpo:
     #types
     d = {}
     for a in self.ligand.allAtoms:
         d[a.autodock_element] = 1
     sortKeyList =  ['C','A','N','O','S','H','P','n','f','F','c','b','I','M']
     lig_types = ""
     for t in sortKeyList:
         if t in d.keys():
             lig_types = lig_types + t
     self.ligand.types = lig_types
     self.gpo['types']['value'] = self.ligand.types
     if self.verbose: print "set types to ", self.gpo['types']['value']
     #gridcenter
     self.ligand.center = self.ligand.getCenter()
     if self.size_box_to_include_ligand:
         self.getSideLengths(self.ligand) #sets ligand.center
     cen = self.ligand.center
     self.gpo['gridcenter']['value'] =  [round(cen[0],4), round(cen[1],4),\
                                     round(cen[2],4)]
     self.gpo['gridcenterAuto']['value'] =  0
     if self.verbose: print "set gridcenter to ", self.gpo['gridcenter']['value']
     #only make the box bigger from npts, do not make it smaller
     for ix, val in enumerate(self.gpo['npts']['value']):
         if hasattr(self.ligand, 'npts'):
             npts = self.ligand.npts
             if npts[ix]>val:
                 if self.verbose: print "increasing ", ix, " grid dimension to ", val
                 self.gpo['npts']['value'][ix] =  npts[ix]
def get_best_energy_info(
    d, rms_tolerance, build_hydrogen_bonds=False, report_energy_breakdown=False, receptor_filename=None, refCoords=None
):
    ostr = ""
    clust0 = d.clusterer.clustering_dict[rms_tolerance][0]
    c = clust0[0]
    # find the filename of the best result
    dlo_filename = get_filename(d, c)
    if verbose:
        print "set dlo_filename to ", dlo_filename
    ostr = dlo_filename + ", "
    de = c.docking_energy
    if refCoords:
        ostr += "%3d,%3d,%3d,% 8.4f,% 8.4f," % (
            len(d.clusterer.data),
            num_clusters,
            len(clust0),
            de,
            c.getRMSD(refCoords=refCoords),
        )
    else:
        ostr += "%3d,%3d,%3d,% 8.4f,% 8.4f," % (len(d.clusterer.data), num_clusters, len(clust0), de, c.getRMSD())
    d.ch.set_conformation(c)
    receptor = None
    if build_hydrogen_bonds:
        if not receptor_filename:
            print "receptor_filename must be specified in order to build_hydrogen_bonds"
            return
        receptor = Read(receptor_filename)[0]
        receptor.buildBondsByDistance()
        d.ligMol.buildBondsByDistance()
        ostr += construct_hydrogen_bonds(receptor.allAtoms, d.ligMol.allAtoms)
    if report_energy_breakdown:
        if not receptor_filename:
            print "receptor_filename must be specified in order to build_hydrogen_bonds"
        if not receptor:
            receptor = Read(receptor_filename)[0]
            receptor.buildBondsByDistance()
        # build bonds if necessary
        d.ligMol.buildBondsByDistance()
        # ostr += get_energy_breakdown(receptor.allAtoms, d.ligMol.allAtoms, c)
        ostr += get_energy_breakdown(receptor.allAtoms, d.ligMol.allAtoms, c.getCoords()[:])

    return ostr
    if not receptorfilename:
        print 'compute_AutoDock41_score: receptorfilename must be specified.'
        usage()
        sys.exit()

    if not ligandfilename:
        print 'compute_AutoDock41_score: ligandfilename must be specified.'
        usage()
        sys.exit()

    ad_scorer = AutoDock41Scorer(exclude_torsFreeEnergy=exclude_torsFreeEnergy)
    if parameter_library_filename is not None:
        ad_scorer.read_parameter_file(parameter_library_filename)
    supported_types = ad_scorer.supported_types
    receptor = Read(receptorfilename)[0]
    assert os.path.splitext(receptor.parser.filename)[-1]=='.pdbqt',"receptor file not in required '.pdbqt' format"
    if verbose: print 'read ', receptorfilename
    receptor.buildBondsByDistance()
    rec_non_std = ""
    non_std_types = check_types(receptor, supported_types)
    if len(non_std_types):
        rec_non_std = non_std_types[0]
        if len(non_std_types)>1:
            for t in non_std_types[1:]:
                rec_non_std = rec_non_std + '_' + t
    #check format of receptor
    ligand = Read(ligandfilename)[0]
    assert os.path.splitext(ligand.parser.filename)[-1]=='.pdbqt',"ligand file not in required '.pdbqt' format"
    if verbose: print 'read ', ligandfilename
    ligand.buildBondsByDistance()
Ejemplo n.º 54
0
 def setUp(self):
     from MolKit import Read
     self.ind = Read('Data/indinavir.pdb')[0]
     self.ind.buildBondsByDistance()
Ejemplo n.º 55
0
class AromaticCycleBondTests(unittest.TestCase):

    def setUp(self):
        from MolKit import Read
        self.ind = Read('Data/indinavir.pdb')[0]
        self.ind.buildBondsByDistance()
    

    def tearDown(self):
        """
        clean-up
        """
        del(self.ind)



    def test_AromaticCycleBondSelector_select_all(self):
        """
         test AromaticCycleBond select: all aromatic bonds in ind
         This bondSelector uses PyBabel aromatic object 
         #nb doesnot count any in merged ring (?)
        """
        ABS = AromaticCycleBondSelector()
        ats = self.ind.allAtoms
        bnds = ats.bonds[0]
        resultBnds = ABS.select(bnds)
        #print ABS.getAtoms(resultBnds).name
        self.assertEqual(len(resultBnds), 18)


    def test_AromaticCycleBond2Selector_select_all(self):
        """
         test AromaticCycleBond2 select: all aromatic bonds in ind
         This bndSelector uses autotors calculation of normals between
         adjacent atoms in cycles to judge aromaticity 
         #nb does count aromatic bonds in merged ring (?)
        """
        ABS2 = AromaticCycleBondSelector2()
        ats = self.ind.allAtoms
        bnds = ats.bonds[0]
        resultBnds = ABS2.select(bnds)
        #print ABS2.getAtoms(resultBnds).name
        self.assertEqual(len(resultBnds), 18)
        self.assertEqual(len(ABS2.getAtoms(resultBnds)), 18)


    def test_AromaticCycleBond2Selector_select_all2(self):
        """
         This is repeated because repeating it broke when all tests were in
         one class....(???)
        """
        ABS2 = AromaticCycleBondSelector2()
        ats = self.ind.allAtoms
        bnds = ats.bonds[0]
        resultBnds = ABS2.select(bnds)
        #print ABS2.getAtoms(resultBnds).name
        self.assertEqual(len(resultBnds), 18)
        self.assertEqual(len(ABS2.getAtoms(resultBnds)), 18)


    def test_AromaticCycleBond2Selector_select_all3(self):
        """
         This is repeated because repeating it broke when all tests were in
         one class....(???)
        """
        ABS2 = AromaticCycleBondSelector2()
        ats = self.ind.allAtoms
        bnds = ats.bonds[0]
        resultBnds = ABS2.select(bnds)
        #print ABS2.getAtoms(resultBnds).name
        self.assertEqual(len(resultBnds), 18)
        self.assertEqual(len(ABS2.getAtoms(resultBnds)), 18)
Ejemplo n.º 56
0
 def setUp(self):
     from MolKit import Read
     self.mol = Read('Data/1crn_2.pdb')[0]
     self.mol.buildBondsByDistance()