

#  $Id: test_AD41analyze.py,v 1.9 2010/08/24 21:48:49 sargis Exp $




import unittest, glob, os, types, Pmv.Grid
import time
from string import find,split
mv = None
ct = 0
totalCt = 53
###totalCt = 65
klass = None

class AD41analyze_BaseTests(unittest.TestCase):
    """
    setUp + tearDown form a fixture: working environment for the testing code
    """
    
        
    def startViewer(self):
        global mv
        #print 'in test_AD startViewer'
        if mv is None:
            from MolKit import Read
            import Tkinter
            from Pmv.moleculeViewer import MoleculeViewer
            mv = MoleculeViewer(trapExceptions = False,
                                withShell=0
                                )
            #mv.loadModule('autotors41Commands', 'AutoDockTools')
            #mv.loadModule('autogpf41Commands', 'AutoDockTools')
            #mv.loadModule('autodpf41Commands', 'AutoDockTools')
            #8/18:
            #mv.loadModule('autoanalyze41Commands', 'AutoDockTools')
            mv.loadModule('deleteCommands', 'Pmv')
            mv.loadModule('selectionCommands', 'Pmv')
            #change warningMsg format
            mv.setUserPreference(('warningMsgFormat', 'printed'), log = 0)
            from AutoDockTools.autotorsCommands import AdtSetMode
            mv.addCommand(AdtSetMode(), 'ADTSetMode')
            mv.ADTSetMode("AD4.0")
            mv.ADTSetMode("AD4.2")
        self.mv = mv


    def setUp(self):
        """
        clean-up
        """
        global klass, mv
        name = self.__class__.__name__
        if not klass:
            klass = name
        elif klass != name:
            print 'SETUP: destroying mv'
            if mv:
                # reload AutoDockTools and  Pmv modules:
                from AutoDockTools import autotors4Commands, autoflex4Commands,\
                      autotors41Commands, autoflex41Commands
                reload(autotors4Commands)
                reload(autoflex4Commands)
                reload(autotors41Commands)
                reload(autoflex41Commands)
                
                import Pmv
                allmod = dir(Pmv)
                for m in allmod:
                    if m.endswith("Commands"):
                        exec("if type(Pmv.%s) == types.ModuleType: reload(Pmv.%s)" % (m,m))
                mv.Exit(0)
                if hasattr(self, 'mv'):
                    del self.mv
                mv = None
            klass = name
        if not hasattr(self, 'mv'):
            self.startViewer()


    def tearDown(self):
        """
        clean-up
        """
        #print 'in AD41analyze tearDown'
        global ct, totalCt
        #reset docked
        from AutoDockTools.Docking import Docking
        for key in self.mv.dockings.keys():
            try:
                self.mv.AD41analyze_deleteDLG(key)
            except:
                pass
        self.mv.dockings = {}
        self.mv.docked = None
        #delete any molecules left due to errors
        for m in self.mv.Mols:
            try:
                self.mv.deleteMol(m)
            except:
                pass
        for g in self.mv.grids.values():
            #for clean up:
            #hide the box
            g.surfGUI.boxvVar.set(0)
            g.surfGUI.changeBox()
            #hide the grid
            if hasattr(g, 'srf') and g.srf:
                g.srf.Set(visible=0)
                g.srf.protected = False
            if g.geom:
                g.geom.protected = False
            if hasattr(g, 'box') and g.box:
                g.box.protected = False
            if hasattr(g, 'slices') and g.slices:
                for slice_list in g.slices.values():
                    for slice in slice_list: 
                        slice.protected = False
                delattr(g, 'slices')
                    
            self.mv.GUI.VIEWER.Redraw()
        #clean-out the dictionary
        self.mv.grids = {}
        ct = ct + 1
        #print 'ct =', ct
        if ct==totalCt:
            print 'destroying mv'
            self.mv.Exit(0)
            del self.mv



