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']
Esempio n. 2
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 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
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
Esempio n. 5
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
Esempio n. 6
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
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
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
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
Esempio n. 10
0
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
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)
Esempio n. 12
0
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
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
Esempio n. 14
0
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)
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)
Esempio n. 16
0
 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]
Esempio n. 17
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 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]
 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'
Esempio n. 20
0
 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'
Esempio n. 21
0
    if not outputfile:
        if verbose:
            print 'write_modes_from_states.py: outputfile not specified. Using stdout'
        #usage()
        #sys.exit()

    lig = Read(ligandfile)
    if not len(lig):
        print "no ligand found in ", ligandfile
        sys.exit()
    lig = lig[0]
    if not hasattr(lig, 'ndihe'):
        print ligandfile + "molecule has no torsion tree"
        sys.exit()
    lig.buildBondsByDistance()
    # add extra slot to ._coords for changing coordinates
    lig.allAtoms.addConformation(lig.allAtoms.coords)
    #?is this necessary
    lig.allAtoms.setConformation(1)
    ntors = lig.ndihe
    length_of_state = 7 + lig.ndihe
    # @@ handle to the input ligLines
    ligLines = lig.parser.allLines

    #setup StateToCoords object
    origin = lig.getCenter()
    if use_zero_origin or interim_state:
        origin = [0., 0., 0.]
    #note: index of _coords to use is always 1
    lig.stoc = StateToCoords(lig, origin, 1)
Esempio n. 22
0
class HydrogenBondBuilderTests(unittest.TestCase):
    def setUp(self):
        from MolKit import Read
        self.mol = Read('Data/1crn_Hs.pdbq')[0]
        self.mol.buildBondsByDistance()

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

    def test_buildHbonds_babelTypes(self):
        """
        test assigning babel_types 
        """
        hb_builder = HydrogenBondBuilder()
        hb_builder.check_babel_types(self.mol.allAtoms)
        d = {}
        for a in self.mol.allAtoms:
            d[a.babel_type] = 1
        all_types = d.keys()
        all_types.sort()
        #print "all_types=", all_types
        #note: these are polar only hydrogens so no type 'HC'
        canned_list = [
            'C+', 'C2', 'C3', 'Cac', 'H', 'N3+', 'Nam', 'Ng+', 'O-', 'O2',
            'O3', 'S3'
        ]
        for k, v in zip(all_types, canned_list):
            self.assertEqual(k, v)

    def test_buildD(self):
        """
        test buildD: donor3Ats, acceptor3Ats, acceptor2Ats, donor2Ats
        """
        hb_builder = HydrogenBondBuilder()
        hb_builder.check_babel_types(self.mol.allAtoms)
        result = hb_builder.buildD(self.mol.allAtoms, hb_builder.paramDict)
        #result_keys = ['donor3Ats', 'acceptor3Ats', 'acceptor2Ats', 'donor2Ats']
        result_keys = [
            'donor3Ats', 'acceptor3Ats', 'hAts', 'acceptorAts', 'acceptor2Ats',
            'donor2Ats'
        ]
        d = {}
        d['donor3Ats'] = [
            'N', 'OG1', 'OG1', 'SG', 'SG', 'OG', 'OG', 'SG', 'OG1', 'SG',
            'OG1', 'OH', 'OG1', 'SG', 'OG1', 'SG', 'OH'
        ]
        d['acceptor3Ats'] = [
            'OG1', 'OG1', 'SG', 'SG', 'OG', 'OG', 'SG', 'OG1', 'SG', 'OG1',
            'OH', 'OG1', 'SG', 'OG1', 'SG', 'OH'
        ]
        d['hAts'] = [
            'HN1', 'HN2', 'HN3', 'HG1', 'HN', 'HG1', 'HN', 'HN', 'HN', 'HG',
            'HN', 'HN', 'HN', 'HN', 'HE', 'HH11', 'HH12', 'HH21', 'HH22', 'HN',
            'HG', 'HN', 'HD21', 'HD22', 'HN', 'HN', 'HD21', 'HD22', 'HN', 'HN',
            'HN', 'HE', 'HH11', 'HH12', 'HH21', 'HH22', 'HN', 'HN', 'HN',
            'HG1', 'HN', 'HN', 'HN', 'HN', 'HN', 'HN', 'HG1', 'HN', 'HH', 'HN',
            'HG1', 'HN', 'HN', 'HN', 'HN', 'HN', 'HN', 'HN', 'HN', 'HG1', 'HN',
            'HN', 'HN', 'HN', 'HH', 'HN', 'HN', 'HD21', 'HD22'
        ]
        d['donor2Ats'] = [
            'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'NE', 'NH1', 'NH2', 'N',
            'N', 'ND2', 'N', 'N', 'ND2', 'N', 'N', 'N', 'NE', 'NH1', 'NH2',
            'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N',
            'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'ND2'
        ]
        d['acceptor2Ats'] = [
            'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'OD1',
            'O', 'O', 'OD1', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O',
            'OE1', 'OE2', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O',
            'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'OD1', 'OD2',
            'O', 'O', 'O', 'OD1', 'OXT'
        ]
        #acceptorAts = acceptor2Ats + acceptor3Ats
        d['acceptorAts'] = [
            'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'OD1',
            'O', 'O', 'OD1', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O',
            'OE1', 'OE2', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O',
            'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'OD1', 'OD2',
            'O', 'O', 'O', 'OD1', 'OXT', 'OG1', 'OG1', 'SG', 'SG', 'OG', 'OG',
            'SG', 'OG1', 'SG', 'OG1', 'OH', 'OG1', 'SG', 'OG1', 'SG', 'OH'
        ]
        for k in result_keys:
            #print 'testing ', k, ': '
            if result[k] is not None and len(result[k]):
                self.assertEqual(result[k].name, d[k])
            else:
                self.assertEqual(result[k], d[k])

    def test_process_part1(self):
        """
        check hAts and acceptorAts from buildD
        """
        hb_builder = HydrogenBondBuilder()
        hb_builder.check_babel_types(self.mol.allAtoms)
        result = hb_builder.buildD(self.mol.allAtoms, hb_builder.paramDict)
        hAts = result['hAts']
        self.assertEqual(len(hAts), 69)
        acceptorAts = result['acceptorAts']
        self.assertEqual(len(acceptorAts), 70)
        #hb_builder.process(result, result, hb_builder.paramDict)

    def test_process_part2(self):
        """
        check results of calls to removeNeighbors, filterBasedOnAngs,
        removeBadAts...
        """
        hb_builder = HydrogenBondBuilder()
        hb_builder.check_babel_types(self.mol.allAtoms)
        result = hb_builder.buildD(self.mol.allAtoms, hb_builder.paramDict)
        hAts = result['hAts']
        acceptorAts = result['acceptorAts']
        dist = hb_builder.paramDict['distCutoff']
        atDict = hb_builder.distSelector.select(hAts, acceptorAts, dist)
        self.assertEqual(len(atDict), 40)
        atDict = hb_builder.removeNeighbors(atDict)
        self.assertEqual(len(atDict), 30)

        donor2Ats = result['donor2Ats']
        donor3Ats = result['donor3Ats']
        acceptor2Ats = result['acceptor2Ats']
        acceptor3Ats = result['acceptor3Ats']
        badAtDict = hb_builder.filterBasedOnAngs(atDict, donor2Ats, donor3Ats,
                                                 acceptor2Ats, acceptor3Ats,
                                                 hb_builder.paramDict)
        self.assertEqual(len(badAtDict), 30)
        atDict = hb_builder.removeBadAts(atDict, badAtDict)
        self.assertEqual(len(atDict), 28)
        #hb_builder.process(result, result, hb_builder.paramDict)
        #self.assertEqual(len(self.mol.allAtoms.get(lambda x: hasattr(x, 'hbonds')), 28)

    def test_buildHbonds(self):
        """
        check results of single call to build
        """
        hb_builder = HydrogenBondBuilder()
        hb_builder.build(self.mol)
        hbond_ats = self.mol.allAtoms.get(lambda x: hasattr(x, 'hbonds'))
        self.assertEquals(len(hbond_ats), 82)
        d = {}
        for a in self.mol.allAtoms:
            if hasattr(a, 'hbonds'):
                for b in a.hbonds:
                    d[b] = 1
        self.assertEquals(len(d.keys()), 28)
Esempio n. 23
0
def get_largest_cluster_info(d, rms_tolerance, build_hydrogen_bonds=False, \
                                    report_energy_breakdown=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
    d.ch.set_conformation(c)
    ostr = " "
    dlo_filename = get_filename(d, c)
    print("lc: dlo_filename= ", dlo_filename)
    ostr += dlo_filename + ","
    print("161 ostr=", ostr, "\n")
    be_lc = c.binding_energy
    print("163 set be_lc to ", be_lc, "\n")
    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())
    print("170 2c: ostr=", ostr, "\n")
    if verbose: print("set dlo_filename to ", dlo_filename)
    #update the coords only if you need to?
    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 len(lp_ats):
        ostr += " % 8.4f," % numpy.add.reduce(lp_ats.estat_energy +
                                              lp_ats.vdw_energy)
        print("199  lp_ats:  ", ostr, "\n")
    if len(ls_ats):
        ostr += " % 8.4f," % numpy.add.reduce(ls_ats.estat_energy +
                                              ls_ats.vdw_energy)
        print("202 ls_ats:  ", ostr, "\n")
    if len(rp_ats):
        ostr += " % 8.4f," % numpy.add.reduce(rp_ats.estat_energy +
                                              rp_ats.vdw_energy)
        print("205 rp_ats:  ", ostr, "\n")
    return ostr
Esempio n. 24
0
class BaseTests(unittest.TestCase):
    def setUp(self):
        from MolKit import Read
        self.mol = Read('Data/1crn_2.pdb')[0]
        self.mol.buildBondsByDistance()

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

    def compareBondSets(self, set1, set2):
        """
        check that two bond sets have same bonds
        """
        self.assertEquals(len(set1), len(set2))
        idlist1 = [id(x) for x in set1]
        idlist2 = [id(x) for x in set2]
        idlist1.sort()
        idlist2.sort()
        for b1, b2 in zip(idlist1, idlist2):
            self.assertEquals(b1, b2)

    def test_constructor(self):
        """
        instantiate an BondClassifier
        """
        bndClassifier = BondClassifier()
        self.assertEquals(bndClassifier.__class__, BondClassifier)

    def test_constructorOptions(self):
        """
         test possible constructor options
            options = {key: bondSelector, key2:bondSelector2,....}
        """
        bndClassifier = BondClassifier({'amide': AmideBondSelector()})
        self.assertEquals(bndClassifier.__class__, BondClassifier)

    def test_inputParameters(self):
        """
         test nul input to classify
            
        """
        bndClassifier = BondClassifier({'amide': AmideBondSelector()})
        self.assertRaises(AssertionError, bndClassifier.classify)

    def test_classifierVSselectors(self):
        """
         make sure that the classifier returns the same results as its
         selectors
        """
        bndClassifier = BondClassifier({
            'amide':
            AmideBondSelector(),
            'cycle':
            CycleBondSelector(),
            'leaf':
            LeafBondSelector(),
            'peptide':
            PeptideBackBoneBondSelector(),
        })
        #all the bonds in the molecule as a BondSet
        bnds = self.mol.allAtoms.bonds[0]

        #get the specified bonds as a BondSet
        localDict = {}
        localDict['amide'] = AmideBondSelector().select(bnds)
        localDict['cycle'] = CycleBondSelector().select(bnds)
        localDict['leaf'] = LeafBondSelector().select(bnds)
        localDict['peptide'] = PeptideBackBoneBondSelector().select(bnds)

        #make the classifier do the same thing
        resultDict = bndClassifier.classify(bnds)

        for k in resultDict.keys():
            self.compareBondSets(localDict[k], resultDict[k])
Esempio n. 25
0
class BaseTests(unittest.TestCase):
    def setUp(self):
        self.mol = Read('Data/1crn.pdb')[0]
        self.mol.buildBondsByDistance()

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

    def test_gasteiger_calc_constructor(self):
        """
        instantiate an GasteigerChargeCalculator
        """
        g_calc = GasteigerChargeCalculator()
        self.assertEquals(g_calc.__class__, GasteigerChargeCalculator)

    def test_gasteiger_calc_addCharges(self):
        """
         GasteigerChargeCalculator addCharges to each atom, giving expected total
        """
        atlen = len(self.mol.allAtoms)
        g_calc = GasteigerChargeCalculator()
        g_calc.addCharges(self.mol.allAtoms)
        g_ats = self.mol.allAtoms.get(lambda x: x.chargeSet == 'gasteiger')
        self.assertEquals(atlen, len(g_ats))
        total_charge = Numeric.add.reduce(self.mol.allAtoms.charge)
        self.assertAlmostEquals(total_charge, 1.221245e-15, 6)

    def test_kollman_calc_constructor(self):
        """
        instantiate an KollmanChargeCalculator
        """
        k_calc = KollmanChargeCalculator()
        self.assertEquals(k_calc.__class__, KollmanChargeCalculator)

    def test_Kollman_calc_addCharges(self):
        """
         KollmanChargeCalculator addCharges to each atom, giving expected total
        """
        atlen = len(self.mol.allAtoms)
        k_calc = KollmanChargeCalculator()
        k_calc.addCharges(self.mol.allAtoms)
        k_ats = self.mol.allAtoms.get(lambda x: x.chargeSet == 'Kollman')
        self.assertEquals(atlen, len(k_ats))
        total_charge = Numeric.add.reduce(self.mol.allAtoms.charge)
        self.assertAlmostEquals(total_charge, -19.554, 4)

    def test_Kollman_calc_from_bug(self):
        """
         test KollmanChargeCalculator can add charges to 1a30
        """
        mol = Read("Data/1a30.pdb")[0]
        atlen = len(mol.allAtoms)
        k_calc = KollmanChargeCalculator()
        k_calc.addCharges(mol.allAtoms)
        k_ats = mol.allAtoms.get(lambda x: x.chargeSet == 'Kollman')
        self.assertEquals(atlen, len(k_ats))
        total_charge = Numeric.add.reduce(mol.allAtoms.charge)
        self.assertAlmostEquals(total_charge, 5.7060, 4)