class AD41analyze_readDLGTests(AD41analyze_BaseTests):
    """
    setUp + tearDown form a fixture: working environment for the testing code
    """
       
    

   
    def test_readDlg(self):
        """reads a dlg and checks 
        """
        self.mv.AD41analyze_readDLG("ind.dlg")
        self.assertEqual(self.mv.docked.dlo_list[0].filename, "ind.dlg")
        self.assertEqual(self.mv.docked.ligMol.name, "ind_out")
  
   
    def test_confor(self):
        """checks for # of conformations
        """
        self.mv.AD41analyze_readDLG("ind.dlg")
        self.assertEqual(len(self.mv.docked.ch.conformations), 10)
  

    def test_delete(self):
        """checks everything is gone
        """
        self.mv.AD41analyze_readDLG("ind.dlg")
        self.mv.AD41analyze_deleteDLG('ind.dlg')
        self.assertEqual(self.mv.docked, None)
 

    def test_cluster(self):
        """checks has clusters
        """
        self.mv.AD41analyze_readDLG("ind.dlg")
        cd = self.mv.docked.clusterer.clustering_dict
        self.assertEqual(cd.keys()[0], 0.5)
        self.assertEqual(len(cd[0.5][0]), 4)
        dlo = self.mv.docked.dlo_list[0]
        self.assertEqual(dlo.hasClusters, 1)


    def test_macrofile(self):
        """checks for macrofile & macroStem
        """
        self.mv.AD41analyze_readDLG("ind.dlg")
        dlo = self.mv.docked.dlo_list[0]
        self.assertEqual(dlo.macroFile, 'hsg1.pdbqs')
        self.assertEqual(dlo.macroStem, 'hsg1')
   
    def test_emptyDlg(self):
       """tests empty dlg entry
       """
       self.assertRaises(IOError,self.mv.AD41analyze_readDLG," ")
 
    def test_readMissingDlg(self):
       """checks non-existent dlg
       """
       self.assertRaises(IOError,self.mv.AD41analyze_readDLG,"fish.dlg")
  
    def test_delete_with_no_docking(self):   
       """checks when one dlg entered and requested for deletion of other
       """
       self.assertRaises(KeyError, self.mv.AD41analyze_deleteDLG,"flh.dlg")


    def test_delete_with_docking(self):   
        """ deleting non-existing name
        """
        self.mv.AD41analyze_readDLG("ind.dlg")
        self.assertRaises(KeyError, self.mv.AD41analyze_deleteDLG,"flh.dlg")


    def test_selectdockeddlg(self):
        """tests not to add to previous
        """
        self.mv.AD41analyze_readDLG("ind.dlg")
        self.mv.AD41analyze_readDLG("flash.dlg",0)
        self.assertEqual(len(self.mv.docked.dlo_list),1)
        self.mv.docked = None
        self.mv.dockings = {}
        #delete any molecules left due to errors
        for m in self.mv.Mols:
            self.mv.deleteMol(m)
        
        
    def test_selectdlg(self):
        """checkligmolnem selected current docked one
        """
        self.mv.AD41analyze_readDLG("ind.dlg")
        self.mv.AD41analyze_readDLG("flash.dlg",0)
        self.mv.AD41analyze_selectDLG("ind.dlg")
        self.assertEqual(self.mv.docked.ligMol.name, "ind_out")
        self.mv.docked = None
        self.mv.dockings = {}
        #delete any molecules left due to errors
        for m in self.mv.Mols:
            self.mv.deleteMol(m)
    

    def test_selectnon_existentdlg(self):
        """check for non-existent selection
        """
        self.mv.AD41analyze_readDLG("ind.dlg")
        self.assertRaises(KeyError,self.mv.AD41analyze_selectDLG,"soap.dlg")
   

    def test_selectemptydlg(self):
        """"check for empty selection
        """
        self.assertRaises(KeyError,self.mv.AD41analyze_selectDLG," ")


    def test_selectdirdlg(self):
        """"check reading all dockinglogs in a directory into separate dockings
        """
        self.mv.AD41analyze_readAllDLGInDirectory("./",0, ask=0 )
        dlgfiles = glob.glob("./*.dlg")
        self.assertEqual(len(self.mv.dockings), len(dlgfiles))


    def test_selectdirdlgseparate(self):
        """"check reading all dockinglogs in a directory into 1 docking
        """
        self.mv.AD41analyze_readAllDLGInDirectory("./",1, ask=0 )
        self.assertEqual(len(self.mv.dockings),1)
     

    def test_showmolecule(self):
        """adds a macromolecule to the viewer and checks length of dir
        """
        self.mv.AD41analyze_readDLG("ind.dlg")
        # self.mv.Mols[0]="ind.dlg"
        #self.mv.Mols[1]="hsg1.pdbqs"
        print len(self.mv.Mols)
        for m in self.mv.Mols:
            print m.name
        self.assertEqual(hasattr(self.mv.docked,'macroMol'), False)        
        self.mv.AD41analyze_readMacromolecule("hsg1.pdbqs")
        self.assertEqual(hasattr(self.mv.docked,'macroMol'), True)        
        self.assertEqual(len(self.mv.Mols),2)
        self.assertEqual(self.mv.docked.macroMol, self.mv.Mols[-1])        
        #delete any molecules left due to errors
        for m in self.mv.Mols:
            self.mv.deleteMol(m)
    

    def test_choose_macromolecule(self):
        """tests choose macro molecule
        """
        self.mv.AD41analyze_readDLG("ind.dlg")
        self.mv.AD41analyze_readMacromolecule("hsg1.pdbqs")
        self.mv.AD41analyze_chooseMacromolecule("ind_out")
        self.assertEqual(self.mv.docked.macroMol.name,"ind_out")
        self.mv.AD41analyze_chooseMacromolecule("hsg1")
        self.assertEqual(self.mv.docked.macroMol.name,"hsg1")
              
    
    def test_nomacromolecule(self):
        """checks for non-existent macromolecule
        """
        self.mv.AD41analyze_readDLG("ind.dlg")
        self.mv.AD41analyze_readMacromolecule("hsg1.pdbq")
        self.assertEqual(hasattr(self.mv.docked,'macroMol'), False)        
        self.assertEqual(len(self.mv.Mols),  1)        
        #delete any molecules left due to errors
        for m in self.mv.Mols:
            self.mv.deleteMol(m)
    

    def test_existingmacromolecule(self):
        """checks length when existing mol called
        """
        self.mv.AD41analyze_readDLG("ind.dlg")
        le=len(self.mv.Mols)
        self.mv.AD41analyze_readMacromolecule("hsg1.pdbqs")
        self.assertEqual(len(self.mv.Mols),le+1)
        self.mv.AD41analyze_readMacromolecule("hsg1.pdbqs")
        self.assertEqual(len(self.mv.Mols),le+1)
        #delete any molecules left due to errors
        for m in self.mv.Mols:
            self.mv.deleteMol(m)


    def test_dockings(self):
        """tests for current docking instance
        """
        filename = "ind.dlg"
        self.mv.AD41analyze_readDLG(filename)
        self.mv.AD41analyze_readMacromolecule("hsg1.pdbqs")
        self.assertEqual(os.path.basename(self.mv.docked.dlo_list[0].filename), filename)

    
    def test_dockingspheres(self):
        """checks ShowDockingAs Spheres: that number of vertices==number of conformations
        """
        self.mv.AD41analyze_readDLG("ind.dlg")
        c = self.mv.AD41analyze_showDockingsAsSpheres
        c(["ind.dlg"]) #calls GUI command which opens its widget
        c.lb.selection_set(0) #set the widget's listbox selection to 1st entry
        c.updateVis()   #updates the dockedSpheres geometry for ligmol
        ligand = self.mv.docked.ligMol
        #get a handle to the geometry
        spheresGeom = ligand.geomContainer.geoms['dockedSpheres']
        #check that the geometry has the correct number of spheres
        self.assertEqual(len(spheresGeom.vertexSet),len(mv.docked.ch.conformations))
        #close the widget
        c.form.withdraw()
    

    def test_emtydlgsdockingspheres(self):
        """checks emptys dlgs docking spheres
        """
        self.mv.AD41analyze_readDLG("ind.dlg")
        self.assertRaises(KeyError,self.mv.AD41analyze_showDockingsAsSpheres,[" "])


    def test_dockingspheresnosset(self):
        """ check that dockedSpheres are not visible if docking is not selected in listbox
        """
        self.mv.AD41analyze_readDLG("ind.dlg")
        c = self.mv.AD41analyze_showDockingsAsSpheres
        c(["ind.dlg"]) #calls GUI command which opens its widget
        c.updateVis()   #updates the dockedSpheres geometry for ligmol
        ligand = self.mv.docked.ligMol
        #get a handle to the geometry
        spheresGeom = ligand.geomContainer.geoms['dockedSpheres']
        self.assertEqual(spheresGeom.visible, False)
        #close the widget
        c.form.withdraw()
    

    def test_dockingspheres_flexres(self):
        """ check that dockedSpheres are centered on ligand atoms only
        """
        self.mv.AD41analyze_readDLG("tut_ind.dlg")
        c = self.mv.AD41analyze_showDockingsAsSpheres
        c(["tut_ind.dlg"]) #calls GUI command which opens its widget
        c.lb.selection_set(0) #set the widget's listbox selection to 1st entry
        c.updateVis()   #updates the dockedSpheres geometry for ligmol
        ligand = self.mv.docked.ligMol
        #get a handle to the geometry
        spheresGeom = ligand.geomContainer.geoms['dockedSpheres']
        verts = spheresGeom.vertexSet.vertices.array[:]
        #check that first two vertices are expected values based on lig atoms only
        self.assertAlmostEqual(verts[0][0], 2.61951017)
        self.assertAlmostEqual(verts[0][1], 6.15904093)
        self.assertAlmostEqual(verts[0][2],-7.75912237)
        self.assertAlmostEqual(verts[1][0], 2.55975509)
        self.assertAlmostEqual(verts[1][1], 6.20373487)
        self.assertAlmostEqual(verts[1][2],-7.4846735)
        #close the widget
        c.form.withdraw()