Esempio n. 26
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)
            sys.exit()

    if not filename:
        print 'write_random_state_ligand: filename must be specified.'
        usage()
        sys.exit()

    m = Read(filename)[0]
    if verbose: print 'read ', filename
    #validate specified ligand file
    assert hasattr(m, 'torTree'), "specified ligand does not have a torsion tree"
    ndihe = m.parser.keys.count('BRANCH')
    if verbose: print m.name, ' has ', ndihe, ' torsions'

    #1. prepare molecule 
    m.buildBondsByDistance()
    orig_coords = m.allAtoms.coords[:]
    m.allAtoms.addConformation(m.allAtoms.coords)
    coord_index = 1
    origin = m.getCenter()
    m.stoc = StateToCoords(m, origin, 1)
    #build reference dictionary of original bonds
    orig = len(m.allAtoms.bonds[0])
    orig_d = {}
    for a in m.allAtoms: orig_d[a]=set(a.bonds.getAtoms())

    #try a new random state up to ntries times
    # convert trans to space centered on m
    for new_try in range(ntries):
        #reset coords in working slot to original coords for new try
        m.allAtoms.updateCoords(orig_coords, ind=coord_index)
            sys.exit()

    if not filename:
        print('write_random_state_ligand: filename must be specified.')
        usage()
        sys.exit()

    m = Read(filename)[0]
    if verbose: print('read ', filename)
    #validate specified ligand file
    assert hasattr(m, 'torTree'), "specified ligand does not have a torsion tree"
    ndihe = m.parser.keys.count('BRANCH')
    if verbose: print(m.name, ' has ', ndihe, ' torsions')

    #1. prepare molecule 
    m.buildBondsByDistance()
    orig_coords = m.allAtoms.coords[:]
    m.allAtoms.addConformation(m.allAtoms.coords)
    coord_index = 1
    origin = m.getCenter()
    m.stoc = StateToCoords(m, origin, 1)
    #build reference dictionary of original bonds
    orig = len(m.allAtoms.bonds[0])
    orig_d = {}
    for a in m.allAtoms: orig_d[a]=set(a.bonds.getAtoms())

    #try a new random state up to ntries times
    # convert trans to space centered on m
    for new_try in range(ntries):
        #reset coords in working slot to original coords for new try
        m.allAtoms.updateCoords(orig_coords, ind=coord_index)
            sys.exit()


    if not  receptor_filename:
        print 'prepare_flexreceptor4: receptor filename must be specified!\n'
        usage()
        sys.exit()

    if not  residues_to_move:
        print 'prepare_flexreceptor4: residues to move must be specified!\n'
        usage()
        sys.exit()


    r = Read(receptor_filename)[0]
    r.buildBondsByDistance()
    if verbose: print 'read ', receptor_filename

    all_res = ResidueSet()
    res_names = residues_to_move.split('_')
    for n in res_names:
        res = r.chains.residues.get(lambda x: x.name==n)
        if verbose: print "adding ", res.name, " to ", all_res
        all_res += res
    if verbose:
        print "all_res=", all_res.full_name(), 'all_res.__class__=', all_res.__class__
    #?check for duplicates
    d = {}
    for res in all_res: d[res] = 1
    all_res = d.keys()
    all_res = ResidueSet(all_res)
    if not outputfile:
        if verbose: print 'write_modes_from_states.py: outputfile not specified. Using stdout'
        #usage()
        #sys.exit()


    lig = Read(ligandfile)
    if not len(lig):
        print "no ligand found in ", ligandfile
        sys.exit()
    lig = lig[0]
    if not hasattr(lig, 'ndihe'):
        print ligandfile + "molecule has no torsion tree"
        sys.exit()
    lig.buildBondsByDistance()
    # add extra slot to ._coords for changing coordinates
    lig.allAtoms.addConformation(lig.allAtoms.coords)
    #?is this necessary
    lig.allAtoms.setConformation(1)
    ntors = lig.ndihe
    length_of_state = 7+lig.ndihe
    # @@ handle to the input ligLines
    ligLines = lig.parser.allLines

    #setup StateToCoords object
    origin = lig.getCenter()
    if use_zero_origin or interim_state:
        origin = [0.,0.,0.]    
    #note: index of _coords to use is always 1
    lig.stoc = StateToCoords(lig, origin, 1)
    if not  res_in_receptor:
        print 'prepare_covalent_flexres: res_in_receptor onto which the ligand will superimposed must be specified!\n'
        usage()
        sys.exit()

    if not ratom1_ratom2_ratom3:
        ratom1_ratom2_ratom3 = atom1_atom2_atom3

    #initialize the receptor
    extension = os.path.splitext(receptor_filename)[1]
    if extension!=".pdbqt":
        print 'prepare_covalent_flexres: receptor file must be in .pdbqt format\n'
        usage()
        sys.exit()
    rM = Read(receptor_filename)[0]
    rM.buildBondsByDistance()
    if verbose: print 'read ', receptor_filename

    #initialize the flexible-residue-to-be in the receptor
    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]
Esempio n. 32
0
def get_best_energy_info(d, rms_tolerance, build_hydrogen_bonds=False, \
                                report_energy_breakdown=False,
                                receptor_filename=None, refCoords=None,
                                subtract_internal_energy=False):
    global be
    ostr = ""
    clust0 = d.clusterer.clustering_dict[rms_tolerance][0]
    c = clust0[0]
    d.ch.set_conformation(c)
    #find the filename of the best result
    dlo_filename = get_filename(d, c)
    #print "83: set dlo_filename to ", dlo_filename
    if verbose: print("set dlo_filename to ", dlo_filename)
    ostr = dlo_filename + ", "
    be = c.binding_energy
    #print "87: set be to ", be
    if subtract_internal_energy:
        be = c.binding_energy - c.total_internal
        #print "90: after subtracting_internal_energy be = ", be
    if refCoords:
        ostr += "%3d,%3d,%3d,% 8.4f,% 8.4f," % (len(
            d.clusterer.data), num_clusters, len(clust0), be,
                                                c.getRMSD(refCoords=refCoords))
        #print "93: len(clust0)=", len(clust0), ", be=", be, " rmsd_LE=", c.getRMSD(refCoords=refCoords)
        #print "94: ostr=", ostr
        #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())
        print("99:  rmsd_LE=", c.getRMSD(), " @@@")
        #print "98: len(clust0)=", len(clust0), ", be=", be, " rmsd_LE=", c.getRMSD()
        #print "99: ostr=", ostr
        #ostr += "%3d,%3d,%3d,% 8.4f,% 8.4f," %(len(d.clusterer.data), num_clusters, len(clust0),  c.binding_energy, c.getRMSD())
    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()[:])
    print("128: len(lp_ats)=", len(lp_ats))
    if len(lp_ats):
        try:
            ostr += " % 8.4f," % numpy.add.reduce(lp_ats.estat_energy +
                                                  lp_ats.vdw_energy)
            print("131: lp_ats 1: ostr=", ostr, "\n")
        except:
            ostr += "         "
    if len(ls_ats):
        ostr += " % 8.4f," % numpy.add.reduce(ls_ats.estat_energy +
                                              ls_ats.vdw_energy)
        print("135 ls_ats 2: ostr=", ostr, "\n")
    print("len(rp_ats)=", len(rp_ats))
    if len(rp_ats):
        ostr += " % 8.4f," % numpy.add.reduce(rp_ats.estat_energy +
                                              rp_ats.vdw_energy)
        print("139: ostr=", ostr, "\n")
    return ostr