###    def evalmol(self):
###        """test calling command mode of autodock"""
###        
###        self.mv.AD41analyze_readDLG("ind.dlg")
###        c=self.mv.AD41analyze_epdbMolecule
###        estFreeEnergy = self.mv.AD41analyze_epdbMolecule('hsg1_ind.dpf',['d1.pdbq'])
###        try:
###            self.assertEqual(round(estFreeEnergy,1), -14.4)
###        except:
###            #currently there is a bug in epdb in autodock3 compiled for sgi machines
###            self.assertEqual(round(estFreeEnergy,1), 4.4)
         

    def test_chooseDockedConformations(self):
        """ test choosing lowest energy conformation"""
        self.mv.AD41analyze_readDLG("ind.dlg")
        c=self.mv.AD41analyze_chooseDockedConformations
        c.guiCallback() #opens the listchooser widget
        c.chooser.lb.select_set(1) #want to show lowest energy
        c.chooser.show_cb()  #this changes conformation of ligand
        lowestEnergyConf = self.mv.docked.clusterer.clustering_dict[0.5][0][0]
        #check that the current conformation is the lowest energy one
        self.assertEqual(lowestEnergyConf, self.mv.docked.ch.current_conf)
        c.chooser.done_cb()  #this closes widget, i hope


###    def test_getChart(self):
###        """test that all the names of the ligands and macromolecules are in the chart
###"""
###        dlgs = ['ind.dlg','flash.dlg','flap.dlg','tut_ind.dlg']
###        for fn in dlgs:
###            self.mv.AD41analyze_readDLG(fn)
###        #self.mv.AD41analyze_readAllDLGInDirectory('./',0)
###        c = self.mv.AD41analyze_getChart
###        c(dlgs)
###        #c(['ind.dlg','flash.dlg','flap.dlg','tut_ind.dlg'])
###        #the buttons have names of ligands and macromolecules
###        namesOfButtons = c.ifd.entryByName.keys()
###        for d in self.mv.dockings.values():
###            self.assertEqual(d.ligMol.name in namesOfButtons, True)
###            self.assertEqual(d.dlo_list[0].macroStem in namesOfButtons, True)
###        c.close()
   

    def test_grids(self):
        """reads a map and checks
        """
        self.mv.AD41analyze_readDLG("ind.dlg")
        c=self.mv.AD41analyze_showGridIsocontours
        c("hsg1.C.map")
        m=mv.grids.values()[0]
        self.assertEqual(m.__class__,Pmv.Grid.AutoGrid)
        c.Close_cb()
        #cleanup: remove the command's ifd so it has to rebuild
        delattr(c, 'ifd')
       
   
    def test_gridsvset(self):
        """checks length of vertexset
        """
        self.mv.AD41analyze_readDLG("ind.dlg")
        c=self.mv.AD41analyze_showGridIsocontours
        c("hsg1.C.map")
        m=mv.grids.values()[0]
        self.assertEqual(len(m.srf.vertexSet), 2263)
        #before UTisocontour removed duplicate vertices
        #self.assertEqual(len(m.srf.vertexSet),8114)
        c.Close_cb()
       

    def test_gridsvisible(self):
        """checks visiblity of grid
        """
        self.mv.AD41analyze_readDLG("ind.dlg")
        c=self.mv.AD41analyze_showGridIsocontours
        c("hsg1.C.map")
        m=mv.grids.values()[0]
        self.assertEqual(m.srf.visible,1)
        c.Close_cb()
        #cleanup: remove the command's ifd so it has to rebuild
        delattr(c, 'ifd')
    

    def test_gridnonexistent(self):
       """checks with empty map name
       """
       self.mv.AD41analyze_readDLG("ind.dlg")
       self.assertRaises(IOError,self.mv.AD41analyze_showGridIsocontours," ", ask=0)
              
       
    def test_gridswrongname(self):
       """checks with wrong map name
       """
       self.mv.AD41analyze_readDLG("ind.dlg")
       self.assertRaises(IOError,self.mv.AD41analyze_showGridIsocontours,"hiu.dlg ",ask=0)


    def test_gridtwiceread(self):
        """checks when read twice map name
        """
        self.mv.AD41analyze_readDLG("ind.dlg")
        c=self.mv.AD41analyze_showGridIsocontours
        returnValue = c("hsg1.C.map")
        self.assertEqual(returnValue.__class__, Pmv.Grid.AutoGrid)
        returnValue.surfGUI.boxvVar.set(0)
        returnValue.surfGUI.changeBox()
        returnValue.srf.Set(visible=0)
        returnValue2 = c("hsg1.C.map")
        self.assertEqual(returnValue2, 'ERROR')
        c.Close_cb()
        self.mv.AD41analyze_deleteDLG("ind.dlg")
        #cleanup: remove the command's ifd so it has to rebuild
        delattr(c, 'ifd')
   

    def test_read_extra_grid(self):
        """ check reading in a grid not used in docking for comparison purposes."""
        self.mv.AD41analyze_readDLG("ind.dlg")
        c = self.mv.AD41analyze_showGridIsocontours
        c("extra.S.map")
        m = mv.grids.values()[0]
        self.assertEqual(m.__class__,Pmv.Grid.AutoGrid)
        c.Close_cb()
        #cleanup: remove the command's ifd so it has to rebuild
        delattr(c, 'ifd')
        
    def test_conformations_showstates_spwattr(self):
       """ checks for spw attr 
       """
       self.mv.AD41analyze_readDLG("ind.dlg")
       self.mv.AD41analyze_showStates("ind_out")
       self.assertEqual(hasattr(self.mv.Mols[0],"spw"),True)
       self.mv.Mols[0].spw.Close_cb()
        
    def test_conformations_showstates_toplevel_winfo(self):
       """ checks toplevel wininfo is mapped
       """
       self.mv.AD41analyze_readDLG("ind.dlg")
       self.mv.AD41analyze_showStates("ind_out")
       self.mv.Mols[0].spw.applyState(0)
       self.assertEqual(self.mv.Mols[0].spw.form.root.winfo_ismapped(),1)
       self.mv.Mols[0].spw.Close_cb()
        
    def test_conformations_showstates_sequencelist(self):
        """checks sequencelist equals to # of conformations
        """
        self.mv.AD41analyze_readDLG("ind.dlg")
        self.mv.AD41analyze_showStates("ind_out")
        self.assertEqual(len(self.mv.Mols[0].spw.sequenceList),len(self.mv.docked.ch.conformations))
        self.mv.Mols[0].spw.Close_cb()

    def test_conformations_showstates_sequencelist_sameorder(self):
        """checks conformations are in same order in both sequence list and
        docked ch list
        """
        self.mv.AD41analyze_readDLG("ind.dlg")
        self.mv.AD41analyze_showStates("ind_out")
        for i in xrange(len(self.mv.Mols[0].spw.sequenceList)):
            self.assertEqual(self.mv.Mols[0].spw.sequenceList[i],self.mv.docked.ch.conformations[i])
        self.mv.Mols[0].spw.Close_cb()

    def test_conformations_showstates_applystates(self):
        """checks coords changing the apply states
        """
        self.mv.AD41analyze_readDLG("ind.dlg")
        self.mv.AD41analyze_showStates("ind_out")
        atom1=self.mv.Mols[0].allAtoms[0]
        self.assertEqual(round(atom1.coords[0],3),4.080)  
        self.assertEqual(round(atom1.coords[1],3),6.701)
        self.assertEqual(round(atom1.coords[2],3),-3.117)
        self.mv.Mols[0].spw.applyState(-1)
        self.assertEqual(round(atom1.coords[0],3),-3.884)  
        self.assertEqual(round(atom1.coords[1],3),-2.421)
        self.assertEqual(round(atom1.coords[2],3),-3.900)
        self.mv.Mols[0].spw.Close_cb()


    def test_Showstates_total_energy(self):
        """ checks total energy
        """
        self.mv.AD41analyze_readDLG("ind.dlg")
        self.mv.AD41analyze_showStates("ind_out")
        self.mv.Mols[0].spw.applyState(0)
        atom1=self.mv.Mols[0].allAtoms[0]
        self.assertEqual(round(atom1.total_energy,3),-0.240)
        self.mv.Mols[0].spw.Close_cb()


    def test_showstates_binding_energy(self): 
        """checks binding energy
        """
        self.mv.AD41analyze_readDLG("ind.dlg")
        self.mv.AD41analyze_showStates("ind_out")
        self.assertEqual(self.mv.docked.ch.conformations[0].binding_energy,-14.34)
        self.mv.Mols[0].spw.Close_cb()
    
    def test_showstates_docking_energy(self): 
        """"checks docking energy
        """
        self.mv.AD41analyze_readDLG("ind.dlg")
        self.mv.AD41analyze_showStates("ind_out")
         
        self.assertEqual(self.mv.docked.ch.conformations[0].docking_energy,-18.84)
        self.mv.Mols[0].spw.Close_cb()


###class AD41analyze_readDiversityResultFiles(AD41analyze_BaseTests):


###    def setUp(self):
###        """
###        clean-up
###        """
###        if not hasattr(self, 'mv'):
###            self.startViewer()
###        self.mv.AD41analyze_readStates('diversity1483_x1hpv.dpf','2176.res')
###        self.mv.AD41analyze_showStates("diversity1483")



###    def test_read_conformations_from_file_atmNum(self):
###        """ checks # of atoms in dpf  after reading
###        using readStates
###  
###        """
###        self.assertEqual(len(self.mv.Mols[-1].atmNum),21)    
###        self.mv.Mols[-1].spw.Close_cb()
###  

###    def test_read_conformations_from_file_length(self):
###        """checks length in sequence list after reading
###        using readStates
###        """
###        self.assertEqual(len(self.mv.Mols[-1].spw.sequenceList), 20)
###        self.mv.Mols[-1].spw.Close_cb()
###  

###    def test_read_conformations_from_file_coords(self):
###        """checks coords are different after applystate()    
###        """
###        m=self.mv.Mols[-1].ROOT    
###        #self.assertEqual(round(m._coords[-1][0],3),0.002)
###        #self.assertEqual(round(m._coords[-1][1],3),-0.004)
###        #self.assertEqual(round(m._coords[-1][2],3),0.002)
###        #self.mv.Mols[-1].spw.applyState(0) 
###        self.assertEqual(round(m._coords[-1][0],3),-1.688)
###        self.assertEqual(round(m._coords[-1][1],3),0.611)
###        self.assertEqual(round(m._coords[-1][2],3),3.759)
###        self.mv.Mols[-1].spw.applyState(3) 
###        self.assertEqual(round(m._coords[-1][0],3),-1.649)
###        self.assertEqual(round(m._coords[-1][1],3), 0.684)
###        self.assertEqual(round(m._coords[-1][2],3),3.813)
###        self.mv.Mols[-1].spw.Close_cb()