class HydrogenBondBuilderTests(unittest.TestCase):

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

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


    def test_buildHbonds_babelTypes(self):
        """
        test assigning babel_types 
        """
        hb_builder = HydrogenBondBuilder()
        hb_builder.check_babel_types(self.mol.allAtoms)
        d = {}
        for a in self.mol.allAtoms:
            d[a.babel_type] = 1
        all_types= d.keys()
        all_types.sort()
        #print "all_types=", all_types
        #note: these are polar only hydrogens so no type 'HC'
        canned_list = ['C+', 'C2', 'C3', 'Cac', 'H',  'N3+', 
                        'Nam', 'Ng+', 'O-', 'O2', 'O3', 'S3']
        for k, v in zip(all_types, canned_list):
            self.assertEqual(k,v)


    def test_buildD(self):
        """
        test buildD: donor3Ats, acceptor3Ats, acceptor2Ats, donor2Ats
        """
        hb_builder = HydrogenBondBuilder()
        hb_builder.check_babel_types(self.mol.allAtoms)
        result = hb_builder.buildD(self.mol.allAtoms, hb_builder.paramDict)
        #result_keys = ['donor3Ats', 'acceptor3Ats', 'acceptor2Ats', 'donor2Ats']
        result_keys = ['donor3Ats', 'acceptor3Ats', 'hAts', 'acceptorAts', 'acceptor2Ats', 'donor2Ats']
        d = {}
        d['donor3Ats'] = ['N', 'OG1', 'OG1', 'SG', 'SG', 'OG', 'OG', 'SG', 'OG1', 'SG', 'OG1', 'OH', 'OG1', 'SG', 'OG1', 'SG', 'OH']
        d['acceptor3Ats'] = ['OG1', 'OG1', 'SG', 'SG', 'OG', 'OG', 'SG', 'OG1', 'SG', 'OG1', 'OH', 'OG1', 'SG', 'OG1', 'SG', 'OH'] 
        d['hAts'] = ['HN1', 'HN2', 'HN3', 'HG1', 'HN', 'HG1', 'HN', 'HN', 'HN', 'HG', 'HN', 'HN', 'HN', 'HN', 'HE', 'HH11', 'HH12', 'HH21', 'HH22', 'HN', 'HG', 'HN', 'HD21', 'HD22', 'HN', 'HN', 'HD21', 'HD22', 'HN', 'HN', 'HN', 'HE', 'HH11', 'HH12', 'HH21', 'HH22', 'HN', 'HN', 'HN', 'HG1', 'HN', 'HN', 'HN', 'HN', 'HN', 'HN', 'HG1', 'HN', 'HH', 'HN', 'HG1', 'HN', 'HN', 'HN', 'HN', 'HN', 'HN', 'HN', 'HN', 'HG1', 'HN', 'HN', 'HN', 'HN', 'HH', 'HN', 'HN', 'HD21', 'HD22']
        d['donor2Ats'] = ['N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'NE', 'NH1', 'NH2', 'N', 'N', 'ND2', 'N', 'N', 'ND2', 'N', 'N', 'N', 'NE', 'NH1', 'NH2', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'N', 'ND2']
        d['acceptor2Ats'] = ['O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'OD1', 'O', 'O', 'OD1', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'OE1', 'OE2', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'OD1', 'OD2', 'O', 'O', 'O', 'OD1', 'OXT']
        #acceptorAts = acceptor2Ats + acceptor3Ats
        d['acceptorAts'] = ['O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'OD1', 'O', 'O', 'OD1', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'OE1', 'OE2', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'OD1', 'OD2', 'O', 'O', 'O', 'OD1', 'OXT', 'OG1', 'OG1', 'SG', 'SG', 'OG', 'OG', 'SG', 'OG1', 'SG', 'OG1', 'OH', 'OG1', 'SG', 'OG1', 'SG', 'OH'] 
        for k in result_keys:
            #print 'testing ', k, ': '
            if result[k] is not None and len(result[k]):
                self.assertEqual(result[k].name, d[k])
            else:
                self.assertEqual(result[k], d[k])



    def test_process_part1(self):
        """
        check hAts and acceptorAts from buildD
        """
        hb_builder = HydrogenBondBuilder()
        hb_builder.check_babel_types(self.mol.allAtoms)
        result = hb_builder.buildD(self.mol.allAtoms, hb_builder.paramDict)
        hAts = result['hAts']
        self.assertEqual(len(hAts), 69)
        acceptorAts = result['acceptorAts']
        self.assertEqual(len(acceptorAts), 70)
        #hb_builder.process(result, result, hb_builder.paramDict)
        

    def test_process_part2(self):
        """
        check results of calls to removeNeighbors, filterBasedOnAngs,
        removeBadAts...
        """
        hb_builder = HydrogenBondBuilder()
        hb_builder.check_babel_types(self.mol.allAtoms)
        result = hb_builder.buildD(self.mol.allAtoms, hb_builder.paramDict)
        hAts = result['hAts']
        acceptorAts = result['acceptorAts']
        dist = hb_builder.paramDict['distCutoff']
        atDict = hb_builder.distSelector.select(hAts, acceptorAts, dist)
        self.assertEqual(len(atDict), 40)
        atDict = hb_builder.removeNeighbors(atDict)
        self.assertEqual(len(atDict), 30)

        donor2Ats = result['donor2Ats']
        donor3Ats = result['donor3Ats']
        acceptor2Ats = result['acceptor2Ats']
        acceptor3Ats = result['acceptor3Ats']
        badAtDict = hb_builder.filterBasedOnAngs(atDict, donor2Ats, donor3Ats,
                        acceptor2Ats, acceptor3Ats, hb_builder.paramDict)
        self.assertEqual(len(badAtDict), 30)
        atDict = hb_builder.removeBadAts(atDict, badAtDict)
        self.assertEqual(len(atDict), 28)
        #hb_builder.process(result, result, hb_builder.paramDict)
        #self.assertEqual(len(self.mol.allAtoms.get(lambda x: hasattr(x, 'hbonds')), 28)
        


    def test_buildHbonds(self):
        """
        check results of single call to build
        """
        hb_builder = HydrogenBondBuilder()
        hb_builder.build(self.mol)
        hbond_ats = self.mol.allAtoms.get(lambda x: hasattr(x, 'hbonds'))
        self.assertEquals(len(hbond_ats), 82)
        d = {}
        for a in self.mol.allAtoms:
            if hasattr(a, 'hbonds'):
                for b in a.hbonds:
                    d[b] = 1
        self.assertEquals(len(d.keys()), 28)
        sys.exit()
    if ligandfilename is None:
        print "trilinterp_atoms.py: ligand filename must be specified."
        usage()
        sys.exit()
    #OPTIONAL:
    if mapstem is None and verbose:
        print "trilinterp_atoms.py: map stem set from receptorfilename"
    if outputfilename is None: 
        if verbose: print "trilinterp_atoms.py: output to screen"
    else:
        print 'writing output to %s' %outputfilename

    #Start to work:
    rec = Read(receptorfilename)[0]
    rec.buildBondsByDistance() #??@@??
    #setup mapstem
    if mapstem is None: 
        mapstem = rec.name

    lig = Read(ligandfilename)[0]
    lig.buildBondsByDistance()
    #get atoms for trilinterp
    if indicies is None or indicies=='':
        indicies = range(len(lig.allAtoms))
    else:
        indicies = map(int, indicies.split(','))
    if verbose: print "now indicies=", indicies

    total = 0
    pts = []
class BaseTests(unittest.TestCase):
    def setUp(self):
        from MolKit import Read
        self.mol = Read('Data/1crn_2.pdb')[0]
        self.mol.buildBondsByDistance()
        
    
    def tearDown(self):
        """
        clean-up
        """
        del self.mol


    def compareBondSets(self, set1, set2):
        """
        check that two bond sets have same bonds
        """
        self.assertEquals(len(set1), len(set2))
        idlist1 = [id(x) for x in set1]
        idlist2 = [id(x) for x in set2]
        idlist1.sort()
        idlist2.sort()
        for b1,b2 in zip(idlist1, idlist2):
            self.assertEquals(b1,b2)


    def test_constructor(self):
        """
        instantiate an BondClassifier
        """
        bndClassifier = BondClassifier()
        self.assertEquals(bndClassifier.__class__, BondClassifier)


    def test_constructorOptions(self):
        """
         test possible constructor options
            options = {key: bondSelector, key2:bondSelector2,....}
        """
        bndClassifier = BondClassifier({'amide': AmideBondSelector()})
        self.assertEquals(bndClassifier.__class__, BondClassifier)


    def test_inputParameters(self):
        """
         test nul input to classify
            
        """
        bndClassifier = BondClassifier({'amide': AmideBondSelector()})
        self.assertRaises(AssertionError, bndClassifier.classify)


    def test_classifierVSselectors(self):
        """
         make sure that the classifier returns the same results as its
         selectors
        """
        bndClassifier = BondClassifier({'amide': AmideBondSelector(),
                                        'cycle': CycleBondSelector(),
                                        'leaf': LeafBondSelector(),
                                        'peptide': PeptideBackBoneBondSelector(),
                                        })
        #all the bonds in the molecule as a BondSet
        bnds = self.mol.allAtoms.bonds[0]

        #get the specified bonds as a BondSet
        localDict = {}
        localDict['amide'] = AmideBondSelector().select(bnds)
        localDict['cycle'] = CycleBondSelector().select(bnds)
        localDict['leaf'] =  LeafBondSelector().select(bnds)
        localDict['peptide'] = PeptideBackBoneBondSelector().select(bnds)

        #make the classifier do the same thing
        resultDict = bndClassifier.classify(bnds)

        for k in resultDict.keys():
            self.compareBondSets(localDict[k], resultDict[k])
Esempio n. 36
0
            print("unable to read ", rms_reference)
        else:
            ref = ref[0]
            coords = ref.allAtoms.coords
            refCoords = coords[:]
    d.clusterer.rmsTool = RMSDCalculator(coords)

    d.clusterer.make_clustering(rms_tolerance)

    # for building hydrogen bonds or reporting energy breakdown
    # setup receptor:
    if build_hydrogen_bonds or report_energy_breakdown:
        d.ligMol.buildBondsByDistance()
        receptor_filename = directory + '/' + receptor_filename
        receptor = Read(receptor_filename)[0]
        receptor.buildBondsByDistance()
    if build_hydrogen_bonds:
        hbondBuilder = HydrogenBondBuilder()
        #do next two lines for each conf
        #d.ligMol.set_conformation(conf)
        #atDict = hbondBuilder.build(receptor.allAtoms, d.ligMol.allAtoms)
        #num_hbonds= len(atDict)
    if report_energy_breakdown:
        ms = MolecularSystem()
        ms.add_entities(receptor.allAtoms)
        ms.add_entities(d.ligMol.allAtoms)
        ad305scorer = AutoDock305Scorer()
        ad305scorer.set_molecular_system(ms)
        #whenever the ligMol changes conf,
        #need to call ms.set_coords(1, new_coords)
Esempio n. 37
0
class PDBWriterTests(unittest.TestCase):
    def setUp(self):
        pass

    def tearDown(self):
        if hasattr(self, 'mol'): del self.mol


    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")

    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")

    def test_Write_3(self):
        """
        Test writing out CONECT records for the bonds described in
        the pdb file eventhough the bonds built by distance exist.
        """
        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")

    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 test_Write_5(self):
        from MolKit import Read
        self.mol = Read("Data/1crn.pdb")[0]
        self.mol.secondaryStructureFromFile()
        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='File')
        # 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 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 test_Write_7(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()
        self.mol.write('Data/1crn_writer.pdb', self.mol, writer)
        # 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")


    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")
Esempio n. 38
0
def autodock_scoring(receptor, ligand):
	receptorfilename =  receptor
	ligandfilename =  ligand
	write_file_mode = False
	outputfilename = dirname+'/Alanine_Scanning_Binding_Energies_Result.csv'
	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()
	rec_non_std = ""

	non_std_types = check_types(receptor, supported_types)

	#Checking the format of receptor
	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

	ligand = Read(ligandfilename)[0]
	ligand.buildBondsByDistance()
	lig_non_std = ""
	non_std_types = check_types(ligand, supported_types)

	#Checking the format of ligand
	if len(non_std_types):
		lig_non_std = non_std_types[0]
		if len(non_std_types)>1:
			for t in non_std_types[1:]:
				lig_non_std = lig_non_std + '_' + t

	mode = 'a'

	first = not os.path.exists(outputfilename)
	if write_file_mode:
		mode = 'w'
		first = True

	optr = open(outputfilename, mode)
    	
	if first:
		tstr = "Receptor,Ligand,AutoDock4.1Score,estat,hb,vdw,dsolv,tors\n"
		optr.write(tstr)

	#setup the molecular system
	ostr = ""

	if len(lig_non_std):
		ostr = 'ERROR: unable to score ligand "%s" due to presence of non-standard atom type(s): %s\n' %(ligand.name, lig_non_std)
		optr.write(ostr)

	elif len(rec_non_std):
		ostr = 'ERROR: unable to score receptor "%s" due to non-standard atom type(s): %s\n' %(receptor.name, rec_non_std)
		optr.write(ostr)
	
	else: 
		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
        	ostr = "%19s,%3s,%8.4f,%6.4f,%6.4f,%6.4f,%6.4f,%6.4f\n" %(receptor.name, uniq_ligand[0], score, estat, hb, vdw, dsolv, torsEnrg)
        	optr.write(ostr)

	optr.close()
Esempio n. 39
0
        sys.exit()

    if not residues_to_move:
        print('prepare_flexreceptor4: residues to move must be specified!\n')
        usage()
        sys.exit()

    extension = os.path.splitext(receptor_filename)[1]
    if extension != ".pdbqt":
        print(
            'prepare_flexreceptor4: receptor file must be in .pdbqt format\n')
        usage()
        sys.exit()

    rec = Read(receptor_filename)[0]
    bnds = rec.buildBondsByDistance()
    if verbose: print('read ', receptor_filename)

    all_res = ResidueSet()
    # hsg1:A:ARG8_ILE82;hsg1:B:THR4
    # ARG8_ILE84
    names_by_chain = residues_to_move.split(',')
    if verbose:
        print("Specified flexres selection strings are:")
        for strN in names_by_chain:
            print("   %s" % strN)
    #1. ['hsg1:A:ARG8_ILE82','hsg1:B:THR4']
    # OR
    #2. ARG8_ILE84
    for res_names_by_chain in names_by_chain:
        #check for ':'
Esempio n. 40
0
 def processLigand(self, ligand_file, percentCutoff=None, output=1, outputfilename=None, comment="USER  AD> ", buildHB=1, remove_modelStr=False):
     #if outputfilename is not None, have to (1) update all the strings or (2) rename ligand
     self.results = d = {}
     ligand = Read(ligand_file)
     assert isinstance(ligand, MoleculeSet)
     assert(len(ligand)==1)
     ligand = ligand[0]
     first = ligand.name.find('_model')
     last = ligand.name.rfind('_model')
     if first!=last:
         ligand.name = ligand.name[:last]
     if remove_modelStr:
         curName = ligand.name
         modelIndex=curName.find("_model")
         if modelIndex>-1:
             curName = curName[:modelIndex]
         #setup outputfilestem
         ligand.name = curName
     ligand.buildBondsByDistance()
     if not percentCutoff:
         percentCutoff = self.percentCutoff
     # first detect sets of atoms forming hydrogen bonds
     # hbondStr,hblist and has_hbonds added to process vina results which do not include valid hydrogen bonds
     hbondStr = ""
     hblist = [""]
     has_hbonds = False
     if buildHB:
         has_hbonds = True
         hbondStr = self.buildHydrogenBonds(ligand, comment=comment)           #
         if self.verbose: print("hbondStr=", hbondStr)
         hblist = hbondStr.split('\n') # hbond info
         if hblist[0]=='lig_hb_atoms : 0':
             has_hbonds = False
     # next detect sets of atoms in close contact not forming hydrogen bonds
     macrocloseContactStr, ligcloseContactStr = self.buildCloseContactAtoms(percentCutoff, ligand, comment=comment)              #
     self.piResults = ""
     if self.detect_pi: 
         self.detectPiInteractions()
         if self.results['pi_cation']:
             self.piResults = self.get_pi_cation_result(print_ctr=1, comment=comment)
             if self.verbose: 
                 print("found pi_cation in ", ligand_file)
                 print("set self.piResults to ", self.piResults)
         if self.results['pi_pi']:
             self.piResults += self.get_pi_pi(print_ctr=1, comment=comment)
             if self.verbose: 
                 print("set self.piResults to ", self.piResults)
     macro_cclist = macrocloseContactStr.split(';')
     lig_cclist = ligcloseContactStr.split(';')
     if has_hbonds or len(macro_cclist):
         fptr = open(ligand_file)
         lines = fptr.readlines()
         fptr.close()
         if outputfilename is not None:
             optr = open(outputfilename, 'w')
         else:
             optr = open(ligand_file, 'w')
         for new_l in hblist:
             if not(len(new_l)): #don't output empty lines
                 continue
             if new_l.find(comment)!=0:
                 new_l = comment + new_l
             if new_l != hblist[-1]:
                 optr.write(new_l+"\n")
             else:
                 optr.write(new_l) # no newline after the last one
         for new_l in macro_cclist:
             if not(len(new_l)): #don't output empty lines
                 continue
             if new_l.find(comment)!=0:
                 new_l = comment + new_l
             if new_l != macro_cclist[-1]:
                 optr.write(new_l + "\n")
             else:
                 optr.write(new_l)
         for new_l in lig_cclist:
             if not(len(new_l)): #don't output empty lines
                 continue
             if new_l.find(comment)!=0:
                 new_l = comment + new_l
             if new_l != lig_cclist[-1]:
                 optr.write(new_l + "\n")
             else:
                 optr.write(new_l)
         if len(self.piResults): ##???
             for s in self.piResults.split("\n"):
                 optr.write(s+"\n")
         for l in lines:
             optr.write(l)
         optr.close()
     return hbondStr + macrocloseContactStr + ligcloseContactStr
Esempio n. 41
0
def autodock_scoring(receptor, ligand):
    receptorfilename = receptor
    ligandfilename = ligand
    write_file_mode = False
    outputfilename = dirname + '/Alanine_Scanning_Binding_Energies_Result.csv'
    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()
    rec_non_std = ""

    non_std_types = check_types(receptor, supported_types)

    #Checking the format of receptor
    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

    ligand = Read(ligandfilename)[0]
    ligand.buildBondsByDistance()
    lig_non_std = ""
    non_std_types = check_types(ligand, supported_types)

    #Checking the format of ligand
    if len(non_std_types):
        lig_non_std = non_std_types[0]
        if len(non_std_types) > 1:
            for t in non_std_types[1:]:
                lig_non_std = lig_non_std + '_' + t

    mode = 'a'

    first = not os.path.exists(outputfilename)
    if write_file_mode:
        mode = 'w'
        first = True

    optr = open(outputfilename, mode)

    if first:
        tstr = "Receptor,Ligand,AutoDock4.1Score,estat,hb,vdw,dsolv,tors\n"
        optr.write(tstr)

    #setup the molecular system
    ostr = ""

    if len(lig_non_std):
        ostr = 'ERROR: unable to score ligand "%s" due to presence of non-standard atom type(s): %s\n' % (
            ligand.name, lig_non_std)
        optr.write(ostr)

    elif len(rec_non_std):
        ostr = 'ERROR: unable to score receptor "%s" due to non-standard atom type(s): %s\n' % (
            receptor.name, rec_non_std)
        optr.write(ostr)

    else:
        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
        ostr = "%19s,%3s,%8.4f,%6.4f,%6.4f,%6.4f,%6.4f,%6.4f\n" % (
            receptor.name, uniq_ligand[0], score, estat, hb, vdw, dsolv,
            torsEnrg)
        optr.write(ostr)

    optr.close()
Esempio n. 42
0
    if not receptor_file:
        print(
            'score_docked_atoms_by_component: receptor filename must be specified.'
        )
        usage()
        sys.exit()

    if not ligand_file:
        print(
            'score_docked_atoms_by_component: ligand file must be specified.')
        usage()
        sys.exit()

    #1: create the python molecules
    rec = Read(receptor_file)[0]
    recbnds = rec.buildBondsByDistance()
    lig = Read(ligand_file)[0]
    ligbnds = lig.buildBondsByDistance()

    #2: setup python scorers for your molecules:
    ms = MolecularSystem()
    ms.add_entities(rec.allAtoms)
    ms.add_entities(lig.allAtoms)

    #3: setup python scorers
    scorer = AutoDock41Scorer()
    scorer.set_molecular_system(ms)
    estat_scores = numpy.add.reduce(scorer.terms[0][0].get_score_array())
    dsolv_scores = numpy.add.reduce(scorer.terms[1][0].get_score_array())
    vdw_scores = numpy.add.reduce(scorer.terms[2][0].get_score_array())
    hbond_scores = numpy.add.reduce(scorer.terms[3][0].get_score_array())
    coords = ligAts.coords[:]
    atom_ct = len(ligAts)
    torsion_ct = len(ligMol.torTree.torsionMap)
    tors_penalty = torsion_ct * 0.2744

    cl = Clusterer(d.ch.conformations)
    d.clusterer = cl
    cl.make_clustering(rms_tolerance)
    ref_coords = cl.clustering_dict[rms_tolerance][0][0].getCoords()[:]

    # for building hydrogen bonds or reporting energy breakdown
    # setup receptor:
    if build_hydrogen_bonds or report_energy_breakdown:
        ligMol.buildBondsByDistance()
        receptor = Read(receptor_filename)[0]
        receptor.buildBondsByDistance()
    if build_hydrogen_bonds:
        hbondBuilder = HydrogenBondBuilder()
    if report_energy_breakdown:
        ms = MolecularSystem()
        ms.add_entities(receptor.allAtoms)
        ms.add_entities(ligMol.allAtoms)
        adscorer = AutoDock4Scorer()
        adscorer.set_molecular_system(ms)

    mode = 'w'
    if append_to_outputfile:
        mode = 'a'
    fptr = open(outputfilename, mode)
    if mode=='w':
        if build_hydrogen_bonds and report_energy_breakdown:
 def processLigand(self, ligand_file, percentCutoff=None, output=1, outputfilename=None, comment="USER  AD> ", buildHB=1, remove_modelStr=False):
     #if outputfilename is not None, have to (1) update all the strings or (2) rename ligand
     self.results = d = {}
     ligand = Read(ligand_file)
     assert isinstance(ligand, MoleculeSet)
     assert(len(ligand)==1)
     ligand = ligand[0]
     first = ligand.name.find('_model')
     last = ligand.name.rfind('_model')
     if first!=last:
         ligand.name = ligand.name[:last]
     if remove_modelStr:
         curName = ligand.name
         modelIndex=curName.find("_model")
         if modelIndex>-1:
             curName = curName[:modelIndex]
         #setup outputfilestem
         ligand.name = curName
     ligand.buildBondsByDistance()
     if not percentCutoff:
         percentCutoff = self.percentCutoff
     # first detect sets of atoms forming hydrogen bonds
     # hbondStr,hblist and has_hbonds added to process vina results which do not include valid hydrogen bonds
     hbondStr = ""
     hblist = [""]
     has_hbonds = False
     if buildHB:
         has_hbonds = True
         hbondStr = self.buildHydrogenBonds(ligand, comment=comment)           #
         if self.verbose: print "hbondStr=", hbondStr
         hblist = hbondStr.split('\n') # hbond info
         if hblist[0]=='lig_hb_atoms : 0':
             has_hbonds = False
     # next detect sets of atoms in close contact not forming hydrogen bonds
     macrocloseContactStr, ligcloseContactStr = self.buildCloseContactAtoms(percentCutoff, ligand, comment=comment)              #
     self.piResults = ""
     if self.detect_pi: 
         self.detectPiInteractions()
         if self.results['pi_cation']:
             self.piResults = self.get_pi_cation_result(print_ctr=1, comment=comment)
             if self.verbose: 
                 print "found pi_cation in ", ligand_file
                 print "set self.piResults to ", self.piResults
         if self.results['pi_pi']:
             self.piResults += self.get_pi_pi(print_ctr=1, comment=comment)
             if self.verbose: 
                 print "set self.piResults to ", self.piResults
     macro_cclist = macrocloseContactStr.split(';')
     lig_cclist = ligcloseContactStr.split(';')
     if has_hbonds or len(macro_cclist):
         fptr = open(ligand_file)
         lines = fptr.readlines()
         fptr.close()
         if outputfilename is not None:
             optr = open(outputfilename, 'w')
         else:
             optr = open(ligand_file, 'w')
         for new_l in hblist:
             if not(len(new_l)): #don't output empty lines
                 continue
             if new_l.find(comment)!=0:
                 new_l = comment + new_l
             if new_l != hblist[-1]:
                 optr.write(new_l+"\n")
             else:
                 optr.write(new_l) # no newline after the last one
         for new_l in macro_cclist:
             if not(len(new_l)): #don't output empty lines
                 continue
             if new_l.find(comment)!=0:
                 new_l = comment + new_l
             if new_l != macro_cclist[-1]:
                 optr.write(new_l + "\n")
             else:
                 optr.write(new_l)
         for new_l in lig_cclist:
             if not(len(new_l)): #don't output empty lines
                 continue
             if new_l.find(comment)!=0:
                 new_l = comment + new_l
             if new_l != lig_cclist[-1]:
                 optr.write(new_l + "\n")
             else:
                 optr.write(new_l)
         if len(self.piResults): ##???
             for s in self.piResults.split("\n"):
                 optr.write(s+"\n")
         for l in lines:
             optr.write(l)
         optr.close()
     return hbondStr + macrocloseContactStr + ligcloseContactStr
Esempio n. 45
0
        print 'prepare_flexdocking4: ligand filename must be specified!\n'
        usage()
        sys.exit()

    if not receptor_filename:
        print 'prepare_flexdocking4: receptor filename must be specified!\n'
        usage()
        sys.exit()

    if not residues_to_move:
        print 'prepare_flexdocking4: residues to move must be specified!\n'
        usage()
        sys.exit()

    l = Read(ligand_filename)[0]
    l.buildBondsByDistance()
    if verbose: print 'read ', ligand_filename
    r = Read(receptor_filename)[0]
    r.buildBondsByDistance()
    if verbose: print 'read ', receptor_filename

    all_res = ResidueSet()
    res_names = residues_to_move.split('_')
    for n in res_names:
        if n.find(':') == -1:
            res = r.chains.residues.get(lambda x: x.name == n)
            all_res += res
            if verbose: print "get: adding ", res.name, " to ", all_res
        else:
            res, msg = CompoundStringSelector().select(ProteinSet([r]), n)
            all_res += res
Esempio n. 46
0
        if o in ('-v', '--v'):
            verbose = True
            if verbose: print 'set verbose to ', True
        if o in ('-h', '--'):
            usage()
            sys.exit()


    if not pdbqt_filename:
        print 'repair_ligand4: pdbqt_filename must be specified.'
        usage()
        sys.exit()

    mol = Read(pdbqt_filename)[0]
    if verbose: print 'read ', pdbqt_filename
    mol.buildBondsByDistance()
    mol.LPO = AD4LigandPreparation(mol, mode='interactive', repairs='', charges_to_add=None,
                root=0, outputfilename=outputfilename, cleanup='')
    #rebuild torTree
    allAts = mol.allAtoms
    for b in allAts.bonds[0]:
        if b.activeTors: b.activeTors = 0
    torscount = 0
    tM = mol.torTree.torsionMap
    for i in range(len(tM)):
        bnum0, bnum1 = tM[i].bond
        a0 = allAts.get(lambda x: x.number==bnum0 + 1)[0]
        a0.tt_ind = bnum0
        a1 = allAts.get(lambda x: x.number==bnum1 + 1)[0]
        a1.tt_ind = bnum1
        b = AtomSet([a0,a1]).bonds[0]
        sys.exit()
    if ligandfilename is None:
        print("trilinterp_atoms.py: ligand filename must be specified.")
        usage()
        sys.exit()
    #OPTIONAL:
    if mapstem is None and verbose:
        print("trilinterp_atoms.py: map stem set from receptorfilename")
    if outputfilename is None:
        if verbose: print("trilinterp_atoms.py: output to screen")
    else:
        print('writing output to %s' % outputfilename)

    #Start to work:
    rec = Read(receptorfilename)[0]
    rec.buildBondsByDistance()  #??@@??
    #setup mapstem
    if mapstem is None:
        mapstem = rec.name

    lig = Read(ligandfilename)[0]
    lig.buildBondsByDistance()
    #get atoms for trilinterp
    if indicies is None or indicies == '':
        indicies = list(range(len(lig.allAtoms)))
    else:
        indicies = list(map(int, indicies.split(',')))
    if verbose: print("now indicies=", indicies)

    total = 0
    pts = []
class BaseTests(unittest.TestCase):

    def setUp(self):
        self.mol = Read('Data/1crn.pdb')[0]
        self.mol.buildBondsByDistance()
    

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


    def test_gasteiger_calc_constructor(self):
        """
        instantiate an GasteigerChargeCalculator
        """
        g_calc = GasteigerChargeCalculator()
        self.assertEquals(g_calc.__class__, GasteigerChargeCalculator)


    def test_gasteiger_calc_addCharges(self):
        """
         GasteigerChargeCalculator addCharges to each atom, giving expected total
        """
        atlen = len(self.mol.allAtoms)
        g_calc = GasteigerChargeCalculator()
        g_calc.addCharges(self.mol.allAtoms)
        g_ats = self.mol.allAtoms.get(lambda x: x.chargeSet=='gasteiger') 
        self.assertEquals(atlen, len(g_ats))
        total_charge = Numeric.add.reduce(self.mol.allAtoms.charge)
        self.assertAlmostEquals(total_charge, 1.221245e-15, 6)


    def test_kollman_calc_constructor(self):
        """
        instantiate an KollmanChargeCalculator
        """
        k_calc = KollmanChargeCalculator()
        self.assertEquals(k_calc.__class__, KollmanChargeCalculator)


    def test_Kollman_calc_addCharges(self):
        """
         KollmanChargeCalculator addCharges to each atom, giving expected total
        """
        atlen = len(self.mol.allAtoms)
        k_calc = KollmanChargeCalculator()
        k_calc.addCharges(self.mol.allAtoms)
        k_ats = self.mol.allAtoms.get(lambda x: x.chargeSet=='Kollman') 
        self.assertEquals(atlen, len(k_ats))
        total_charge = Numeric.add.reduce(self.mol.allAtoms.charge)
        self.assertAlmostEquals(total_charge, -19.554, 4)


    def test_Kollman_calc_from_bug(self):
        """
         test KollmanChargeCalculator can add charges to 1a30
        """
        mol = Read("Data/1a30.pdb")[0]
        atlen = len(mol.allAtoms)
        k_calc = KollmanChargeCalculator()
        k_calc.addCharges(mol.allAtoms)
        k_ats = mol.allAtoms.get(lambda x: x.chargeSet=='Kollman') 
        self.assertEquals(atlen, len(k_ats))
        total_charge = Numeric.add.reduce(mol.allAtoms.charge)
        self.assertAlmostEquals(total_charge, 5.7060, 4)
Esempio n. 49
0
                print 'set output outputfilename to ', a
        if o in ('-v', '--v'):
            verbose = True
            if verbose: print 'set verbose to ', True
        if o in ('-h', '--'):
            usage()
            sys.exit()

    if not pdbqt_filename:
        print 'repair_ligand4: pdbqt_filename must be specified.'
        usage()
        sys.exit()

    mol = Read(pdbqt_filename)[0]
    if verbose: print 'read ', pdbqt_filename
    mol.buildBondsByDistance()
    mol.LPO = AD4LigandPreparation(mol,
                                   mode='interactive',
                                   repairs='',
                                   charges_to_add=None,
                                   root=0,
                                   outputfilename=outputfilename,
                                   cleanup='')
    #rebuild torTree
    allAts = mol.allAtoms
    for b in allAts.bonds[0]:
        if b.activeTors: b.activeTors = 0
    torscount = 0
    tM = mol.torTree.torsionMap
    for i in range(len(tM)):
        bnum0, bnum1 = tM[i].bond
class BondSelectorBaseTests(unittest.TestCase):
    def setUp(self):
        from MolKit import Read
        self.mol = Read('Data/1crn_2.pdb')[0]
        self.mol.buildBondsByDistance()

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

    def test_constructor(self):
        """
        instantiate an BondSelector
        """
        bndSel = BondSelector()
        self.assertEquals(bndSel.__class__, BondSelector)

    def test_constructorOptions(self):
        """
         test possible constructor options
            options = [lambda x: cond1, lambda x: cond2...]
        """

        bndSel = BondSelector([lambda x: x])
        self.assertEquals(bndSel.__class__, BondSelector)

    def test_select_with_no_bonds(self):
        """
         test select with no input bonds
        """
        bndSel = BondSelector([lambda x: x])
        bndSel.select()
        #clean-up

    def test_select_with_no_criteria(self):
        """
         test select with no screening criteria
        """
        bndSel = BondSelector()
        ats = self.mol.allAtoms[:10]
        bnds = ats.bonds[0]
        bndSel.select(bnds)

    def test_select_no_bonds(self):
        """
         test select with criteria which selects no bonds
        """
        bndSel = BondSelector([lambda x: x.atom1.number == 2000])
        ats = self.mol.allAtoms[:10]
        bnds = ats.bonds[0]
        resultBnds = bndSel.select(bnds)
        self.assertEqual(len(resultBnds), 0)

    def test_select_one_bond(self):
        """
         test select with criteria which selects one bond
        """
        bndSel = BondSelector([lambda x: x.atom1.number == 1])
        ats = self.mol.allAtoms[:10]
        bnds = ats.bonds[0]
        resultBnds = bndSel.select(bnds)
        #self.assertEqual(len(resultBnds) , 1)
        self.assertEqual(len(resultBnds), 3)

    def test_select_three_bonds(self):
        """
         test select with criteria which selects some bonds
        """
        bndSel = BondSelector(
            [lambda x: x.atom1.number == 1 or x.atom1.number == 2])
        ats = self.mol.allAtoms[:10]
        bnds = ats.bonds[0]
        resultBnds = bndSel.select(bnds)
        #print "len(resultBnds)=", len(resultBnds)
        #self.assertEqual(len(resultBnds) , 3)
        self.assertEqual(len(resultBnds), 5)

    def test_select_all_bonds(self):
        """
         test select with criteria which selects all bonds
        """
        bndSel = BondSelector([lambda x: x])
        ats = self.mol.allAtoms[:10]
        bnds = ats.bonds[0]
        resultBnds = bndSel.select(bnds)
        self.assertEqual(len(resultBnds), len(bnds))

    def test_select_two_criteria(self):
        """
         test select with two criteria, result is sum 
        """
        bndSel = BondSelector([lambda x:x.atom1.number==1, lambda x:\
                    x.atom1.number==2])
        ats = self.mol.allAtoms[:10]
        bnds = ats.bonds[0]
        resultBnds = bndSel.select(bnds)
        #self.assertEqual(len(resultBnds) , 3)
        self.assertEqual(len(resultBnds), 5)

    def test_select_three_criteria(self):
        """
         test select with three criteria, result is sum 
        """
        bndSel = BondSelector([lambda x:x.atom1.number==1, lambda x:\
                    x.atom1.number==2,lambda x:x.atom1.name=='CA'])
        ats = self.mol.allAtoms[:10]
        bnds = ats.bonds[0]
        resultBnds = bndSel.select(bnds)
        #print 'len(resultBnds)==', len(resultBnds)
        #self.assertEqual(len(resultBnds) , 4)
        self.assertEqual(len(resultBnds), 5)

    def test_BondBranchBondSelector_constructor(self):
        """
         test BondBranch constructor
        """
        bndLenSel = BondBranchBondSelector(2)
        self.assertEqual(bndLenSel.__class__, BondBranchBondSelector)

    def test_BondBranchBondSelector_select_no_bnds(self):
        """
         test BondBranch select: no bonds
        """
        bndSel = BondBranchBondSelector(2)
        ats = self.mol.allAtoms[0:5]
        bnds = ats.bonds[0]
        resultBnds = bndSel.select(bnds)
        #print 'no_bnds:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds), 0)

    def test_BondBranchBondSelector_select_some_bnds(self):
        """
         test BondBranch select: some bonds
        """
        bndSel = BondBranchBondSelector(2)
        ats = self.mol.allAtoms[:10]
        bnds = ats.bonds[0]
        resultBnds = bndSel.select(bnds)
        #print 'some_bnds:len(resultBnds)=', len(resultBnds)
        #self.assertEqual(len(resultBnds) , 1)
        self.assertEqual(len(resultBnds), 2)

    def test_BondBranchBondSelector_select_all_bnds(self):
        """
         test BondBranch select: all bonds
        """
        bndSel = BondBranchBondSelector(2)
        ats = self.mol.allAtoms
        bnds = ats.bonds[0]
        resultBnds = bndSel.select(bnds)
        #print 'all_bnds:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds), 120)

    def test_BondElementBondSelector_constructor(self):
        """
         test BondElement constructor
        """
        bndLenSel = BondElementBondSelector('C')
        self.assertEqual(bndLenSel.__class__, BondElementBondSelector)

    def test_BondElementBondSelector_select_no_bnds(self):
        """
         test BondElement select: no bonds
        """
        bndSel = BondElementBondSelector('P')
        ats = self.mol.allAtoms
        bnds = ats.bonds[0]
        resultBnds = bndSel.select(bnds)
        #print 'no_bnds:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds), 0)

    def test_BondElementBondSelector_select_some_bnds(self):
        """
         test BondElement select: some bonds
        """
        bndSel = BondElementBondSelector('C')
        ats = self.mol.allAtoms[:10]
        bnds = ats.bonds[0]
        resultBnds = bndSel.select(bnds)
        #print 'some_bnds:len(resultBnds)=', len(resultBnds)
        #self.assertEqual(len(resultBnds) , 9)
        self.assertEqual(len(resultBnds), 6)

    def test_BondElementBondSelector_select_all_bnds(self):
        """
         test BondElement select: all bonds
        """
        bndSel = BondElementBondSelector('C')
        ats = self.mol.allAtoms
        bnds = ats.bonds[0]
        resultBnds = bndSel.select(bnds)
        #print 'all_bnds:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds), 334)

    def test_LeafBondSelector_constructor(self):
        """
         test LeafBond constructor
        """
        leafBndSel = LeafBondSelector()
        self.assertEqual(leafBndSel.__class__, LeafBondSelector)

    def test_LeafBondSelector_select_no_leaves(self):
        """
         test LeafBond select: no bonds
        """
        leafBndSel = LeafBondSelector()
        ats = self.mol.allAtoms[7:10]
        bnds = ats.bonds[0]
        resultBnds = leafBndSel.select(bnds)
        #print 'no_leaves:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds), 0)

    def test_LeafBondSelector_select_some_leaves(self):
        """
         test LeafBond select: some bonds
        """
        leafBndSel = LeafBondSelector()
        ats = self.mol.allAtoms[:10]
        bnds = ats.bonds[0]
        resultBnds = leafBndSel.select(bnds)
        #print 'some_leaves:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds), 2)
        #self.assertEqual(len(resultBnds) , 5)

    def test_LeafBondSelector_select_all_leaves(self):
        """
         test LeafBond select: all bonds
        """
        leafBndSel = LeafBondSelector()
        ats = self.mol.allAtoms
        bnds = ats.bonds[0]
        resultBnds = leafBndSel.select(bnds)
        #print 'all_leaves:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds), 150)

    def test_HydrogenRotatorBondSelector_constructor(self):
        """
         test HydrogenRotator constructor
        """
        hrBndSel = HydrogenRotatorBondSelector()
        self.assertEqual(hrBndSel.__class__, HydrogenRotatorBondSelector)

    def test_HydrogenRotatorBondSelector_select_none(self):
        """
         test HydrogenRotator select: no bonds
        """
        HRSel = HydrogenRotatorBondSelector()
        ats = self.mol.allAtoms[2:6]
        bnds = ats.bonds[0]
        resultBnds = HRSel.select(bnds)
        #print 'no_hydrogenrotators:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds), 0)

    def test_HydrogenRotatorBondSelector_select_some(self):
        """
         test HydrogenRotator select: some bonds
        """
        HRSel = HydrogenRotatorBondSelector()
        ats = self.mol.chains.residues[:8].atoms
        bnds = ats.bonds[0]
        resultBnds = HRSel.select(bnds)
        #print 'some_hydrogenrotators:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds), 4)

    def test_HydrogenRotatorBondSelector_select_all(self):
        """
         test HydrogenRotator select: all bonds
        """
        HRSel = HydrogenRotatorBondSelector()
        ats = self.mol.allAtoms
        bnds = ats.bonds[0]
        resultBnds = HRSel.select(bnds)
        #print 'all_hydrogenrotators:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds), 18)

    def test_AmideBondSelector_constructor(self):
        """
         test AmideBond constructor
        """
        amBndSel = AmideBondSelector()
        self.assertEqual(amBndSel.__class__, AmideBondSelector)

    def test_AmideBondSelector_select_none(self):
        """
         test AmideBond select: no bonds
        """
        from MolKit.bondSelector import AmideBondSelector
        amBndSel = AmideBondSelector()
        ats = self.mol.allAtoms[0:2]
        bnds = ats.bonds[0]
        resultBnds = amBndSel.select(bnds)
        #print 'no_amidebonds:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds), 0)

    def test_AmideBondSelector_select_some(self):
        """
         test AmideBond select: some bonds
        """
        amBndSel = AmideBondSelector()
        ats = self.mol.allAtoms[:50]
        bnds = ats.bonds[0]
        resultBnds = amBndSel.select(bnds)
        #print 'some_amidebonds:len(resultBnds)=', len(resultBnds)
        #self.assertEqual(len(resultBnds) , 7)
        self.assertEqual(len(resultBnds), 6)

    def test_AmideBondSelector_select_all(self):
        """
         test AmideBond select: all bonds
        """
        amBndSel = AmideBondSelector()
        ats = self.mol.allAtoms
        bnds = ats.bonds[0]
        resultBnds = amBndSel.select(bnds)
        #print 'all_amidebonds:len(resultBnds)=', len(resultBnds)
        #assert len(resultBnds) == 2
        self.assertEqual(len(resultBnds), 48)

    def test_PeptideBackBoneBondSelector_constructor(self):
        """
         test PetideBackBone constructor
        """
        ppbbSel = PeptideBackBoneBondSelector()
        self.assertEqual(ppbbSel.__class__, PeptideBackBoneBondSelector)

    def test_PeptideBackBoneBondSelector_select_none(self):
        """
         test PetideBackBone select: no bonds
        """
        ppbbSel = PeptideBackBoneBondSelector()
        ats = self.mol.allAtoms[4:8]
        bnds = ats.bonds[0]
        resultBnds = ppbbSel.select(bnds)
        #print 'no_ppbbbonds:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds), 0)

    def test_PeptideBackBoneBondSelector_select_some(self):
        """
         test PetideBackBone select: some bonds
        """
        ppbbSel = PeptideBackBoneBondSelector()
        ats = self.mol.allAtoms[:50]
        bnds = ats.bonds[0]
        resultBnds = ppbbSel.select(bnds)
        #print 'some_ppbbbonds:len(resultBnds)=', len(resultBnds)
        #self.assertEqual(len(resultBnds) , 22)
        self.assertEqual(len(resultBnds), 17)

    def test_PeptideBackBoneBondSelector_select_all(self):
        """
         test PetideBackBone select: all bonds
        """
        ppbbSel = PeptideBackBoneBondSelector()
        ats = self.mol.allAtoms
        bnds = ats.bonds[0]
        resultBnds = ppbbSel.select(bnds)
        #print 'all_ppbbbonds:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds), 132)

    def test_CycleBondSelector_constructor(self):
        """
         test CycleBondSelector constructor
        """
        cbSel = CycleBondSelector()
        self.assertEqual(cbSel.__class__, CycleBondSelector)

    def test_CycleBondSelector_select_none(self):
        """
         test CycleBondSelector select: no bonds
        """
        cbSel = CycleBondSelector()
        ats = self.mol.allAtoms[4:8]
        bnds = ats.bonds[0]
        resultBnds = cbSel.select(bnds)
        #print 'no_cb_bonds:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds), 0)

    def test_CycleBondSelector_select_some(self):
        """
         test CycleBondSelector select: some bonds
        """
        cbSel = CycleBondSelector()
        ats = self.mol.allAtoms[:50]
        bnds = ats.bonds[0]

    def test_BondElementBondSelector_select_all_bnds(self):
        """
         test BondElement select: all bonds
        """
        bndSel = BondElementBondSelector('C')
        ats = self.mol.allAtoms
        bnds = ats.bonds[0]
        resultBnds = bndSel.select(bnds)
        #print 'all_bnds:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds), 334)

    def test_LeafBondSelector_constructor(self):
        """
         test LeafBond constructor
        """
        leafBndSel = LeafBondSelector()
        self.assertEqual(leafBndSel.__class__, LeafBondSelector)

    def test_LeafBondSelector_select_no_leaves(self):
        """
         test LeafBond select: no bonds
        """
        leafBndSel = LeafBondSelector()
        ats = self.mol.allAtoms[7:10]
        bnds = ats.bonds[0]
        resultBnds = leafBndSel.select(bnds)
        #print 'no_leaves:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds), 0)

    def test_LeafBondSelector_select_some_leaves(self):
        """
         test LeafBond select: some bonds
        """
        leafBndSel = LeafBondSelector()
        ats = self.mol.allAtoms[:10]
        bnds = ats.bonds[0]
        resultBnds = leafBndSel.select(bnds)
        #print 'some_leaves:len(resultBnds)=', len(resultBnds)
        #self.assertEqual(len(resultBnds) , 2)
        self.assertEqual(len(resultBnds), 5)

    def test_LeafBondSelector_select_all_leaves(self):
        """
         test LeafBond select: all bonds
        """
        leafBndSel = LeafBondSelector()
        ats = self.mol.allAtoms
        bnds = ats.bonds[0]
        resultBnds = leafBndSel.select(bnds)
        #print 'all_leaves:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds), 150)

    def test_HydrogenRotatorBondSelector_constructor(self):
        """
         test HydrogenRotator constructor
        """
        hrBndSel = HydrogenRotatorBondSelector()
        self.assertEqual(hrBndSel.__class__, HydrogenRotatorBondSelector)

    def test_HydrogenRotatorBondSelector_select_none(self):
        """
         test HydrogenRotator select: no bonds
        """
        HRSel = HydrogenRotatorBondSelector()
        ats = self.mol.allAtoms[2:6]
        bnds = ats.bonds[0]
        resultBnds = HRSel.select(bnds)
        #print 'no_hydrogenrotators:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds), 0)

    def test_HydrogenRotatorBondSelector_select_some(self):
        """
         test HydrogenRotator select: some bonds
        """
        HRSel = HydrogenRotatorBondSelector()
        ats = self.mol.chains.residues[:8].atoms
        bnds = ats.bonds[0]
        resultBnds = HRSel.select(bnds)
        #print 'some_hydrogenrotators:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds), 4)

    def test_HydrogenRotatorBondSelector_select_all(self):
        """
         test HydrogenRotator select: all bonds
        """
        HRSel = HydrogenRotatorBondSelector()
        ats = self.mol.allAtoms
        bnds = ats.bonds[0]
        resultBnds = HRSel.select(bnds)
        #print 'all_hydrogenrotators:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds), 18)

    def test_AmideBondSelector_constructor(self):
        """
         test AmideBond constructor
        """
        amBndSel = AmideBondSelector()
        self.assertEqual(amBndSel.__class__, AmideBondSelector)

    def test_AmideBondSelector_select_none(self):
        """
         test AmideBond select: no bonds
        """
        from MolKit.bondSelector import AmideBondSelector
        amBndSel = AmideBondSelector()
        ats = self.mol.allAtoms[0:2]
        bnds = ats.bonds[0]
        resultBnds = amBndSel.select(bnds)
        #print 'no_amidebonds:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds), 0)

    def test_AmideBondSelector_select_some(self):
        """
         test AmideBond select: some bonds
        """
        amBndSel = AmideBondSelector()
        ats = self.mol.allAtoms[:50]
        bnds = ats.bonds[0]
        resultBnds = amBndSel.select(bnds)
        #print 'some_amidebonds:len(resultBnds)=', len(resultBnds)
        #self.assertEqual(len(resultBnds) , 7)
        self.assertEqual(len(resultBnds), 6)

    def test_AmideBondSelector_select_all(self):
        """
         test AmideBond select: all bonds
        """
        amBndSel = AmideBondSelector()
        ats = self.mol.allAtoms
        bnds = ats.bonds[0]
        resultBnds = amBndSel.select(bnds)
        #print 'all_amidebonds:len(resultBnds)=', len(resultBnds)
        #assert len(resultBnds) == 2
        self.assertEqual(len(resultBnds), 48)

    def test_PeptideBackBoneBondSelector_constructor(self):
        """
         test PetideBackBone constructor
        """
        ppbbSel = PeptideBackBoneBondSelector()
        self.assertEqual(ppbbSel.__class__, PeptideBackBoneBondSelector)

    def test_PeptideBackBoneBondSelector_select_none(self):
        """
         test PetideBackBone select: no bonds
        """
        ppbbSel = PeptideBackBoneBondSelector()
        ats = self.mol.allAtoms[4:8]
        bnds = ats.bonds[0]
        resultBnds = ppbbSel.select(bnds)
        #print 'no_ppbbbonds:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds), 0)

    def test_PeptideBackBoneBondSelector_select_some(self):
        """
         test PetideBackBone select: some bonds
        """
        ppbbSel = PeptideBackBoneBondSelector()
        ats = self.mol.allAtoms[:50]
        bnds = ats.bonds[0]
        resultBnds = ppbbSel.select(bnds)
        #print 'some_ppbbbonds:len(resultBnds)=', len(resultBnds)
        #self.assertEqual(len(resultBnds) , 22)
        self.assertEqual(len(resultBnds), 17)

    def test_PeptideBackBoneBondSelector_select_all(self):
        """
         test PetideBackBone select: all bonds
        """
        ppbbSel = PeptideBackBoneBondSelector()
        ats = self.mol.allAtoms
        bnds = ats.bonds[0]
        resultBnds = ppbbSel.select(bnds)
        #print 'all_ppbbbonds:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds), 132)

    def test_CycleBondSelector_constructor(self):
        """
         test CycleBondSelector constructor
        """
        cbSel = CycleBondSelector()
        self.assertEqual(cbSel.__class__, CycleBondSelector)

    def test_CycleBondSelector_select_none(self):
        """
         test CycleBondSelector select: no bonds
        """
        cbSel = CycleBondSelector()
        ats = self.mol.allAtoms[4:8]
        bnds = ats.bonds[0]
        resultBnds = cbSel.select(bnds)
        #print 'no_cb_bonds:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds), 0)

    def test_CycleBondSelector_select_some(self):
        """
         test CycleBondSelector select: some bonds
        """
        cbSel = CycleBondSelector()
        ats = self.mol.allAtoms[:50]
        bnds = ats.bonds[0]
        resultBnds = cbSel.select(bnds)
        #print 'some_cb_bonds:len(resultBnds)=', len(resultBnds)
        #self.assertEqual(len(resultBnds) , 5)
        #because of di-sulfide bridges:
        #when increase RingFinder parameter "maxSize"
        self.assertEqual(len(resultBnds), 42)

    def test_CycleBondSelector_select_all(self):
        """
         test CycleBondSelector select: all bonds
        """
        cbSel = CycleBondSelector()
        ats = self.mol.allAtoms
        bnds = ats.bonds[0]
        resultBnds = cbSel.select(bnds)
        #print 'all_cb_bonds:len(resultBnds)=', len(resultBnds)
        #self.assertEqual(len(resultBnds) , 43)
        #because of di-sulfide bridges:
        #when increase RingFinder parameter "maxSize"
        self.assertEqual(len(resultBnds), 165)

    def test_BondOrderBondSelector(self):
        """
         test BondOrder constructor
        """
        bobSel = BondOrderBondSelector()
        self.assertEqual(bobSel.__class__, BondOrderBondSelector)

    def test_BondOrderBondSelector_select_none(self):
        """
         test BondOrder select: no bonds
        """
        bobSel = BondOrderBondSelector()
        ats = self.mol.allAtoms[4:8]
        bnds = ats.bonds[0]
        resultBnds = bobSel.select(bnds)
        #print 'no_cb_bonds:len(resultBnds)=', len(resultBnds)
        #self.assertEqual(len(resultBnds) , 2)
        self.assertEqual(len(resultBnds), 3)

    def test_BondOrderBondSelector_select_some(self):
        """
         test BondOrder select: some bonds
        """
        bobSel = BondOrderBondSelector()
        ats = self.mol.allAtoms[:50]
        bnds = ats.bonds[0]
        resultBnds = bobSel.select(bnds)
        #print 'some_cb_bonds:len(resultBnds)=', len(resultBnds)
        #self.assertEqual(len(resultBnds) , 43)
        self.assertEqual(len(resultBnds), 44)

    def test_BondOrderBondSelector_select_all(self):
        """
         test BondOrder select: all bonds
        """
        bobSel = BondOrderBondSelector()
        ats = self.mol.allAtoms
        bnds = ats.bonds[0]
        resultBnds = bobSel.select(bnds)
        #print 'all_cb_bonds:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds), 341)

    def test_RotatableBondSelector_constructor(self):
        """
         test RotatableBond constructor
        """
        rotSel = RotatableBondSelector()
        self.assertEqual(rotSel.__class__, RotatableBondSelector)

    def test_RotatableBondSelector_select_none(self):
        """
         test RotatableBond select: no bonds
        """
        rotSel = RotatableBondSelector()
        ats = self.mol.allAtoms[4:8]
        bnds = ats.bonds[0]
        resultBnds = rotSel.select(bnds)
        #print 'no_cb_bonds:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds), 1)

    def test_RotatableBondSelector_select_some(self):
        """
         test RotatableBond select: some bonds
        """
        rotSel = RotatableBondSelector()
        ats = self.mol.allAtoms[:50]
        bnds = ats.bonds[0]
        resultBnds = rotSel.select(bnds)
        #print 'some_cb_bonds:len(resultBnds)=', len(resultBnds)
        #self.assertEqual(len(resultBnds) , 34)
        #because of disulfide bridges-> large cycles
        #self.assertEqual(len(resultBnds) , 27)
        self.assertEqual(len(resultBnds), 20)

    def test_RotatableBondSelector_select_all(self):
        """
         test RotatableBond select: all bonds
        """
        rotSel = RotatableBondSelector()
        ats = self.mol.allAtoms
        bnds = ats.bonds[0]
        resultBnds = rotSel.select(bnds)
        #print 'all_cb_bonds:len(resultBnds)=', len(resultBnds)
        #self.assertEqual(len(resultBnds) , 211)
        #because of disulfide bridges-> large cycles
        self.assertEqual(len(resultBnds), 89)

    def test_GuanidiniumBondSelector_select_all(self):
        """
         test GuanidiniumBond select: all bonds
        """
        guanSel = GuanidiniumBondSelector()
        ats = self.mol.allAtoms
        bnds = ats.bonds[0]
        resultBnds = guanSel.select(bnds)
        #print 'all_guanidinium_bonds:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds), 6)
        for b in resultBnds:
            self.assertEqual(b.atom1.parent.type, 'ARG')
            if b.atom1.element == 'C':
                self.assertEqual(b.atom1.name, 'CZ')
            if b.atom1.element == 'N':
                self.assertEqual(b.atom1.name in ['NE', 'NH1', 'NH2'], True)

    def test_PeptideAromaticCycleBondSelector_select_all(self):
        """
         test PeptideAromaticCycleBond select: all aromatic bonds in 1crn
        """
        PABS = PeptideAromaticCycleBondSelector()
        ats = self.mol.allAtoms
        bnds = ats.bonds[0]
        resultBnds = PABS.select(bnds)
        self.assertEqual(len(resultBnds), 18)

    def test_PeptideAromaticCycleBondSelector_select_some(self):
        """
         test PeptideAromaticCycleBond select: 6 bonds
        """
        PABS = PeptideAromaticCycleBondSelector()
        bnds = self.mol.chains.residues[:21].atoms.bonds[0]  #includes 1 PHE
        resultBnds = PABS.select(bnds)
        self.assertEqual(len(resultBnds), 6)

    def test_PeptideAromaticCycleBondSelector_labels_aromatic_bnds(self):
        """
         test PeptideAromaticCycleBond labels aromatic bnds
        """
        PABS = PeptideAromaticCycleBondSelector()
        bnds = self.mol.chains.residues.atoms.bonds[0]
        resultBnds = PABS.select(bnds)
        for b in resultBnds:
            self.assertEqual(hasattr(b, 'aromatic'), True)
Esempio n. 51
0
class BondSelectorBaseTests(unittest.TestCase):
    def setUp(self):
        from MolKit import Read
        self.mol = Read('Data/1crn_2.pdb')[0]
        self.mol.buildBondsByDistance()
    

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


    def test_constructor(self):
        """
        instantiate an BondSelector
        """
        bndSel = BondSelector()
        self.assertEquals(bndSel.__class__, BondSelector)


    def test_constructorOptions(self):
        """
         test possible constructor options
            options = [lambda x: cond1, lambda x: cond2...]
        """
    
        bndSel = BondSelector([lambda x: x])
        self.assertEquals(bndSel.__class__, BondSelector)


    def test_select_with_no_bonds(self):
        """
         test select with no input bonds
        """
        bndSel = BondSelector([lambda x:x])
        bndSel.select()
        #clean-up


    def test_select_with_no_criteria(self):
        """
         test select with no screening criteria
        """
        bndSel = BondSelector()
        ats = self.mol.allAtoms[:10]
        bnds = ats.bonds[0]
        bndSel.select(bnds)


    def test_select_no_bonds(self):
        """
         test select with criteria which selects no bonds
        """
        bndSel = BondSelector([lambda x:x.atom1.number==2000])
        ats = self.mol.allAtoms[:10]
        bnds = ats.bonds[0]
        resultBnds = bndSel.select(bnds)
        self.assertEqual(len(resultBnds) , 0)


    def test_select_one_bond(self):
        """
         test select with criteria which selects one bond
        """
        bndSel = BondSelector([lambda x:x.atom1.number==1])
        ats = self.mol.allAtoms[:10]
        bnds = ats.bonds[0]
        resultBnds = bndSel.select(bnds)
        #self.assertEqual(len(resultBnds) , 1)
        self.assertEqual(len(resultBnds) , 3)


    def test_select_three_bonds(self):
        """
         test select with criteria which selects some bonds
        """
        bndSel = BondSelector([lambda x:x.atom1.number==1 or x.atom1.number==2])
        ats = self.mol.allAtoms[:10]
        bnds = ats.bonds[0]
        resultBnds = bndSel.select(bnds)
        #print "len(resultBnds)=", len(resultBnds)
        #self.assertEqual(len(resultBnds) , 3)
        self.assertEqual(len(resultBnds) , 5)


    def test_select_all_bonds(self):
        """
         test select with criteria which selects all bonds
        """
        bndSel = BondSelector([lambda x:x])
        ats = self.mol.allAtoms[:10]
        bnds = ats.bonds[0]
        resultBnds = bndSel.select(bnds)
        self.assertEqual(len(resultBnds) , len(bnds))


    def test_select_two_criteria(self):
        """
         test select with two criteria, result is sum 
        """
        bndSel = BondSelector([lambda x:x.atom1.number==1, lambda x:\
                    x.atom1.number==2])
        ats = self.mol.allAtoms[:10]
        bnds = ats.bonds[0]
        resultBnds = bndSel.select(bnds)
        #self.assertEqual(len(resultBnds) , 3)
        self.assertEqual(len(resultBnds) , 5)


    def test_select_three_criteria(self):
        """
         test select with three criteria, result is sum 
        """
        bndSel = BondSelector([lambda x:x.atom1.number==1, lambda x:\
                    x.atom1.number==2,lambda x:x.atom1.name=='CA'])
        ats = self.mol.allAtoms[:10]
        bnds = ats.bonds[0]
        resultBnds = bndSel.select(bnds)
        #print 'len(resultBnds)==', len(resultBnds)
        #self.assertEqual(len(resultBnds) , 4)
        self.assertEqual(len(resultBnds) , 5)


    def test_BondBranchBondSelector_constructor(self):
        """
         test BondBranch constructor
        """
        bndLenSel = BondBranchBondSelector(2)
        self.assertEqual( bndLenSel.__class__,BondBranchBondSelector)


    def test_BondBranchBondSelector_select_no_bnds(self):
        """
         test BondBranch select: no bonds
        """
        bndSel = BondBranchBondSelector(2)
        ats = self.mol.allAtoms[0:5]
        bnds = ats.bonds[0]
        resultBnds = bndSel.select(bnds)
        #print 'no_bnds:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds) , 0)


    def test_BondBranchBondSelector_select_some_bnds(self):
        """
         test BondBranch select: some bonds
        """
        bndSel = BondBranchBondSelector(2)
        ats = self.mol.allAtoms[:10]
        bnds = ats.bonds[0]
        resultBnds = bndSel.select(bnds)
        #print 'some_bnds:len(resultBnds)=', len(resultBnds)
        #self.assertEqual(len(resultBnds) , 1)
        self.assertEqual(len(resultBnds) , 2)


    def test_BondBranchBondSelector_select_all_bnds(self):
        """
         test BondBranch select: all bonds
        """
        bndSel = BondBranchBondSelector(2)
        ats = self.mol.allAtoms
        bnds = ats.bonds[0]
        resultBnds = bndSel.select(bnds)
        #print 'all_bnds:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds) , 120)


    def test_BondElementBondSelector_constructor(self):
        """
         test BondElement constructor
        """
        bndLenSel = BondElementBondSelector('C')
        self.assertEqual( bndLenSel.__class__,BondElementBondSelector)


    def test_BondElementBondSelector_select_no_bnds(self):
        """
         test BondElement select: no bonds
        """
        bndSel = BondElementBondSelector('P')
        ats = self.mol.allAtoms
        bnds = ats.bonds[0]
        resultBnds = bndSel.select(bnds)
        #print 'no_bnds:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds) , 0)


    def test_BondElementBondSelector_select_some_bnds(self):
        """
         test BondElement select: some bonds
        """
        bndSel = BondElementBondSelector('C')
        ats = self.mol.allAtoms[:10]
        bnds = ats.bonds[0]
        resultBnds = bndSel.select(bnds)
        #print 'some_bnds:len(resultBnds)=', len(resultBnds)
        #self.assertEqual(len(resultBnds) , 9)
        self.assertEqual(len(resultBnds) , 6)


    def test_BondElementBondSelector_select_all_bnds(self):
        """
         test BondElement select: all bonds
        """
        bndSel = BondElementBondSelector('C')
        ats = self.mol.allAtoms
        bnds = ats.bonds[0]
        resultBnds = bndSel.select(bnds)
        #print 'all_bnds:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds) , 334)


    def test_LeafBondSelector_constructor(self):
        """
         test LeafBond constructor
        """
        leafBndSel = LeafBondSelector()
        self.assertEqual( leafBndSel.__class__, LeafBondSelector)


    def test_LeafBondSelector_select_no_leaves(self):
        """
         test LeafBond select: no bonds
        """
        leafBndSel = LeafBondSelector()
        ats = self.mol.allAtoms[7:10]
        bnds = ats.bonds[0]
        resultBnds = leafBndSel.select(bnds)
        #print 'no_leaves:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds) , 0)


    def test_LeafBondSelector_select_some_leaves(self):
        """
         test LeafBond select: some bonds
        """
        leafBndSel = LeafBondSelector()
        ats = self.mol.allAtoms[:10]
        bnds = ats.bonds[0]
        resultBnds = leafBndSel.select(bnds)
        #print 'some_leaves:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds) , 2)
        #self.assertEqual(len(resultBnds) , 5)


    def test_LeafBondSelector_select_all_leaves(self):
        """
         test LeafBond select: all bonds
        """
        leafBndSel = LeafBondSelector()
        ats = self.mol.allAtoms
        bnds = ats.bonds[0]
        resultBnds = leafBndSel.select(bnds)
        #print 'all_leaves:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds) , 150)


    def test_HydrogenRotatorBondSelector_constructor(self):
        """
         test HydrogenRotator constructor
        """
        hrBndSel = HydrogenRotatorBondSelector()
        self.assertEqual( hrBndSel.__class__, HydrogenRotatorBondSelector)


    def test_HydrogenRotatorBondSelector_select_none(self):
        """
         test HydrogenRotator select: no bonds
        """
        HRSel = HydrogenRotatorBondSelector()
        ats = self.mol.allAtoms[2:6]
        bnds = ats.bonds[0]
        resultBnds = HRSel.select(bnds)
        #print 'no_hydrogenrotators:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds) , 0)


    def test_HydrogenRotatorBondSelector_select_some(self):
        """
         test HydrogenRotator select: some bonds
        """
        HRSel = HydrogenRotatorBondSelector()
        ats = self.mol.chains.residues[:8].atoms
        bnds = ats.bonds[0]
        resultBnds = HRSel.select(bnds)
        #print 'some_hydrogenrotators:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds) , 4)


    def test_HydrogenRotatorBondSelector_select_all(self):
        """
         test HydrogenRotator select: all bonds
        """
        HRSel = HydrogenRotatorBondSelector()
        ats = self.mol.allAtoms
        bnds = ats.bonds[0]
        resultBnds = HRSel.select(bnds)
        #print 'all_hydrogenrotators:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds) , 18)


    def test_AmideBondSelector_constructor(self):
        """
         test AmideBond constructor
        """
        amBndSel = AmideBondSelector()
        self.assertEqual(amBndSel.__class__, AmideBondSelector)


    def test_AmideBondSelector_select_none(self):
        """
         test AmideBond select: no bonds
        """
        from MolKit.bondSelector import AmideBondSelector
        amBndSel = AmideBondSelector()
        ats = self.mol.allAtoms[0:2]
        bnds = ats.bonds[0]
        resultBnds = amBndSel.select(bnds)
        #print 'no_amidebonds:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds) , 0)


    def test_AmideBondSelector_select_some(self):
        """
         test AmideBond select: some bonds
        """
        amBndSel = AmideBondSelector()
        ats = self.mol.allAtoms[:50]
        bnds = ats.bonds[0]
        resultBnds = amBndSel.select(bnds)
        #print 'some_amidebonds:len(resultBnds)=', len(resultBnds)
        #self.assertEqual(len(resultBnds) , 7)
        self.assertEqual(len(resultBnds) , 6)


    def test_AmideBondSelector_select_all(self):
        """
         test AmideBond select: all bonds
        """
        amBndSel = AmideBondSelector()
        ats = self.mol.allAtoms
        bnds = ats.bonds[0]
        resultBnds = amBndSel.select(bnds)
        #print 'all_amidebonds:len(resultBnds)=', len(resultBnds)
        #assert len(resultBnds) == 2
        self.assertEqual(len(resultBnds) , 48)


    def test_PeptideBackBoneBondSelector_constructor(self):
        """
         test PetideBackBone constructor
        """
        ppbbSel = PeptideBackBoneBondSelector()
        self.assertEqual(ppbbSel.__class__, PeptideBackBoneBondSelector)


    def test_PeptideBackBoneBondSelector_select_none(self):
        """
         test PetideBackBone select: no bonds
        """
        ppbbSel = PeptideBackBoneBondSelector()
        ats = self.mol.allAtoms[4:8]
        bnds = ats.bonds[0]
        resultBnds = ppbbSel.select(bnds)
        #print 'no_ppbbbonds:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds) , 0)


    def test_PeptideBackBoneBondSelector_select_some(self):
        """
         test PetideBackBone select: some bonds
        """
        ppbbSel = PeptideBackBoneBondSelector()
        ats = self.mol.allAtoms[:50]
        bnds = ats.bonds[0]
        resultBnds = ppbbSel.select(bnds)
        #print 'some_ppbbbonds:len(resultBnds)=', len(resultBnds)
        #self.assertEqual(len(resultBnds) , 22)
        self.assertEqual(len(resultBnds) , 17)


    def test_PeptideBackBoneBondSelector_select_all(self):
        """
         test PetideBackBone select: all bonds
        """
        ppbbSel = PeptideBackBoneBondSelector()
        ats = self.mol.allAtoms
        bnds = ats.bonds[0]
        resultBnds = ppbbSel.select(bnds)
        #print 'all_ppbbbonds:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds) , 132)


    def test_CycleBondSelector_constructor(self):
        """
         test CycleBondSelector constructor
        """
        cbSel = CycleBondSelector()
        self.assertEqual(cbSel.__class__, CycleBondSelector)


    def test_CycleBondSelector_select_none(self):
        """
         test CycleBondSelector select: no bonds
        """
        cbSel = CycleBondSelector()
        ats = self.mol.allAtoms[4:8]
        bnds = ats.bonds[0]
        resultBnds = cbSel.select(bnds)
        #print 'no_cb_bonds:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds) , 0)


    def test_CycleBondSelector_select_some(self):
        """
         test CycleBondSelector select: some bonds
        """
        cbSel = CycleBondSelector()
        ats = self.mol.allAtoms[:50]
        bnds = ats.bonds[0]


    def test_BondElementBondSelector_select_all_bnds(self):
        """
         test BondElement select: all bonds
        """
        bndSel = BondElementBondSelector('C')
        ats = self.mol.allAtoms
        bnds = ats.bonds[0]
        resultBnds = bndSel.select(bnds)
        #print 'all_bnds:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds) , 334)


    def test_LeafBondSelector_constructor(self):
        """
         test LeafBond constructor
        """
        leafBndSel = LeafBondSelector()
        self.assertEqual( leafBndSel.__class__, LeafBondSelector)


    def test_LeafBondSelector_select_no_leaves(self):
        """
         test LeafBond select: no bonds
        """
        leafBndSel = LeafBondSelector()
        ats = self.mol.allAtoms[7:10]
        bnds = ats.bonds[0]
        resultBnds = leafBndSel.select(bnds)
        #print 'no_leaves:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds) , 0)


    def test_LeafBondSelector_select_some_leaves(self):
        """
         test LeafBond select: some bonds
        """
        leafBndSel = LeafBondSelector()
        ats = self.mol.allAtoms[:10]
        bnds = ats.bonds[0]
        resultBnds = leafBndSel.select(bnds)
        #print 'some_leaves:len(resultBnds)=', len(resultBnds)
        #self.assertEqual(len(resultBnds) , 2)
        self.assertEqual(len(resultBnds) , 5)


    def test_LeafBondSelector_select_all_leaves(self):
        """
         test LeafBond select: all bonds
        """
        leafBndSel = LeafBondSelector()
        ats = self.mol.allAtoms
        bnds = ats.bonds[0]
        resultBnds = leafBndSel.select(bnds)
        #print 'all_leaves:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds) , 150)


    def test_HydrogenRotatorBondSelector_constructor(self):
        """
         test HydrogenRotator constructor
        """
        hrBndSel = HydrogenRotatorBondSelector()
        self.assertEqual( hrBndSel.__class__, HydrogenRotatorBondSelector)


    def test_HydrogenRotatorBondSelector_select_none(self):
        """
         test HydrogenRotator select: no bonds
        """
        HRSel = HydrogenRotatorBondSelector()
        ats = self.mol.allAtoms[2:6]
        bnds = ats.bonds[0]
        resultBnds = HRSel.select(bnds)
        #print 'no_hydrogenrotators:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds) , 0)


    def test_HydrogenRotatorBondSelector_select_some(self):
        """
         test HydrogenRotator select: some bonds
        """
        HRSel = HydrogenRotatorBondSelector()
        ats = self.mol.chains.residues[:8].atoms
        bnds = ats.bonds[0]
        resultBnds = HRSel.select(bnds)
        #print 'some_hydrogenrotators:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds) , 4)


    def test_HydrogenRotatorBondSelector_select_all(self):
        """
         test HydrogenRotator select: all bonds
        """
        HRSel = HydrogenRotatorBondSelector()
        ats = self.mol.allAtoms
        bnds = ats.bonds[0]
        resultBnds = HRSel.select(bnds)
        #print 'all_hydrogenrotators:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds) , 18)


    def test_AmideBondSelector_constructor(self):
        """
         test AmideBond constructor
        """
        amBndSel = AmideBondSelector()
        self.assertEqual(amBndSel.__class__, AmideBondSelector)


    def test_AmideBondSelector_select_none(self):
        """
         test AmideBond select: no bonds
        """
        from MolKit.bondSelector import AmideBondSelector
        amBndSel = AmideBondSelector()
        ats = self.mol.allAtoms[0:2]
        bnds = ats.bonds[0]
        resultBnds = amBndSel.select(bnds)
        #print 'no_amidebonds:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds) , 0)


    def test_AmideBondSelector_select_some(self):
        """
         test AmideBond select: some bonds
        """
        amBndSel = AmideBondSelector()
        ats = self.mol.allAtoms[:50]
        bnds = ats.bonds[0]
        resultBnds = amBndSel.select(bnds)
        #print 'some_amidebonds:len(resultBnds)=', len(resultBnds)
        #self.assertEqual(len(resultBnds) , 7)
        self.assertEqual(len(resultBnds) , 6)


    def test_AmideBondSelector_select_all(self):
        """
         test AmideBond select: all bonds
        """
        amBndSel = AmideBondSelector()
        ats = self.mol.allAtoms
        bnds = ats.bonds[0]
        resultBnds = amBndSel.select(bnds)
        #print 'all_amidebonds:len(resultBnds)=', len(resultBnds)
        #assert len(resultBnds) == 2
        self.assertEqual(len(resultBnds) , 48)


    def test_PeptideBackBoneBondSelector_constructor(self):
        """
         test PetideBackBone constructor
        """
        ppbbSel = PeptideBackBoneBondSelector()
        self.assertEqual(ppbbSel.__class__, PeptideBackBoneBondSelector)


    def test_PeptideBackBoneBondSelector_select_none(self):
        """
         test PetideBackBone select: no bonds
        """
        ppbbSel = PeptideBackBoneBondSelector()
        ats = self.mol.allAtoms[4:8]
        bnds = ats.bonds[0]
        resultBnds = ppbbSel.select(bnds)
        #print 'no_ppbbbonds:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds) , 0)


    def test_PeptideBackBoneBondSelector_select_some(self):
        """
         test PetideBackBone select: some bonds
        """
        ppbbSel = PeptideBackBoneBondSelector()
        ats = self.mol.allAtoms[:50]
        bnds = ats.bonds[0]
        resultBnds = ppbbSel.select(bnds)
        #print 'some_ppbbbonds:len(resultBnds)=', len(resultBnds)
        #self.assertEqual(len(resultBnds) , 22)
        self.assertEqual(len(resultBnds) , 17)


    def test_PeptideBackBoneBondSelector_select_all(self):
        """
         test PetideBackBone select: all bonds
        """
        ppbbSel = PeptideBackBoneBondSelector()
        ats = self.mol.allAtoms
        bnds = ats.bonds[0]
        resultBnds = ppbbSel.select(bnds)
        #print 'all_ppbbbonds:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds) , 132)


    def test_CycleBondSelector_constructor(self):
        """
         test CycleBondSelector constructor
        """
        cbSel = CycleBondSelector()
        self.assertEqual(cbSel.__class__, CycleBondSelector)


    def test_CycleBondSelector_select_none(self):
        """
         test CycleBondSelector select: no bonds
        """
        cbSel = CycleBondSelector()
        ats = self.mol.allAtoms[4:8]
        bnds = ats.bonds[0]
        resultBnds = cbSel.select(bnds)
        #print 'no_cb_bonds:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds) , 0)


    def test_CycleBondSelector_select_some(self):
        """
         test CycleBondSelector select: some bonds
        """
        cbSel = CycleBondSelector()
        ats = self.mol.allAtoms[:50]
        bnds = ats.bonds[0]
        resultBnds = cbSel.select(bnds)
        #print 'some_cb_bonds:len(resultBnds)=', len(resultBnds)
        #self.assertEqual(len(resultBnds) , 5)
        #because of di-sulfide bridges:
        #when increase RingFinder parameter "maxSize"
        self.assertEqual(len(resultBnds) , 42)


    def test_CycleBondSelector_select_all(self):
        """
         test CycleBondSelector select: all bonds
        """
        cbSel = CycleBondSelector()
        ats = self.mol.allAtoms
        bnds = ats.bonds[0]
        resultBnds = cbSel.select(bnds)
        #print 'all_cb_bonds:len(resultBnds)=', len(resultBnds)
        #self.assertEqual(len(resultBnds) , 43)
        #because of di-sulfide bridges:
        #when increase RingFinder parameter "maxSize"
        self.assertEqual(len(resultBnds) , 165)

    
    def test_BondOrderBondSelector(self):
        """
         test BondOrder constructor
        """
        bobSel = BondOrderBondSelector()
        self.assertEqual(bobSel.__class__, BondOrderBondSelector)


    def test_BondOrderBondSelector_select_none(self):
        """
         test BondOrder select: no bonds
        """
        bobSel = BondOrderBondSelector()
        ats = self.mol.allAtoms[4:8]
        bnds = ats.bonds[0]
        resultBnds = bobSel.select(bnds)
        #print 'no_cb_bonds:len(resultBnds)=', len(resultBnds)
        #self.assertEqual(len(resultBnds) , 2)
        self.assertEqual(len(resultBnds) , 3)


    def test_BondOrderBondSelector_select_some(self):
        """
         test BondOrder select: some bonds
        """
        bobSel = BondOrderBondSelector()
        ats = self.mol.allAtoms[:50]
        bnds = ats.bonds[0]
        resultBnds = bobSel.select(bnds)
        #print 'some_cb_bonds:len(resultBnds)=', len(resultBnds)
        #self.assertEqual(len(resultBnds) , 43)
        self.assertEqual(len(resultBnds) , 44)


    def test_BondOrderBondSelector_select_all(self):
        """
         test BondOrder select: all bonds
        """
        bobSel = BondOrderBondSelector()
        ats = self.mol.allAtoms
        bnds = ats.bonds[0]
        resultBnds = bobSel.select(bnds)
        #print 'all_cb_bonds:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds) , 341)


    def test_RotatableBondSelector_constructor(self):
        """
         test RotatableBond constructor
        """
        rotSel = RotatableBondSelector()
        self.assertEqual(rotSel.__class__, RotatableBondSelector)


    def test_RotatableBondSelector_select_none(self):
        """
         test RotatableBond select: no bonds
        """
        rotSel = RotatableBondSelector()
        ats = self.mol.allAtoms[4:8]
        bnds = ats.bonds[0]
        resultBnds = rotSel.select(bnds)
        #print 'no_cb_bonds:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds) , 1)


    def test_RotatableBondSelector_select_some(self):
        """
         test RotatableBond select: some bonds
        """
        rotSel = RotatableBondSelector()
        ats = self.mol.allAtoms[:50]
        bnds = ats.bonds[0]
        resultBnds = rotSel.select(bnds)
        #print 'some_cb_bonds:len(resultBnds)=', len(resultBnds)
        #self.assertEqual(len(resultBnds) , 34)
        #because of disulfide bridges-> large cycles
        #self.assertEqual(len(resultBnds) , 27)
        self.assertEqual(len(resultBnds) , 20)


    def test_RotatableBondSelector_select_all(self):
        """
         test RotatableBond select: all bonds
        """
        rotSel = RotatableBondSelector()
        ats = self.mol.allAtoms
        bnds = ats.bonds[0]
        resultBnds = rotSel.select(bnds)
        #print 'all_cb_bonds:len(resultBnds)=', len(resultBnds)
        #self.assertEqual(len(resultBnds) , 211)
        #because of disulfide bridges-> large cycles
        self.assertEqual(len(resultBnds), 89)


    def test_GuanidiniumBondSelector_select_all(self):
        """
         test GuanidiniumBond select: all bonds
        """
        guanSel = GuanidiniumBondSelector()
        ats = self.mol.allAtoms
        bnds = ats.bonds[0]
        resultBnds = guanSel.select(bnds)
        #print 'all_guanidinium_bonds:len(resultBnds)=', len(resultBnds)
        self.assertEqual(len(resultBnds), 6)
        for b in resultBnds:
            self.assertEqual(b.atom1.parent.type, 'ARG')
            if b.atom1.element=='C':
                self.assertEqual(b.atom1.name, 'CZ')
            if b.atom1.element=='N':
                self.assertEqual(b.atom1.name in ['NE','NH1','NH2'], True)


    def test_PeptideAromaticCycleBondSelector_select_all(self):
        """
         test PeptideAromaticCycleBond select: all aromatic bonds in 1crn
        """
        PABS = PeptideAromaticCycleBondSelector()
        ats = self.mol.allAtoms
        bnds = ats.bonds[0]
        resultBnds = PABS.select(bnds)
        self.assertEqual(len(resultBnds), 18)


    def test_PeptideAromaticCycleBondSelector_select_some(self):
        """
         test PeptideAromaticCycleBond select: 6 bonds
        """
        PABS = PeptideAromaticCycleBondSelector()
        bnds = self.mol.chains.residues[:21].atoms.bonds[0]  #includes 1 PHE
        resultBnds = PABS.select(bnds)
        self.assertEqual(len(resultBnds), 6)


    def test_PeptideAromaticCycleBondSelector_labels_aromatic_bnds(self):
        """
         test PeptideAromaticCycleBond labels aromatic bnds
        """
        PABS = PeptideAromaticCycleBondSelector()
        bnds = self.mol.chains.residues.atoms.bonds[0]  
        resultBnds = PABS.select(bnds)
        for b in resultBnds:
            self.assertEqual(hasattr(b, 'aromatic'), True)
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)
Esempio n. 53
0
        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()
    lig_non_std = ""
    non_std_types = check_types(ligand, supported_types)
    if len(non_std_types):
Esempio n. 54
0
class BaseTests(unittest.TestCase):

    def setUp(self):
        self.lig = Read('Data/ind_crystal.pdb')[0]
        self.lig.buildBondsByDistance()
        self.rec = Read('Data/hsg1.pdbqt')[0]
        self.rec.buildBondsByDistance()
    

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


    def test_CloserThanVDWSelector(self):
        """
        instantiate a CloserThanVDWSelector
        """
        d_sel = CloserThanVDWSelector()
        self.assertEquals(d_sel.__class__, CloserThanVDWSelector)


    def test_CloserThanVDWSelector_setupCutoff(self):
        """
         CloserThanVDWSelector cutoff is expected shape
        """
        cutoff = CloserThanVDWSelector().setupCutoff(self.rec.allAtoms, self.lig.allAtoms, 3.0)
        self.assertEquals(cutoff.shape[0], len(self.lig.allAtoms))
        self.assertEquals(cutoff.shape[1], len(self.rec.allAtoms))


    def test_CloserThanVDWSelector_select(self):
        """
        CloserThanVDWSelector.select returns expected number of atoms 
        """
        d_sel = CloserThanVDWSelector()
        resultD, distD = d_sel.select(self.lig.allAtoms, self.rec.allAtoms)
        #check that 14 atoms in the ligand are near 1 or more atoms in the receptor
        self.assertEquals(len(resultD.keys()), 14)
        d = {}
        for k in resultD.values():
            for item in k:
                d[item] = 0
        #check that 16 atoms in the receptor are near an atom in the ligand
        self.assertEquals(len(d.keys()), 16)
                

    def test_CloserThanVDWPlusConstantSelector(self):
        """
        instantiate a CloserThanVDWPlusConstantSelector
        """
        d_sel = CloserThanVDWPlusConstantSelector()
        self.assertEquals(d_sel.__class__, CloserThanVDWPlusConstantSelector)


    def test_CloserThanVDWPlusConstantSelector_setupCutoff(self):
        """
         CloserThanVDWPlusConstantSelector cutoff is expected shape
        """
        cutoff = CloserThanVDWPlusConstantSelector().setupCutoff(self.rec.allAtoms, self.lig.allAtoms, 3.0)
        self.assertEquals(cutoff.shape[0], len(self.lig.allAtoms))
        self.assertEquals(cutoff.shape[1], len(self.rec.allAtoms))


    def test_CloserThanVDWPlusConstantSelector_select(self):
        """
        CloserThanVDWPlusConstantSelector.select returns expected number of atoms 
        """
        d_sel = CloserThanVDWPlusConstantSelector(constant=1)
        resultD, distD = d_sel.select(self.lig.allAtoms, self.rec.allAtoms)
        #check that 45 atoms in the ligand are near 1 or more atoms in the receptor
        self.assertEquals(len(resultD.keys()), 45)
        d = {}
        for k in resultD.values():
            for item in k:
                d[item] = 0
        #check that 16 atoms in the receptor are near an atom in the ligand
        # when using sum of vdw PLUS 1.0 angstrom
        self.assertEquals(len(d.keys()), 93)