###    def test_read_conformations_from_file_binding_energy(self):
###        """checks docking energy after reading from read States 
###        """        
###        self.assertEqual(round(self.mv.docked.ch.conformations[0].binding_energy,3), -8.944)
###        self.mv.Mols[-1].spw.Close_cb()
###       

###    def test_read_conformations_from_file_docking_energy(self):
###        """checks docking energy after reading from readStates       
###        """
###        self.assertEqual(round(self.mv.docked.ch.conformations[0].docking_energy, 3),-9.513)
###        self.mv.Mols[-1].spw.Close_cb()
   


###class AD41analyze_read_write_result_files(AD41analyze_BaseTests):
###        
###    def setUp(self):
###        """
###        clean-up
###        """
###        if not hasattr(self, 'mv'):
###            self.startViewer()
###        self.mv.AD41analyze_readDLG("ind.dlg", ask=0)
###        if not os.path.exists('test_ind.res'):
###            self.mv.AD41analyze_writeStates("ind_out",'test_ind.res')
###        self.mv.AD41analyze_readStates('hsg1_ind.dpf', 'test_ind.res', 0, ask=0)



###    def tearDown(self):
###        """
###        clean-up
###        """
###        print 'in read_write tearDown'
###        global ct, totalCt
###        #reset docked
###        from AutoDockTools.Docking import Docking
###        self.mv.docked = None
###        for key in self.mv.dockings.keys():
###            self.mv.AD41analyze_deleteDLG(key)
###        self.mv.dockings = {}
###        #delete any molecules left due to errors
###        #for m in self.mv.Mols:
###        #    self.mv.deleteMol(m)
###        ct = ct + 1
###        #print 'ct =', ct
###        if ct==totalCt:
###            print 'destroying mv'
###            self.mv.Exit(0)
###            del self.mv


###    def test_write_result_file_exists(self):
###        """6:checks file exists after writing  result file
###        """
###        self.assertEqual(os.path.exists('test_ind.res'),True)
###        cmd = "rm test_ind.res"
###        os.system(cmd)

###         
###    def test_write_dockings_result_file(self):
###        """2:checks dockings after writing  result file
###        """
###        d1 = self.mv.dockings['ind.dlg']
###        d2 = self.mv.dockings['test_ind.res']
###        self.assertEqual(d1.__class__, d2.__class__)
###    

###    def test_write_docking_result_file_dlolist_length(self):
###        """1:checks length of dlo_lists are equal after writing result file
###        """
###        d1 = self.mv.dockings['ind.dlg']
###        d2 = self.mv.dockings['test_ind.res']
###        self.assertEqual(len(d1.dlo_list), len(d2.dlo_list))


###    def test_write_result_file_dockings_docking_energy(self):
###        """4:checks clustering dict of d1 and d2 conformations docking energies
###        are equal after writing  result file
###        """
###        d1 = self.mv.dockings['ind.dlg']
###        d2 = self.mv.dockings['test_ind.res']
###        d1_conf_list = d1.clusterer.clustering_dict[0.5][0]
###        d2_conf_list = d2.ch.conformations
###        self.assertEqual( d1_conf_list[0].docking_energy, d2_conf_list[0].docking_energy)
###        self.assertEqual(d1_conf_list[1].docking_energy,d2_conf_list[1].docking_energy)
###   

###    def test_write_result_file_dockings_number_of_conformations(self):
###        """5:checks lengths of conformations after writing  result file
###        """
###        d1 = self.mv.dockings['ind.dlg']
###        d2 = self.mv.dockings['test_ind.res']
###        self.assertEqual(len(d1.ch.conformations), len(d2.ch.conformations))
###      

###    def test_write_result_file_compare_ligMols(self):
###        """3:checks names of ligmols after writing  result file
###        """
###        d1 = self.mv.dockings['ind.dlg']
###        d2 = self.mv.dockings['test_ind.res']
###        self.assertEqual(len(d1.ligMol.allAtoms), len(d2.ligMol.allAtoms))
###        self.assertEqual(d1.ligMol.name+'_1', d2.ligMol.name)
       


class AD41analyze_clusterings(AD41analyze_BaseTests):
        
    def setUp(self):
        """
        clean-up
        """
##         if not hasattr(self, 'mv'):
##             self.startViewer()
        apply(AD41analyze_BaseTests.setUp, (self, ), {})
        self.mv.AD41analyze_readDLG("ind.dlg")
        self.mv.AD41analyze_showClusteringStates("ind_out")
           

    def test_show_clusterings_length(self):
        """checks length clustering_dict
        """
        d = self.mv.docked
        v = d.clusterer.clustering_dict[0.5]
        self.assertEqual(len(v),2)
        self.assertEqual(len(v[0]),4)
        self.assertEqual(len(v[1]),6)


    def test_show_clusterings_lowest_energy(self):
        """checks lowest energy of clustering dict and conformations are same
        """
        d = self.mv.docked
        v = d.clusterer.clustering_dict[0.5]
        self.assertEqual(round(v[0][0].docking_energy,3),
                      round(d.ch.conformations[5].docking_energy,3))
        

    def test_show_clusterings_binding_energy(self):
        """checks cluterings binding energies
        """
        d = self.mv.docked
        v = d.clusterer.clustering_dict[0.5]
        self.assertEqual(round((v[0][0].binding_energy),3),-14.280)
        
        
    def test_show_clusterings_docking_energy(self):
        """checks clusterings docking energies
        """
        d = self.mv.docked
        v = d.clusterer.clustering_dict[0.5]
        self.assertEqual(round((v[0][0].docking_energy),3),-18.900)
    
        
    def test_show_clusterings_shows_histogram(self):
        """checks widgetfor showing histograms exists
        """
        d = self.mv.docked
        m = d.ligMol
        #self.mv.AD41analyze_showClusteringStates("ind_out-2")
        self.assertEqual(m.clustNB.master.winfo_exists(), 1)
        #self.assertEqual(m.clustNB.master.winfo_ismapped(), 1)
        m.clustNB.exit()
        self.assertEqual(m.clustNB.master.winfo_exists(), 0)
    

    def test_make_clusterings_at_high_rmsd(self):
        """checks clusterings at high rmsd
        """
        d = self.mv.docked
        self.mv.AD41analyze_selectDLG('ind.dlg')
        self.mv.AD41analyze_makeClustering([12.0], 'docking', None)
        v = d.clusterer.clustering_dict[12.]
        self.assertEqual(len(v), 1)
        self.assertEqual(len(v[0]), 10)


    def test_make_clusterings_at_low_rmsd(self):
        """checks clusterings at low rmsd
        """
        
        d = self.mv.docked
        self.mv.AD41analyze_selectDLG('ind.dlg')
        self.mv.AD41analyze_makeClustering([0.1], 'docking', None)
        v = d.clusterer.clustering_dict[0.1]
        self.assertEqual(len(v), 10)
        self.assertEqual(len(v[0]), 1)

    def test_write_clusterings_file_length_of_all_lines(self):
        """checks no . of ind_out all lines and conformations are same
        """
        
        d = self.mv.docked
        fptr=open("test_ind.clust")
        alllines=fptr.readlines()
        self.assertEqual(len(alllines),len(d.ch.conformations)+1)
        
    def test_write_clusterings_file_length_of_split_lines(self):
        """checks first line of ind_out is same length as clusterer.dict
        """
        
        d = self.mv.docked
        fptr=open("test_ind.clust")
        alllines=fptr.readlines()
        from string import split
        ll=split(alllines[0])
        v = d.clusterer.clustering_dict
        self.assertEqual(len(ll),len(v.keys())+5)
     
    def test_write_clusterings_file_energy_used(self):
        """checks both are using docking energies
        """
        
        d = self.mv.docked
        c1=d.clusterer
        fptr=open("test_ind.clust")
        alllines=fptr.readlines()
        from string import split
        ll=split(alllines[0])
        ll[-1]=c1.energy_used
        self.assertEqual(ll[-1],c1.energy_used)
    


class AD41analyze_check_coordinates(AD41analyze_BaseTests):

    def test_current_coords_of_atom0_bug(self):
        """checks ats[0]._coords[0] = ats[0].coords
        """
        self.mv.AD41analyze_readDLG("ind.dlg")
        ats0 = self.mv.allAtoms[0]
        old_ats0_coords =ats0._coords
        old_ats0coords  =ats0.coords
        self.mv.AD41analyze_showStates("ind_out")
        self.mv.Mols[0].spw.applyState(1)
        new_ats0_coords =ats0._coords
        new_ats0coords  =ats0.coords
        self.assertEqual(old_ats0coords,old_ats0_coords[0])
        #It should be new_ats0coords = new_ats0_coorsd[0],but we are getting
        self.assertEqual(new_ats0coords!=new_ats0_coords[0],True)
        self.mv.Mols[0].spw.Close_cb()
        
    def test_write_current_coords_bug(self):
        """checks when 1-1 docked conformation is choosed ,coords of atom0 =
        atom0 's coords in currentcoords file 
        """
        self.mv.AD41analyze_readDLG("ind.dlg")
        ats0 = self.mv.allAtoms[0]
        c = self.mv.AD41analyze_chooseDockedConformations
        c.guiCallback() #opens the listchooser widget
        c.chooser.lb.selection_clear(0,'end')
        c.chooser.lb.select_set(1) #want to show lowest energy
        c.chooser.show_cb()
        old_ats0coords  =ats0.coords
        self.mv.writePDB("ind_out","curcoords.pdb")
        fptr  =open("curcoords.pdb")
        alllines = fptr.readlines()
        #for i in range(0,len(alllines)):
	        #if find(str(alllines),'HETATM   1') >= 0:
                #pos = i
		        #break;
        split(str(alllines[0]))
        #these should be equal
        self.assertEqual(ats0.coords[0] != alllines[0][6],True)
        self.assertEqual(ats0.coords[1] != alllines[0][7],True)
        self.assertEqual(ats0.coords[2] != alllines[0][8],True)
        c.chooser.done_cb()
        os.system('rm -f curcoords.pdb')
        


class AD41analyze_showBindingSite(AD41analyze_BaseTests):
    """
     check AD41analyze_showBindingSite for expected display
    """
   
    def test_showBindingSite(self):
        """
        check for expected number of atoms in various displayed geometries

        """
        self.mv.AD41analyze_readDLG("ind.dlg")
        docking = self.mv.docked
        self.mv.AD41analyze_readMacromolecule("hsg1.pdbqs")
        self.mv.AD41analyze_showStates("ind_out") 
        command = self.mv.AD41analyze_showBindingSite
        
        #import pdb; pdb.set_trace()
        
        command('ind.dlg') 
        self.mv.GUI.VIEWER.Redraw()
        # input conformation of ligand clashes with receptor
        lig = self.mv.Mols[0]
        lig_gcg = lig.geomContainer.geoms
        lig_gca = lig.geomContainer.atoms
        macro = self.mv.Mols[1]
        macro_gcg = macro.geomContainer.geoms
        macro_gca = macro.geomContainer.atoms
        #12/13/07:changed macro close res display from lines to s&b
        self.assertEqual(len(macro_gca['sticks']), 118)
        #self.assertEqual(len(macro_gca['bonded']), 118)
        self.assertEqual(len(macro_gca['ResidueLabels']), 13)
        #check for secondary structure
        #turn on showSS:
        command.showSS.set(1)
        command('ind.dlg')
        self.assertEqual(len(lig_gca['bonded']), 49)
        self.assertEqual(len(lig_gca['ind_out_msms']), 49)
        self.assertEqual(len(lig_gca['cpk']), 0)
        #check for expected number of hbonds in input conf.
        self.assertEqual(len(lig.allAtoms.get(lambda x: hasattr(x, 'hbonds'))),7)
        #change to docked conformation
        lig.spw.applyState(2)
        #check for secondary structure
        self.assertEqual(len(macro_gca['ResidueLabels']), 14)
        #check for expected number of hbonds
        self.assertEqual(len(lig.allAtoms.get(lambda x: hasattr(x, 'hbonds'))), 6)
        # undisplay Msms in order to check for expected number of close-contact (8) 
        # and hbonding atoms(3) in the ligand for this conformation
        var = command.showMsms
        var.set(0)
        lig.spw.applyState(1)
        #command.update(docking, ('msmsatoms', var, self.mv.displayMSMS))
        self.mv.GUI.VIEWER.Redraw()
        # spheres on close contact displayed, spheres on hbonds not displayed
        self.assertEqual(len(lig_gca['cpk']), 23)
        # turn on 'display spheres on hbonding atoms' command.showHbatSpheres
        command.showHbatSpheres.set(1)
        lig.spw.applyState(1)
        #command.update(docking, ('hb_macro_ats', command.showHbatSpheres, self.mv.displayCPK))
        self.mv.GUI.VIEWER.Redraw()
        self.assertEqual(len(lig_gca['cpk']), 26)
        # turn off 'display spheres on close contact atoms' command.showCloseContactSpheres
        command.showCloseContactSpheres.set(0)
        lig.spw.applyState(1)
        #command.update(docking, ('non_hbas', command.showCloseContactSpheres, self.mv.displayCPK))
        self.mv.GUI.VIEWER.Redraw()
        # hbonding atoms(3) in the ligand for this conformation
        self.assertEqual(len(lig_gca['cpk']), 3)
        #redisplay Msms
        var.set(1)
        lig.spw.applyState(1)
        #command.update(docking, ('msmsatoms', var, self.mv.displayMSMS))
        self.mv.GUI.VIEWER.Redraw()
        # when msms surface for ligand displayed, no spheres are drawn on
        # ligand hbonding and close contact atoms
        self.assertEqual(len(lig_gca['cpk']), 0)



if __name__ == '__main__':
    unittest.main()
    #test_cases = [
    #        AD41analyze_BaseTests,
    #        AD41analyze_readDLGTests,
### #        AD41analyze_readDiversityResultFiles, DEPRECATED
    #        AD41analyze_read_write_result_files,
    #        AD41analyze_clusterings,
    #        AD41analyze_check_coordinates,
    #        AD41analyze_showBindingSite,
    #        ]
    #unittest.main( argv=([__name__ ,] + test_cases) )










#        

#   





