#
#
#
#
# $Id: test_AD.py,v 1.30 2012/11/29 21:48:28 rhuey Exp $
#

import unittest, os, sys, string, types
#from test import test_support
from string import split, strip
from MolKit.molecule import Atom
#no effect on order of output lines
#import MolKit.molecule
#import MolKit.protein
#MolKit.molecule.bhtreeFlag = 0
#MolKit.protein.bhtreeFlag = 0
#from time import sleep



#initialize globals: mv, ct, totalCt
mv = None
ct = 0
#totalCt = 45
#with ligands->59
#totalCt = 59
#with tutorial->60
####totalCt = 60
##when autoanalyze can be tested:
totalCt = 48
#totalCt = 63
#totalCt = 5

logfile = None
from compare_ligand_files import LigandFileChecker



class AD_BaseTests(unittest.TestCase):
    """
    setUp + tearDown form a fixture: working environment for the testing code
    """
    
    datadir = './ligandfiles'

        
    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)
            #mv = MoleculeViewer(trapExceptions=False, withShell=False)
            mv.loadModule('autotorsCommands', 'AutoDockTools')
            mv.loadModule('autogpfCommands', 'AutoDockTools')
            mv.loadModule('autodpfCommands', 'AutoDockTools')
            #8/18:
            mv.loadModule('autoanalyzeCommands', 'AutoDockTools')
            mv.loadModule('deleteCommands', 'Pmv')
            mv.loadModule('selectionCommands', 'Pmv')
            #change warningMsg format
            mv.setUserPreference(('warningMsgFormat', 'printed'), log = 0)
            
        self.mv = mv
        if not hasattr(self, 'lfc'):
            self.lfc = LigandFileChecker()



    def setUp(self):
        """
        clean-up
        """
        global logfile
        if not hasattr(self, 'mv'):
            self.startViewer()
        if not logfile or not hasattr(self, 'logfile') :
            print "OPENING test_result"
            logfile = self.logfile = open("test_result", "a")
            print "OPENED test_result"

        #if len(sys.argv):
        #    directory = os.path.split(sys.argv[0])[0]
        #    if len(directory):
        #        os.chdir(directory)


    def check_ligand(self, filename, ref=None):
        print 'checking ', filename
        #self.ct = self.ct + 1
        ligStem = os.path.splitext(filename)[0]
        ligOld = os.path.join(self.datadir, ligStem+'.out.pdbq')
        #FIX THIS: it's awkward....
        self.mv.ADtors_readLigand(os.path.join(self.datadir, filename))
        #print "read ", self.mv.Mols[-1].parser.filename
        print "read ", filename
        self.mv.ADtors_autoRoot()
        #self.mv.ADtors_defineRotBonds.setNoAmideTors(log=1)
        #self.mv.ADtors_defineRotBonds.setNoPeptideTors(log=1)
        outfile = ligOld +'.test'
        self.mv.ADtors_writeFormattedPDBQ(outfile)
        self.mv.deleteMol(ligStem)
        #open reference file and compare, line-by-line
        #try to catch some architecture dependent differences
        std_filename = ligOld
        if ref:
            std_filename = os.path.join(self.datadir, ref)
        #x = open(std_filename)
        #xlines = x.readlines()
        #new = open(outfile)
        #newlines = new.readlines()
        #ok = 1
        #equalLines = 1
        #equalCharges = 1
        #badLines = []
        results =  self.lfc.check_files(outfile, std_filename, 
                        start_key='ROOT')
        print 'outfile=', outfile,
        print 'std_filename=', std_filename
        #if len(xlines)!=len(newlines):
        #    #equalLines, equalCharges, badLines
        #    return 0, equalCharges, results
        ##self.assertEquals(len(xlines), len(newlines))
        #for i in range(len(xlines)):
        #    #REMARKS are not ordered
        #    if string.find(xlines[i],'REMARK')==0:
        #        pass
        #    elif xlines[i]!=newlines[i] and len(xlines[i])>70:
        #        xCharge = float(strip(xlines[i][-6:]))
        #        newCharge = float(strip(newlines[i][-6:]))
        #        if xCharge!=newCharge:
                    #ch1 = float(strip(xCharge))
                    #ch1 = float(xCharge[:-1])
                    #ch2 = float(strip(newCharge))
                    #ch2 = float(newCharge[:-1])
        #            df = abs(xCharge-newCharge)
                    #df = abs(ch1-ch2)
        #            if df > .002:
        #                equalCharges = 0
                        #badLines.append(i)
        #            return equalLines, equalCharges, results
                #else:
                #    #lines differ somewhere else
                #    badLines.append(i)
        #return equalLines, equalCharges, badLines
        #return equalLines, equalCharges, results
        return results



class ADtutorial_BaseTests(AD_BaseTests):
    """
    sequence for Using AutoDock with AutoDockTools tutorial
    """


    def setUp(self):
        """
        setUp
        """
        if not hasattr(self, 'mv'):
            self.startViewer()
        for m in self.mv.Mols:
            self.mv.deleteMol(m)
        if not hasattr(self, 'logfile'):
            self.logfile = open("test_result", "w")



    def tearDown(self):
        """
        clean-up
        """
        #print 'in tearDown'
        #reset atorsDict
        try:
            delattr(self.mv, 'LPO')
        except:
            pass
        #self.mv.atorsDict = {}
        #reset gpo
        from AutoDockTools.GridParameters import GridParameters
        self.mv.gpo = GridParameters()
        self.mv.gpo.vf = self.mv
        #reset dpo
        from AutoDockTools.DockingParameters import DockingParameters
        self.mv.dpo = DockingParameters()
        self.mv.dpo.vf = self.mv
        global ct
        ct = ct + 1
        if ct==totalCt:
            #self.pause(10)
            self.mv.GUI.ROOT.update_idletasks()
            print 'destroying mv'
            try:
                self.mv.Exit(0)
                del self.mv
            except:
                print 'error in mv.Exit(0)'
            print "CLOSING test_result"
        #self.logfile.close()


    def test_ADtutorial(self):
        """
        test tutorial sequence
        """
        self.mv.readMolecule('hsg1.pdb')
        self.mv.GUI.ROOT.update_idletasks()
        #print 'read hsg1.pdb'
        self.mv.selectFromString(mols='',chains='',res= 'HOH*',atoms='*', negate=0, silent=1)
        self.mv.deleteAtomSet(self.mv.getSelection())
        self.mv.GUI.ROOT.update_idletasks()
        #print 'deleted water atoms'
        self.mv.add_hGC("hsg1:::", method = 'noBondOrder', renumber = 1, polarOnly = 1)
        self.mv.GUI.ROOT.update_idletasks()
        #print 'added polar hydrogens '
        self.mv.ADtors_readLigand('ind.pdb',  ask = 1)
        self.mv.GUI.ROOT.update_idletasks()
        #print 'read ind.pdb'
        self.mv.ADtors_autoRoot()
        self.mv.GUI.ROOT.update_idletasks()
        #print 'set autoRoot'
        from MolKit.molecule import Atom
        self.mv.setIcomLevel(Atom,  KlassSet = None)
        self.mv.ADtors_defineRotBonds.setNoAmideTors_cb(redraw=0)
        self.mv.GUI.ROOT.update_idletasks()
        #print 'set noAmideTors'
        #FIX THIS: get 'indistinguishable nodes' when run from script
        # BUT NOT when run in viewer, step-by-step
        try:
            self.mv.ADtors_limitTorsions(6, 'fewest')
        except:
            print 'error in limitTorsions'
        self.mv.GUI.ROOT.update_idletasks()
        #print 'limited torsions to 6 moving the fewest'
        self.mv.ADtors_writeFormattedPDBQ('tt_ind.out.pdbq')
        self.mv.GUI.ROOT.update_idletasks()
        #print 'wrote tt_ind.out.pdbq'
        self.mv.ADgpf_chooseMacromolecule("hsg1",filename='tt_hsg1.pdbqs')
        self.mv.GUI.ROOT.update_idletasks()
        #print 'chose hsg1 and wrote tt_hsg1.pdbqs'
        self.mv.ADgpf_setGpo(SHB = 0, types = 'CANOH')
        self.mv.GUI.ROOT.update_idletasks()
        #print 'setGpo to not model SHB'
        self.mv.ADgpf_setGpo(npts = [60, 60, 60], gridcenter = [2.5, 6.5, -7.5], gridcenterAuto = 0)
        self.mv.GUI.ROOT.update_idletasks()
        #print 'setGpo npts, gridcenter'
        self.mv.ADgpf_writeGPF('tt_hsg1.gpf')
        self.mv.GUI.ROOT.update_idletasks()
        #print 'wrote tt_hsg1.gpf'
        self.mv.ADdpf_readMacromolecule('tt_hsg1.pdbqs')
        self.mv.GUI.ROOT.update_idletasks()
        #print 'wrote tt_hsg1.pdbqs'
        self.mv.ADdpf_chooseFormattedLigand("ind")
        self.mv.GUI.ROOT.update_idletasks()
        #fix this when public version autodpf is updated to include this parameter
        #self.mv.ADdpf_chooseFormattedLigand("ind", ask=0)
        self.mv.ADdpf_writeGALS('tt_ind.dpf')



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


    def tearDown(self):
        """
        clean-up
        """
        global ct, totalCt
        #print 'in tors tearDown'
        #reset atorsDict
        #self.mv.atorsDict = {}
        try:
            delattr(self.mv, 'LPO')
        except:
            pass
        #delete any molecules left due to errors
        for m in self.mv.Mols:
            self.mv.deleteMol(m)
            self.mv.GUI.ROOT.update_idletasks()
        ct = ct + 1
        #print 'ct =', ct
        if ct==totalCt:
            #self.pause(10)
            self.mv.GUI.ROOT.update_idletasks()
            print 'destroying mv'
            try:
                self.mv.Exit(0)
                del self.mv
            except:
                print 'error in mv.Exit(0)'
            print "CLOSING test_result"
            self.logfile.close()
            print "CLOSED test_result"


    def test_cyclohexanePhePh(self):
        """
        test cyclohexanePhePh formatting
        """
        self.mv.ADtors_readLigand('cyclohexanePhePh.mol2')
        mol = self.mv.Mols[0]
        self.mv.GUI.ROOT.update_idletasks()
        self.assertEquals( mol.torscount, 2)
        self.assertEquals( mol.possible_tors, 2)
        self.assertEquals( mol.allAtoms.bonds[0].activeTors.count(1), 2)
        self.mv.deleteMol(mol)
        

    def test_autoRoot(self):
        """
        ADtors_autoRoot
        """
        self.mv.ADtors_readLigand('ind.pdb')
        mol = self.mv.Mols[0]
        #mol = self.mv.atorsDict['molecule']
        self.mv.ADtors_autoRoot()
        self.mv.GUI.ROOT.update_idletasks()

        self.assertEquals( mol.ROOT.name , 'C11')
        self.assertEquals( mol.ROOT.rnum0 , 0)
        self.mv.deleteMol(mol)
        #self.mv.deleteMol('ind')
        

    def test_automaticLigandFormatting(self):
        """
        ADtors_automaticLigandFormatting
        """
        self.mv.ADtors_automaticLigandFormatting("ind.pdb", log=0, 
                    ask_outfile=0,
                    outfile='test_ind.out.pdbq')
        #check entries in atorsDict:
        mol = self.mv.Mols[-1]
        self.mv.GUI.ROOT.update_idletasks()
        self.assertEquals( hasattr(mol,'LPO') , True)
        self.assertEquals( mol.ROOT.name , 'C11')
        self.assertEquals( mol.torscount , 14)
        #following test too dependent on pybabel
        #self.assertEquals( len(dict['pTatomset']) , 35)
        self.assertEquals( len(mol.LPO.aromCs) , 17)
        self.assertEquals( len(mol.amidebnds) , 2)
        self.assertEquals( mol.LPO.outputfilename , 'test_ind.out.pdbq')
        self.mv.deleteMol(mol)


    def test_torTree(self):
        """
        check duplicate torTree construction
        (to check for a bug which is currently fixed)
        """
        for i in range(2):
            self.mv.ADtors_readLigand('ind.pdb')
            self.mv.GUI.ROOT.update_idletasks()
            #mol = self.mv.atorsDict['molecule']
            mol = self.mv.Mols[-1]
            self.mv.ADtors_autoRoot()
            self.mv.GUI.ROOT.update_idletasks()
            self.mv.ADtors_defineRotBonds.setNoAmideTors_cb()
            self.mv.GUI.ROOT.update_idletasks()
            self.mv.ADtors_limitTorsions(13, 'fewest')
            self.mv.GUI.ROOT.update_idletasks()
            self.mv.ADtors_limitTorsions(12, 'fewest')
            self.mv.GUI.ROOT.update_idletasks()
            self.mv.ADtors_limitTorsions(11, 'fewest')
            self.mv.GUI.ROOT.update_idletasks()
            self.mv.ADtors_limitTorsions(10, 'fewest')
            self.mv.GUI.ROOT.update_idletasks()
            self.mv.ADtors_limitTorsions(9, 'fewest')
            self.mv.GUI.ROOT.update_idletasks()
            self.mv.ADtors_limitTorsions(8, 'fewest')
            self.mv.GUI.ROOT.update_idletasks()
            self.mv.ADtors_limitTorsions(7, 'fewest')
            self.mv.GUI.ROOT.update_idletasks()
            self.mv.ADtors_limitTorsions(6, 'fewest')
            self.mv.GUI.ROOT.update_idletasks()
            self.mv.deleteMol(mol)
        self.assertEquals(1,1)


    def test_chooseLigand(self):
        """
        ADtors_chooseLigand
        4/21: PASSED
        """
        self.mv.readMolecule('ind.pdb')
        self.mv.displayLines('ind')
        self.mv.buildBondsByDistance('ind')
        self.mv.ADtors_chooseLigand('ind')
        self.mv.GUI.ROOT.update_idletasks()
        #check formatted mol:
        #mol = self.mv.atorsDict['molecule']
        mol = self.mv.Mols[0]
        self.assertEquals( mol.ROOT.rnum0 , 0)
        self.assertEquals( mol.torscount , 14)
        self.assertEquals( mol.LPO.ACM.cutoff , 7.5)
        self.assertEquals( len(mol.possible_tors_bnds) , 16)
        self.assertEquals( mol.LPO.outputfilename , None)
        self.assertEquals( len(mol.ppbbbnds) , 0)
        self.assertEquals( mol.TORSDOF , 14)
        self.assertEquals( len(mol.LPO.aromCs) , 17)
        self.assertEquals( len(mol.amidebnds) , 2)
        self.assertEquals( mol.amidebnds[0].atom1.name in ['C3', 'N2', 'C21', 'N4'],1)
        self.assertEquals( mol.amidebnds[0].atom2.name in ['C3', 'N2', 'C21', 'N4'],1)
        self.assertEquals( mol.amidebnds[1].atom1.name in ['C3', 'N2', 'C21', 'N4'],1)
        self.assertEquals( mol.amidebnds[1].atom2.name in ['C3', 'N2', 'C21', 'N4'],1)
        self.assertEquals( hasattr(mol, 'autoRoot') , False)
        self.mv.deleteMol(mol)
        

    def test_changePlanarityCriteria(self):
        """
        ADtors_changePlanarityCriteria
        """
        self.mv.setUserPreference(('warningMsgFormat', 'printed'))
        self.mv.ADtors_readLigand('mtx.pdb')
        #mol = self.mv.atorsDict['molecule']
        mol = self.mv.Mols[0]
        self.mv.GUI.ROOT.update_idletasks()
        #dict = self.mv.atorsDict
        self.assertEquals( mol.LPO.ACM.cutoff , 7.5)
        self.assertEquals( len(mol.LPO.aromCs) , 0)
        self.mv.ADtors_changePlanarityCriteria(10.0)
        self.mv.GUI.ROOT.update_idletasks()
        self.assertEquals( mol.LPO.ACM.cutoff , 10.0)
        self.assertEquals( len(mol.LPO.aromCs) , 6)
        #self.assertEquals( dict['aromaticCutOff'] , 10.0)
        #self.assertEquals( len(dict['aromaticCs']) , 6)
        self.mv.ADtors_changePlanarityCriteria(12.5)
        self.mv.GUI.ROOT.update_idletasks()
        self.assertEquals( mol.LPO.ACM.cutoff , 12.5)
        self.assertEquals( len(mol.LPO.aromCs) , 12)
        #self.assertEquals( dict['aromaticCutOff'] , 12.5)
        #self.assertEquals( len(dict['aromaticCs']) , 12)
        #restore mv
        self.mv.deleteMol(mol)

     
    def test_defineRotBonds(self):
        """
        ADtors_defineRotBonds
        4/21 PASSED
        """
        self.mv.ADtors_readLigand('ind.pdb')
        self.mv.GUI.ROOT.update_idletasks()
        #dict = self.mv.atorsDict
        mol = self.mv.atorsDict['molecule']
        #4/21: reduce from 16 to 14 because amide off by default
        self.assertEquals( mol.torscount , 14)
        #the amides are OFF by default; this turns them on
        self.mv.ADtors_defineRotBonds.setNoAmideTors_cb()
        self.mv.GUI.ROOT.update_idletasks()
        self.assertEquals( mol.torscount , 14)
        self.mv.ADtors_defineRotBonds.setNoAmideTors_cb()
        self.mv.GUI.ROOT.update_idletasks()
        self.assertEquals( mol.torscount , 16)
        self.mv.ADtors_defineRotBonds.setNoPeptideTors_cb()
        self.mv.GUI.ROOT.update_idletasks()
        self.assertEquals( mol.torscount , 16)
        self.mv.ADtors_defineRotBonds.setNoActiveTors_cb()
        self.mv.GUI.ROOT.update_idletasks()
        self.assertEquals( mol.torscount , 0)
        self.mv.ADtors_defineRotBonds.setNoActiveTors_cb()
        self.mv.GUI.ROOT.update_idletasks()
        self.assertEquals( mol.torscount , 16)
        #self.mv.deleteMol('ind')
        self.mv.deleteMol(mol)
        self.mv.GUI.ROOT.update_idletasks()


    def test_limitTorsions(self):
        """
        ADtors_limitTorsions
        """
        self.mv.ADtors_readLigand('ind.pdb')
        mol = self.mv.atorsDict['molecule']
        self.mv.GUI.ROOT.update_idletasks()
        self.mv.ADtors_autoRoot()
        self.mv.GUI.ROOT.update_idletasks()
        #4/21: reduce from 16 to 14 because amide off by default
        self.assertEquals( mol.torscount , 14)
        self.mv.ADtors_limitTorsions(0, 'fewest')
        self.mv.GUI.ROOT.update_idletasks()
        self.assertEquals( mol.torscount , 0)
        self.mv.ADtors_limitTorsions(13, 'fewest')
        self.mv.GUI.ROOT.update_idletasks()
        self.assertEquals( mol.torscount , 13)
        #check that doing it again does nothing
        self.mv.ADtors_limitTorsions(13, 'fewest')
        self.mv.GUI.ROOT.update_idletasks()
        self.assertEquals( mol.torscount , 13)
        self.mv.ADtors_limitTorsions(13, 'most')
        self.mv.GUI.ROOT.update_idletasks()
        self.mv.ADtors_limitTorsions(13, 'most')
        self.mv.ADtors_limitTorsions(14, 'fewest')
        self.mv.GUI.ROOT.update_idletasks()
        self.assertEquals( mol.torscount , 14)
        #can't have more than all of the possible ones...
        self.mv.ADtors_limitTorsions(20, 'fewest')
        self.mv.GUI.ROOT.update_idletasks()
        #print 'dict[torscount]=', dict['torscount']
        self.assertEquals( mol.torscount , 14)
        #self.mv.deleteMol('ind')
        self.mv.deleteMol(mol)
        self.mv.GUI.ROOT.update_idletasks()


    def test_readLigand(self):
        """
        ADtors_readLigand
        """
        self.mv.ADtors_readLigand('ind.pdb')
        self.mv.GUI.ROOT.update_idletasks()
        mol = self.mv.atorsDict['molecule']
        self.assertEquals( len(mol.allAtoms),49)
        #check entries in atorsDict:
        #dict = self.mv.atorsDict
        self.assertEquals( mol.ROOT.rnum0 , 0)
        self.assertEquals( mol.torscount, 14)
        self.assertEquals( mol.LPO.ACM.cutoff, 7.5)
        self.assertEquals( len(mol.possible_tors_bnds), 16)
        self.assertEquals( mol.LPO.outputfilename, None)
        self.assertEquals( len(mol.ppbbbnds), 0)
        self.assertEquals( mol.TORSDOF , 14)
        self.assertEquals( len(mol.LPO.aromCs) , 17)
        self.assertEquals( len(mol.amidebnds), 2)
        self.mv.deleteMol(mol)
        self.mv.GUI.ROOT.update_idletasks()
        

    def test_rigidLigand(self):
        """
        ADtors_rigidLigand
        """
        filename = 'ind_rigid.pdbq'
        if os.path.exists(filename):
            cmd = 'rm -f ' + filename
            os.system(cmd)
        self.mv.ADtors_rigidLigand('ind.pdb', 'ind_rigid.pdbq')
        self.mv.GUI.ROOT.update_idletasks()
        #check entries in atorsDict:
        self.assertEquals( os.path.exists(filename), True)
        fptr = open('ind_rigid.pdbq')
        allLines = fptr.readlines()
        fptr.close()
        self.mv.GUI.ROOT.update_idletasks()
        self.assertEquals( len(allLines) , 96)
        self.assertEquals( allLines[0][:25] , 'REMARK  0 active torsions')
        self.assertEquals( allLines[1][:4] , 'ROOT')
        self.assertEquals( allLines[-2][:7] , 'ENDROOT')
        self.assertEquals( allLines[-1][:7] , 'TORSDOF')



    def test_setBondRotatableFlag(self):
        """
        ADtors_setBondRotatableFlag
        """
        self.mv.ADtors_readLigand('ind.pdb')
        self.mv.GUI.ROOT.update_idletasks()
        mol = self.mv.atorsDict['molecule']
        #this test is too dependent on pybabel variety etc
        self.mv.ADtors_defineRotBonds.setNoAmideTors_cb()
        self.mv.GUI.ROOT.update_idletasks()
        self.assertEquals( mol.torscount , 14)
        self.mv.ADtors_defineRotBonds.setNoAmideTors_cb()
        self.mv.GUI.ROOT.update_idletasks()
        self.assertEquals( mol.torscount , 16)
        self.mv.ADtors_setBondRotatableFlag("ind:I:IND201:,N4,C22", 0)
        self.mv.GUI.ROOT.update_idletasks()
        self.assertEquals( mol.torscount , 15)
        self.mv.ADtors_setBondRotatableFlag("ind:I:IND201:,N4,C22", 1)
        self.mv.GUI.ROOT.update_idletasks()
        self.assertEquals( mol.torscount , 16)
        self.mv.deleteMol(mol)
        self.mv.GUI.ROOT.update_idletasks()


    def test_setCarbonNames(self):
        """
        ADtors_setCarbonNames
        """
        self.mv.ADtors_readLigand('ind.pdb')
        self.mv.GUI.ROOT.update_idletasks()
        mol = self.mv.atorsDict['molecule']
        self.assertEquals( len(mol.LPO.aromCs) , 17)
        self.mv.ADtors_setCarbonNames("ind:I:IND201:,C23,O4")
        self.mv.GUI.ROOT.update_idletasks()
        self.assertEquals( len(mol.LPO.aromCs) , 18)
        self.mv.ADtors_setCarbonNames("ind:I:IND201:,C13,C14")
        self.mv.GUI.ROOT.update_idletasks()
        self.assertEquals( len(mol.LPO.aromCs) , 20)
        self.mv.ADtors_setCarbonNames("ind:I:IND201:,N1")
        self.mv.GUI.ROOT.update_idletasks()
        self.assertEquals( len(mol.LPO.aromCs) , 20)
        self.mv.ADtors_setCarbonNames("ind:I:IND201:,A29,A27,A30,A28,A25,A26")
        self.mv.GUI.ROOT.update_idletasks()
        self.assertEquals( len(mol.LPO.aromCs) , 14)
        self.mv.deleteMol(mol)
        self.mv.GUI.ROOT.update_idletasks()


    def test_setRoot(self):
        """
        ADtors_setRoot
        """
        self.mv.ADtors_readLigand('ind.pdb')
        self.mv.GUI.ROOT.update_idletasks()
        mol = self.mv.atorsDict['molecule']
        self.mv.ADtors_setRoot('ind:::C10')
        self.mv.GUI.ROOT.update_idletasks()
        self.assertEquals( mol.ROOT.name , 'C10')
        self.mv.deleteMol(mol)
        self.mv.GUI.ROOT.update_idletasks()


    #TEST FAILING: FIX IT by implementing 'compare_files' method
    def test_writeFormattedPDBQ(self):
        """
        ADtors_writeFormattedPDBQ
        """
        self.mv.ADtors_readLigand('ind.pdb')
        self.mv.GUI.ROOT.update_idletasks()
        mol = self.mv.atorsDict['molecule']
        self.mv.ADtors_autoRoot()
        self.mv.GUI.ROOT.update_idletasks()
        #4/26: amide are off by default, apparently
        #self.mv.ADtors_defineRotBonds.setNoAmideTors_cb()
        self.mv.GUI.ROOT.update_idletasks()
        self.mv.ADtors_writeFormattedPDBQ('test_ind.out.pdbq')
        self.mv.GUI.ROOT.update_idletasks()
        
        results =  self.lfc.check_files('test_ind.out.pdbq', 
                                    'ref_ind.out.pdbq')
        no_errors, err_msg = self.lfc.report(results)
        if no_errors!=True:
            fileptr = open("writeFormatted_errors", "w")
            ostr = "\ntest_ind.out.pdbq:\n"
            fptr.write(ostr)
            fptr.write(err_msg)
        self.assertEquals(no_errors, True)

#        fptr = open('test_ind.out.pdbq')
#        allLines = fptr.readlines()
#        rptr = open('ref_ind.out.pdbq')
#        refLines = rptr.readlines()
#        for i in range(len(refLines)):
#            t_line = allLines[i]
#            r_line = refLines[i]
#            #if r_line!=t_line:
#            #    print i, '-', t_line
#            if string.find(t_line, 'REMARK') > -1:
#                continue
#            #print 'r_line=', r_line
#            #print 't_line=', t_line
#            self.assertEquals( r_line , t_line)
        self.mv.deleteMol(mol)
        self.mv.GUI.ROOT.update_idletasks()

            
    def test_stop(self):
        """
        ADtors_stop
        """
        self.mv.ADtors_readLigand('ind.pdb')
        mol = self.mv.atorsDict['molecule']
        self.mv.GUI.ROOT.update_idletasks()
        #check entries in atorsDict:
        #dict = self.mv.atorsDict
        self.mv.ADtors_autoRoot()
        self.mv.GUI.ROOT.update_idletasks()
        self.mv.ADtors_defineRotBonds.setNoAmideTors_cb()
        self.mv.GUI.ROOT.update_idletasks()
        self.mv.ADtors_writeFormattedPDBQ('stop_ind.out.pdbq')
        self.mv.GUI.ROOT.update_idletasks()
        self.mv.deleteMol(mol)
        self.mv.GUI.ROOT.update_idletasks()
        #11/21: i guess this is obsolete
        #self.mv.deleteMol.getFreeMemoryInformation()
        #deldict = self.mv.deleteMol.getFreeMemoryInformation()
        self.mv.GUI.ROOT.update_idletasks()
        #print deldict
        self.mv.ADtors_stop()
        #just check that test gets this far...
        self.assertEquals( 1, 1)


#    def test_addChainToRoot(self):
#        """
#        ADtors_addChainToRoot
#        """
#        ##THIS IS VERY SLOW##
#        self.mv.ADtors_readLigand('hsg1.pdbqs')
#        dict = self.mv.atorsDict
#        self.assertEquals( len(dict['chain_rootlist']) , 0)
#        self.mv.ADtors_addChainToRoot("hsg1:A", log = 0)
#        self.assertEquals( len(dict['chain_rootlist']) , 1)
#        self.assertEquals( dict['chain_rootlist'][0].name , 'A')
#        self.mv.deleteMol('hsg1')
#        

#    def test_RemoveChainFromRoot(self):
#        """
#        ADtors_removeChainFromRoot
#        """
#        self.mv.ADtors_readLigand('hsg1.pdbqs')
#        #check entries in atorsDict:
#        dict = self.mv.atorsDict
#        self.assertEquals( len(dict['chain_rootlist']) , 0)
#        self.mv.ADtors_addChainToRoot("hsg1:A", log = 0)
#        self.assertEquals( len(dict['chain_rootlist']) , 1)
#        self.assertEquals( dict['chain_rootlist'][0].name , 'A')
#        self.assertEquals( len(dict['rootlist']) , 0)
#        self.assertEquals( dict['rootnum'] , 0)
#        self.mv.ADtors_removeChainFromRoot("hsg1:A", log = 0)
#        self.assertEquals( len(dict['chain_rootlist']) , 0)
#        self.mv.deleteMol('hsg1')




class ADgpf_BaseTests(AD_BaseTests):
    """
    setUp + tearDown form a fixture: working environment for the testing code
    """
    #global mv


    def tearDown(self):
        """
        clean-up
        """
        #print 'in gpf tearDown'
        global ct, totalCt
        #reset gpo
        from AutoDockTools.GridParameters import GridParameters
        self.mv.gpo = GridParameters()
        self.mv.gpo.vf = self.mv
        #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
            print "CLOSING test_result"
            self.logfile.close()
            print "CLOSED test_result"


    def test_setGpo(self):
        """
        ADgpf_setGpo
        """
        #test gpo values:
        test_list = [ ('gridcenter', 'fred'),('spacing', 0.5 ),
                      ('covalent_half_width', 10.0 ), ('sol_par', [] ),
                      ('OHB', 11 ), ('smooth', 1100 ), ('covalentmap', 10 ),
                      ('gridfld', 'fred.maps.fld'), ('gridcenterAuto', 11 ),
                      ('covalent_coords', [] ), ('receptor', 'fred.pdbqs'),
                      ('covalent_constant', -1.78 ), 
                      ('covalent_energy_barrier', 110000 ),
                      ('mset', 'FRED'), ('nbp_r_eps', [] ),
                      ('types', 'FRED'), ('NHB', 1 ), ('SHB', 1 ),
                      ('elecmap', 'fred.e.map'), ('dielectric', -10),
                      ('constant', [] ), ('npts', [80, 80, 80] ),
                      ('map',  'fred')]

        test_dict = {}
        for i,j in test_list:
            test_dict[i] = j

        gpo = self.mv.gpo
        for k, v in test_dict.items():
            kw = {}
            kw[k] = v
            apply(self.mv.ADgpf_setGpo,(), kw)
            self.assertEquals(gpo[k]['value'], v)


    def test_initLigand(self):
        """
        ADgpf_initLigand
        """
        import Tkinter
        self.mv.ADgpf_readFormattedLigand('ind.out.pdbq')
        mol = self.mv.Mols[-1]
        self.mv.ADgpf_initLigand.Close_cb()
        self.assertEquals(self.mv.gpo.ligand_filename, 'ind.out.pdbq')
        #this is not good
        self.assertEquals(self.mv.gpo.ligand.name , 'ind_out')
        self.assertEquals(self.mv.gpo['types']['value'] , 'CANOH')
        self.mv.deleteMol(mol)
        #reset stuff in self.mv
        self.mv.ADgpf_setMapTypes.gtypes = Tkinter.StringVar(master=self.mv.GUI.ROOT)
        self.mv.ADgpf_setMapTypes.gtypes.set('')


    def test_initMacro(self):
        """
        ADgpf_initMacro
        """
        gpo = self.mv.gpo
        self.mv.ADgpf_readMacromolecule('hsg1.pdbqs')
        mol = self.mv.Mols[-1]
        self.assertEquals(self.mv.gpo.receptor_filename , 'hsg1.pdbqs')
        self.assertEquals(self.mv.gpo.receptor.name , 'hsg1')
        self.assertEquals(self.mv.gpo.receptor_stem , 'hsg1')
        #self.mv.deleteMol('hsg1')
        self.mv.deleteMol(mol)


#   #FIX THIS: currently it asks if you want to define the new type
#    def test_checkMacroTypes(self):
#        #'ADgpf_checkMacroTypes'
#        gpo = self.mv.gpo
#        self.mv.readMolecule('fx.pdbqs')
#        ##num = self.mv.ADgpf_checkMacroTypes(self.mv.Mols[0])
#        #if so it opens a window to get Rij and epsij
#        #if not, num==0
#        ##assert num == 1
#        ##assert self.mv.Mols[0].mset == 'CNOSHHM'
#        self.mv.deleteMol('fx')



    def test_readMacromolecule(self):
        """
        ADgpf_readMacromolecule
        """
        gpo = self.mv.gpo
        self.mv.ADgpf_readMacromolecule('hsg1.pdbqs')
        mol = self.mv.Mols[-1]
        #check that the read was ok:
        self.assertEquals( len(self.mv.allAtoms) , 1844)
        self.assertEquals( len(self.mv.allAtoms.parent.uniq()) , 198)
        #check that initMacro was called:
        self.assertEquals( self.mv.gpo.receptor_filename , 'hsg1.pdbqs')
        self.assertEquals( self.mv.gpo.receptor.name , 'hsg1')
        self.assertEquals( self.mv.gpo.receptor_stem , 'hsg1')
        #self.mv.deleteMol('hsg1')
        self.mv.deleteMol(mol)


    def test_chooseMacromolecule(self):
        """
        ADgpf_chooseMacromolecule
        """
        self.mv.readMolecule('hsg1.pdbqs')
        mol = self.mv.Mols[-1]
        #check that the read was ok:
        self.assertEquals( len(mol.allAtoms) , 1844)
        self.assertEquals( len(mol.allAtoms.parent.uniq()) , 198)
        self.mv.ADgpf_chooseMacromolecule('hsg1')
        #check that initMacro was called:
        self.assertEquals( self.mv.gpo.receptor_filename , 'hsg1.pdbqs')
        self.assertEquals( self.mv.gpo.receptor.name , 'hsg1')
        self.assertEquals( self.mv.gpo.receptor_stem , 'hsg1')
        #self.mv.deleteMol('hsg1')
        self.mv.deleteMol(mol)


    def test_addSolvationParameters(self):
        """
        ADgpf_addSolvationParameters
        4/21: PASSED
        """
        self.mv.readMolecule('1crn.pdbq')
        mol = self.mv.Mols[-1]
        self.mv.ADgpf_addSolvationParameters('1crn', outfile='1crn.pdbqs')
        self.assertEquals( len(self.mv.Mols[-1].allAtoms.get(lambda x: hasattr(x, 'AtVol'))) , len(self.mv.Mols[-1].allAtoms))
        self.assertEquals( len(self.mv.Mols[-1].allAtoms.get(lambda x: hasattr(x, 'AtSolPar'))) , len(self.mv.Mols[-1].allAtoms))
        self.mv.deleteMol(mol)


    def test_setMapTypes(self):
        """
        ADgpf_setMapTypes
        """
        self.mv.ADgpf_setMapTypes("CANOSH",1,0,0)
        #self.mv.ADgpf_initLigand.Close_cb()
        self.assertEquals( self.mv.gpo['types']['value'] , 'CANOSH')
        self.assertEquals( self.mv.gpo['NHB']['value'] , 1)
        self.assertEquals( self.mv.gpo['OHB']['value'] , 0)
        self.assertEquals( self.mv.gpo['SHB']['value'] , 0)


    def test_chooseFormattedLigand(self):
        """
        ADgpf_chooseFormattedLigand
        """
        self.mv.readMolecule('ind.out.pdbq')
        mol = self.mv.Mols[-1]
        self.mv.ADgpf_chooseFormattedLigand('ind_out')
        self.assertEquals( self.mv.gpo.ligand_filename , 'ind.out.pdbq')
        self.assertEquals( self.mv.gpo.ligand.name , 'ind_out')
        self.assertEquals( self.mv.gpo['types']['value'] , 'CANOH')
        self.mv.ADgpf_initLigand.Close_cb()
        #self.mv.deleteMol('ind_out')
        self.mv.deleteMol(mol)



    def test_readformattedLigand(self):
        """
        ADgpf_readformattedLigand
        """
        self.mv.ADgpf_readFormattedLigand('ind.out.pdbq')
        mol = self.mv.Mols[-1]
        self.assertEquals( len(mol.allAtoms), 49)
        #self.mv.ADgpf_initLigand.Accept_cb()
        self.assertEquals( self.mv.gpo.ligand_filename , 'ind.out.pdbq')
        #this is not good
        self.assertEquals( self.mv.gpo.ligand.name , 'ind_out')
        self.assertEquals( self.mv.gpo['types']['value'] , 'CANOH')
        self.mv.ADgpf_initLigand.Close_cb()
        #self.mv.deleteMol('ind_out')
        self.mv.deleteMol(mol)


    def test_defineAtomParameters(self):
        """
        ADgpf_defineAtomParameters
        """
        from AutoDockTools.energyConstants import Rij, epsij 
        from AutoDockTools.energyConstants import SolVol, SolPar, SolCon
        self.mv.ADgpf_defineAtomParameters('X',10,10)
        self.assertEquals( Rij['ljXC'] , 7.0)
        self.assertEquals( round(epsij['ljXC'], 3) , 0.472)
        self.assertEquals( SolPar['X'] , 0.0)
        self.assertEquals( SolCon['X'] , 0.0)
        self.assertEquals( SolVol['X'] , 0.0)


    def test_setGrid(self):
        """
        ADgpf_setGrid
        """
        test_list = [ ('gridcenter', [9.362, 9.677, 6.944] ), ('spacing', 0.5 ),
                      ('gridcenterAuto', 0 ), ('npts', [60, 60, 60] ), ]

        test_dict_setGrid = {}
        for i,j in test_list:
            test_dict_setGrid[i] = j


        self.mv.ADgpf_readMacromolecule('1crn.pdbqs')
        mol = self.mv.Mols[-1]
        #print 'gpo.receptor=', self.mv.gpo.receptor
        c = self.mv.ADgpf_setGrid
        c.buildForm()
        c.nxpts.set(60)
        c.nypts.set(60)
        c.nzpts.set(60)
        c.spacewheel.set(0.5)
        c.autoCenter()
        c.Accept_cb()
        gpo = self.mv.gpo
        for k, v in test_dict_setGrid.items():
            #print 'testing ', k, '-', v
            #print 'gpo[k]=', gpo[k]['value']
            if k=='gridcenter':
                v2 = gpo[k]['value'] 
                #print 'k=',k, ' v=', v, ' vs v2=', v2
                self.assertEquals( abs(v[0]-v2[0]) < .001, 1)
                self.assertEquals( abs(v[1]-v2[1]) < .001, 1)
                self.assertEquals( abs(v[2]-v2[2]) < .001, 1)
            else:    
                self.assertEquals( gpo[k]['value'] , v)
        #self.mv.deleteMol('1crn')
        self.mv.deleteMol(mol)


    def test_setOtherOptions(self):
        """
        ADgpf_setOtherOptions
        """
        self.mv.ADgpf_setOtherOptions(dielectric=40., smooth=1.0)
        self.assertEquals( self.mv.gpo['dielectric']['value'] , 40.)
        self.assertEquals( self.mv.gpo['smooth']['value'] , 1.)
        self.mv.ADgpf_setOtherOptions(dielectric=-0.1146, smooth=0.5)
        self.assertEquals( self.mv.gpo['dielectric']['value'] , -0.1146)
        self.assertEquals( self.mv.gpo['smooth']['value'] , .5)



    def test_writeGPF(self):
        """
        ADgpf_writeGPF
        """
        self.mv.ADgpf_readMacromolecule('hsg1.pdbqs')
        mol = self.mv.Mols[-1]
        #self.assertEquals( self.mv.gpo.receptor_filename , 'hsg1.pdbqs')
        #self.assertEquals( self.mv.gpo.receptor.name , 'hsg1')
        #self.assertEquals( self.mv.gpo.receptor_stem , 'hsg1')
        self.mv.ADgpf_readFormattedLigand('ind.out.pdbq')
        lig = self.mv.Mols[-1]
        self.mv.ADgpf_initLigand.Close_cb()
        self.mv.ADgpf_setGpo(log = 0, npts = [60, 60, 60], 
                spacing=0.375,
                gridcenter = [2.5, 6.5, -7.5], gridcenterAuto=0)
        self.mv.ADgpf_writeGPF('test_hsg1.gpf')
        fptr = open('test_hsg1.gpf')
        allLines = fptr.readlines()
        #print 'len(allLines)=', len(allLines)
        rptr = open('ref_hsg.gpf')
        refLines = rptr.readlines()
        #print 'len(refLines)=', len(refLines)
        self.assertEquals( len(allLines),len(refLines))
        for i in range(len(refLines)):
            t_line = allLines[i]
            r_line = refLines[i]
            if r_line!=t_line:
                print i, '-', t_line
            self.assertEquals( r_line , t_line)
        #self.mv.deleteMol('hsg1')
        self.mv.deleteMol(mol)
        #self.mv.deleteMol('ind_out')
        self.mv.deleteMol(lig)


    def test_readGPF(self):
        """
        ADgpf_readGPF
        """
        test_list = [ ('gridcenter',  [2.5, 6.5, -7.5] ), ('spacing',  0.375 ),
                      ('sol_par',  [] ),
                      ('OHB',  1 ), ('smooth',  0.5 ), 
                      ('gridfld',  'hsg1.maps.fld' ), ('gridcenterAuto',  0 ),
                      ('receptor',  'hsg1.pdbqs' ),
                      ('mset',  'CNOSHHH' ), ('nbp_r_eps',  [] ),
                      ('types',  'CANOH' ), ('NHB',  1 ), ('SHB',  1 ), 
                      ('elecmap',  'hsg1.e.map' ), ('dielectric',  -0.1146 ), 
                      ('constant',  [] ), ('npts',  [60, 60, 60] ), 
                      ('map',  'hsg1.H.map' )]

        test_dict_readGPF = {}
        for i,j in test_list:
            test_dict_readGPF[i] = j

        self.mv.ADgpf_readGPF('hsg1.gpf')
        for k, v in test_dict_readGPF.items():
            if v!=self.mv.gpo[k]['value']:
                print k,':', v, ' != ', self.mv.gpo[k]['value']
            self.assertEquals( self.mv.gpo[k]['value'] , v)


    def test_selectCenter(self):
        """
        ADgpf_selectCenter
        """
        from AutoDockTools.autogpfCommands import cenCross
        self.mv.readMolecule('1crn.pdbqs')
        mol = self.mv.Mols[-1]
        self.mv.loadModule('bondsCommands')
        #NB: fix this: selectCenter tries to updateBox etc which can't
        #work if the form hasn't been built because of self.spacewheel...
        self.mv.ADgpf_setGrid.buildForm()
        self.mv.buildBondsByDistance('1crn')
        self.mv.ADgpf_selectCenter("1crn: :PRO36:CB")
        at = self.mv.allAtoms.get(lambda x: x.full_name()=='1crn: :PRO36:CB')[0]
        self.mv.GUI.VIEWER.Redraw()
        self.assertEquals( round(cenCross.vertexSet.vertices.array[0][0],3) , round(at.coords[0],3))
        self.assertEquals( round(cenCross.vertexSet.vertices.array[0][1],3) , round(at.coords[1],3))
        self.assertEquals( round(cenCross.vertexSet.vertices.array[0][2],3) , round(at.coords[2],3))
        self.mv.ADgpf_selectCenter("1crn: :TYR29:CZ")
        self.mv.GUI.VIEWER.Redraw()
        at2 = self.mv.allAtoms.get(lambda x: x.full_name()=='1crn: :TYR29:CZ')[0]
        self.assertEquals( round(cenCross.vertexSet.vertices.array[0][0],3) , round(at2.coords[0],3))
        self.assertEquals( round(cenCross.vertexSet.vertices.array[0][1],3) , round(at2.coords[1],3))
        self.assertEquals( round(cenCross.vertexSet.vertices.array[0][2],3) , round(at2.coords[2],3))
        self.mv.ADgpf_setGrid.Accept_cb()
        #self.mv.deleteMol('1crn')
        self.mv.deleteMol(mol)
        



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

    #global mv

    def tearDown(self):
        """
        clean-up
        """
        #print 'in dpf tearDown'
        global ct, totalCt
        #reset dpo
        from AutoDockTools.DockingParameters import DockingParameters
        self.mv.dpo = DockingParameters()
        self.mv.dpo.vf = self.mv
        #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
            print "CLOSING test_result"
            self.logfile.close()
            print "CLOSED test_result"


    def test_setDpo(self):
        """
        ADdpf_setDpo
        """
        #test dpo values:
        test_list = [('qstep',100.0),('fld', 'hsg1.maps.fld'),
                     ('ga_mutation_rate',0.05),
                     ('tran0', 10.0), ('ls_search_freq' , 0.10),
                     ('ga_cauchy_beta', 2.0), ('runs', 100), ('dstep',100.0),
                     ('analysis', 0), #('gausstorcon_list', []),
                     ('e0max', [0.0, 20000]), #('gausstorcon', []),
                     ('about', [1.0, 2.0, 3.0]), ('select','a'), ('tstep', [100.0]),
                     ('rtrf', 0.01), ('sw_max_fail',10), #('showtorpen', 1),
                     ('outlev', 0), ('rt0', 10.0), ('trnrf', 10.0),
                     ('dihe0', 10), ('cluster', 7), ('simanneal', 0),
                     ('set_ga', 0), ('map', 7), # ('barrier', 20000.0),
                     ('ga_run', 100), ('ga_pop_size', 100), ('quarf', 10.0),
                     ('move', 'sam'), ('set_psw1', 0),
                     ('dihrf', 10.0), ('sw_max_succ', 10), ('ga_num_evals', 100000),
                     ('ga_cauchy_alpha', 0.02), ('quat0', 10), ('rejs', 10),
                     ('sw_max_its', 1000), #('hardtorcon', []),
                     ('intelec', 1),
                     ('ndihe', 10), ('linear_schedule', 0), ('set_sw1', 1),
                     ('accs', 100), ('ga_num_generations', 10000),
                     ('extnrg', 10000.0), ('intnbp_r_eps', None),
                     ('types', 'ACOH'), ('seed', ['pid', 17]),
                     ('ga_elitism', 10), ('do_local_only', 100),
                     ('cycles', 100), ('do_global_only', 100), ('rmsref', 17),
                     ('torsdof', [0, 0.5]),# ('hardtorcon_list', []),
                     ('write_all_flag', 1), ('ga_window_size', 100),
                     ('sw_lb_rho', 0.1), ('ga_crossover_rate', 0.2),
                     ('sw_rho', 0.5), ('rmstol', 4.0)]

        test_dict = {}
        for i,j in test_list:
            test_dict[i] = j

        dpo = self.mv.dpo
        self.mv.ADdpf_readMacromolecule('hsg1.pdbqs')
        # macromolecule dependent fields:
        self.assertEquals( self.mv.dpo['fld']['value'] , 'hsg1.maps.fld')
        self.mv.ADdpf_readFormattedLigand('ind.out.pdbq')
        lig = self.mv.Mols[-1]
        # ligand dependent fields:
        self.assertEquals( self.mv.dpo['move']['value'] , 'ind.out.pdbq')
        self.assertEquals( self.mv.dpo['torsdof']['value'] , [14, .3113])
        self.assertEquals( abs(self.mv.dpo['about']['value'][0] - .3689) <.001, 1)
        self.assertEquals( abs(self.mv.dpo['about']['value'][1] - -.2148) <.001, 1)
        self.assertEquals( abs(self.mv.dpo['about']['value'][2] - -4.9865) <.001, 1)
        #check entries in dpo:
        dpo = self.mv.dpo
        for k, v in test_dict.items():
            #print 'testing ', k ,' - ', v
            apply(self.mv.ADdpf_setDpo,(), {k:v})
            #print dpo[k]
            self.assertEquals( dpo[k]['value'] , v)
        self.mv.deleteMol(lig)


    def test_chooseFormattedLigand(self):
        """
        ADdpf_chooseFormattedLigand
        """
        dpo = self.mv.dpo
        self.mv.readMolecule('ind.out.pdbq')
        mol = self.mv.Mols[-1]
        self.mv.displayLines('ind_out')
        self.mv.buildBondsByDistance('ind_out')
        self.mv.ADdpf_chooseFormattedLigand('ind_out')
        # ligand dependent fields:
        self.assertEquals( self.mv.dpo.ligand.name , 'ind_out')
        self.assertEquals( self.mv.dpo['move']['value'] , 'ind.out.pdbq')
        self.assertEquals( self.mv.dpo['torsdof']['value'] , [14, .3113])
        self.assertEquals( abs(self.mv.dpo['about']['value'][0] - .3689) <.001, 1)
        self.assertEquals( abs(self.mv.dpo['about']['value'][1] - -.2148) <.001, 1)
        self.assertEquals( abs(self.mv.dpo['about']['value'][2] - -4.9865) <.001, 1)
        #self.mv.deleteMol('ind_out')
        self.mv.deleteMol(mol)


    def test_readFormattedLigand(self):
        """
        ADdpf_readFormattedLigand
        """
        self.mv.ADdpf_readFormattedLigand('ind.out.pdbq')
        mol = self.mv.Mols[-1]
        self.assertEquals( len(self.mv.Mols[-1].allAtoms), 49)
        #self.mv.ADdpf_initLigand.Accept_cb()
        self.assertEquals( self.mv.dpo.ligand_filename , 'ind.out.pdbq')
        #this is not good
        # ligand dependent fields:
        self.assertEquals( self.mv.dpo.ligand.name , 'ind_out')
        self.assertEquals( self.mv.dpo['types']['value'] , 'CANOH')
        self.assertEquals( self.mv.dpo['move']['value'] , 'ind.out.pdbq')
        self.assertEquals( self.mv.dpo['torsdof']['value'] == [14, .3113],1)
        self.assertEquals( abs(self.mv.dpo['about']['value'][0] - .3689) <.001,1)
        self.assertEquals( abs(self.mv.dpo['about']['value'][1] - -.2148) <.001,1)
        self.assertEquals( abs(self.mv.dpo['about']['value'][2] - -4.9865) <.001,1)
        #self.mv.ADdpf_initLigand.Close_cb()
        #self.mv.deleteMol('ind_out')
        self.mv.deleteMol(mol)


    def test_initLigand(self):
        """
        ADdpf_initLigand
        """
        import Tkinter
        self.mv.ADdpf_readFormattedLigand('ind.out.pdbq')
        mol = self.mv.Mols[-1]
        #this is not good
        #self.assertEquals(self.mv.dpo.ligand.name , 'ind_out')
        self.assertEquals(self.mv.dpo['rmsref']['value'] , 'ind.out.pdbq')
        self.assertEquals(self.mv.dpo['types']['value'] , 'CANOH')
        # ligand dependent fields:
        c = self.mv.ADdpf_initLigand
        #print 'c.ndiheMsgStr=', c.ndiheMsgStr.get()[-2:]
        self.assertEquals( strip(c.ndiheMsgStr.get()[-2:]) , '6')
        #print 'c.ligMsgStr=', c.ligMsgStr.get()[-12:]
        self.assertEquals( c.ligMsgStr.get()[-12:] , 'ind.out.pdbq')
        #print 'c.centerMsgStr=', c.centerMsgStr.get()
        self.assertEquals( c.centerMsgStr.get()[-19:] , '0.369 -0.215 -4.987')
        #print 'c.typeMsgStr=', c.typesMsgStr.get()
        self.assertEquals( c.typesMsgStr.get()[-5:] , 'CANOH')
        #print 'c.tdofMsgStr=', c.tdofMsgStr.get()
        self.assertEquals( strip(c.tdofMsgStr.get()[-2:]) , '14')
        #print 'c.torsdofcoeff=', c.torsdofcoeff.get()
        self.assertEquals( strip(c.torsdofcoeff.get()) , '0.3113')
        #print 'c.tran0=',c.tran0.get()
        self.assertEquals( c.tran0.get() , 'random')
        #print 'c.quat0=',c.quat0.get()
        self.assertEquals( c.quat0.get() , 'random')
        #print 'c.about=',c.about.get()
        self.assertEquals( c.about.get() , ' 0.369 -0.215 -4.987')
        #print 'c.types=',c.types.get()
        self.assertEquals( c.types.get() , 'CANOH')
        ##print c.barrier.get()
        #self.assertEquals( c.barrier.get() , '')
        #are these IntVars or StringVars
        #print 'c.initTransType=',c.initTransType.get()
        #print type(c.initTransType.get())
        self.assertEquals( c.initTransType.get() , 1)
        #print 'c.initQuatType=',c.initQuatType.get()
        self.assertEquals( c.initQuatType.get() , 1)
        #print 'hasattr(self.mv.dpo, ligand)=', hasattr(self.mv.dpo, 'ligand')
        self.assertEquals( self.mv.dpo.ligand.name , 'ind_out')
        self.assertEquals( self.mv.dpo['move']['value'] , 'ind.out.pdbq')
        self.assertEquals( self.mv.dpo['torsdof']['value'] , [14, .3113])
        self.assertEquals( abs(self.mv.dpo['about']['value'][0] - .3689) <.001, 1)
        self.assertEquals( abs(self.mv.dpo['about']['value'][1] - -.2148) <.001, 1)
        self.assertEquals( abs(self.mv.dpo['about']['value'][2] - -4.9865) <.001, 1)
        #reset stuff in self.mv
        #self.mv.deleteMol('ind_out')
        self.mv.deleteMol(mol)

        
    def test_chooseMacromolecule(self):
        """
        ADdpf_chooseMacromolecule
        """
        self.mv.readMolecule('hsg1.pdbqs')
        mol = self.mv.Mols[-1]
        #check that the read was ok:
        self.assertEquals( len(mol.allAtoms) , 1844)
        self.mv.displayLines(mol)
        self.mv.buildBondsByDistance(mol)
        self.mv.ADdpf_chooseMacromolecule(mol)
        # macromolecule dependent fields:
        self.assertEquals( self.mv.dpo.receptor_filename , 'hsg1.pdbqs')
        self.assertEquals( self.mv.dpo.molstem , 'hsg1')
        #this isn't set by this command (?)
        #self.assertEquals( self.mv.dpo.receptor.name , 'hsg1')
        self.assertEquals( self.mv.dpo['fld']['value'] , 'hsg1.maps.fld')
        #self.mv.deleteMol('hsg1')
        self.mv.deleteMol(mol)



    def test_readMacromolecule(self):
        """
        ADdpf_readMacromolecule
        """
        dpo = self.mv.dpo
        self.mv.ADdpf_readMacromolecule('hsg1.pdbqs')
        # macromolecule dependent fields:
        self.assertEquals( self.mv.dpo.receptor_filename , 'hsg1.pdbqs')
        #self.assertEquals( self.mv.dpo.receptor.name , 'hsg1')
        self.assertEquals( self.mv.dpo.receptor_stem , 'hsg1')
        self.assertEquals( self.mv.dpo.molstem , 'hsg1')
        #dpf_readMacromolecule DOES NOT add molecule
        #self.mv.deleteMol('hsg1')


    def test_setDockingParameters(self):
        """
        ADdpf_setDockingParameters
        """
        #dpo keys:
        param_list = ['dstep', 'e0max', 'emaxRetries', 'extnrg', 'intelec', 'outlev', 'qstep', 'rmsref', 'rmstol', 'seed1', 'seed2', 'tstep', 'write_all_flag']
        #test values:
        value_list = ['100.0', 1000.0, 20000.0, '2000.0', '1', 0, '100.0', 'fred', '1.0', 'time', 'pid', '4.0', 1]
        test_list = [
                    ('dstep', '100.0'),
                    ('e0max','1000.0'),
                    ('emaxRetries','20000.0'),
                    ('extnrg','2000.0'),
                    ('intelec','1'),
                    ('outlev','0'),
                    ('qstep','100.0'),
                    ('rmsref','fred'),
                    ('rmsref_flag',1),
                    ('rmstol','4.0'),
                    ('tstep','4.0'),
                    ('write_all_flag',1)]
        test_dict = {}
        for i,j in test_list:
            test_dict[i] = j

        #the variables for setting the ranNumLib and randomnumbevariables have to be
        #handled specially:
                    #('ranNumLib',1),
                    #('ranNumVar1',2),
                    #('ranNumVar2',1),
            c = self.mv.ADdpf_setDockingParameters
            c.guiCallback()
            for tup in test_list:
                k = tup[0]
                v = tup[1]
                #these are TkStringVars so can't use setattr
                #setattr(c,k,str(v))
                var = getattr(c, k)
                var.set(v)
                #exec('c.'+k+'.set('+"v"+')')
            c.ranNumVar1.set('0')
            c.ranNumVar2.set('0')
            c.ifd.entryByName['userSeedEnt1']['widget'].delete(0,'end')
            c.ifd.entryByName['userSeedEnt1']['widget'].insert(0,'17')
            c.ifd.entryByName['userSeedEnt2']['widget'].delete(0,'end')
            c.ifd.entryByName['userSeedEnt2']['widget'].insert(0,'34')
            # update dpo
            c.Accept_cb()
            #check entries in dpo:
            dpo = self.mv.dpo
            for k, v in test_dict.items():
#                if k!='emaxRetries':
#                    print 'testing ', k ,' - ', v, 'vs ', dpo[k]['value']
#                    print 'type(v)= ', type(v)
#                    print 'type(dpo val)= ', type(dpo[k]['value'])
#                else:
#                    print 'testing ', k ,' - ', v, 'vs ', dpo['e0max']['value'][1]
#                    print 'type(v)= ', type(v)
#                    print 'type(dpo val)= ', type(dpo['e0max']['value'][1])
                if k=='tstep':
                    #self.assertEquals( str(dpo[k]['value'][0]) , str(v)) previous form
                    self.assertEquals( str(dpo[k]['value']) , str(v)) # 2012 format 
                elif k=='e0max':
                    self.assertEquals( str(dpo['e0max']['value'][0]) , str(v))
                elif k=='emaxRetries':
                    self.assertEquals( str(dpo['e0max']['value'][1]) , str(v))
                else:
                    self.assertEquals( str(dpo[k]['value']) , str(v))
            

    def test_read(self):
        """
        ADdpf_read
        """
        #default dpo values:
        test_list = [('qstep',50.0),('fld', 'hsg1.maps.fld'),
                     ('ga_mutation_rate',0.02),
                     ('tran0', 'random'), ('ls_search_freq' , 0.06),
                     ('ga_cauchy_beta', 1.0), ('runs', 10), ('dstep',50.0),
                     ('analysis', 1),# ('gausstorcon_list', []),
                     ('about', [0.3689,-0.2148,-4.9865]), 
                     ('e0max', [0.0, 10000]), #('gausstorcon', []),
                     ('select','m'), ('tstep', 2.0),
                     ('rtrf', 0.95), ('sw_max_fail', 4),# ('showtorpen', 0),
                     ('outlev', 1), ('rt0', 616.0), ('trnrf', 1.0),
                     ('dihe0', 'random'), ('simanneal', 1),
                     ('set_ga', 1), ('map', 'hsg1.e.map'),# ('barrier', 10000.0),
                     ('ga_run', 10), ('ga_pop_size', 150), ('quarf', 1.0),
                     ('move', 'ind.out.pdbq'), ('set_sw1', 1),
                     ('dihrf', 1.0), ('sw_max_succ', 4), ('ga_num_evals', 2500000),
                     ('ga_cauchy_alpha', 0.0), ('quat0', 'random'), ('rejs', 25000),
                     ('sw_max_its', 300),
                     #('hardtorcon', []),
                     ('intelec', 0),
                     ('ndihe', 6), ('linear_schedule', 1), 
                     ('accs', 25000), ('ga_num_generations', 27000),
                     ('extnrg', 1000.0), ('intnbp_r_eps', [2.0, 0.00297, 12, 6]),
                     ('types', 'CANOH'), ('seed', ['pid', 'time']),
                     ('ga_elitism', 1), ('do_local_only', 50),
                     ('cycles', 50), ('do_global_only', 50), 
                     ('torsdof', [14, 0.3113]),# ('hardtorcon_list', []),
                     ('write_all_flag', 0), ('ga_window_size', 10),
                     ('sw_lb_rho', 0.01), ('ga_crossover_rate', 0.8),
                     ('sw_rho', 1.0), ('rmstol', 2.0)]

        test_dict = {}
        for i,j in test_list:
            test_dict[i] = j
        from AutoDockTools.DockingParameters import DockingParameters
        self.mv.dpo = DockingParameters()
        self.mv.ADdpf_read('hsg1_ind.dpf')
        #check entries in dpo:
        dpo = self.mv.dpo
        for k, v in test_dict.items():
            #print 'testing ', k ,' - ', v
            #if dpo[k]['value']!=v:
            #    print k, ':', dpo[k]['value'], ' ', v
            self.assertEquals( dpo[k]['value'] , v)


    def test_setGAparameters(self):
        """
        ADdpf_setGAparameters
        """
        param_list = ['ga_cauchy_alpha','ga_cauchy_beta','ga_crossover_rate','ga_elitism','ga_mutation_rate','ga_num_evals','ga_num_generations','ga_pop_size','ga_run','ga_window_size']

        value_list = ['100', '0.01', '1.5',  '2', '0.05', '2500000', '270000', '200', '20', '20']


        test_list = [ ('ga_cauchy_alpha', '0.01'),
                    ('ga_cauchy_beta', '1.5'),
                    ('ga_crossover_rate', '0.9'),
                    ('ga_elitism', '2'),
                    ('ga_mutation_rate', '0.05'),
                    ('ga_num_evals', '2500000'),
                    ('ga_num_generations', '270000'),
                    ('ga_pop_size', '200'),
                    ('ga_run', '20'),
                    ('ga_window_size', '20')]


        test_dict = {}
        for i,j in test_list:
            test_dict[i] = j

            c = self.mv.ADdpf_setGAparameters
            c.guiCallback()
            for tup in test_list:
                k = tup[0]
                v = tup[1]
                var = getattr(c, k)
                var.set(v) 
            # update dpo
            c.Accept_cb()
            #check entries in dpo:
            dpo = self.mv.dpo
            for k, v in test_dict.items():
                self.assertEquals(str(dpo[k]['value']) , str(v))



    def test_setSAparameters(self):
        """
        ADdpf_setSAparameters
        """
        #default dpo values:
        param_list = ['accs', 'linear_schedule', 'cycles', \
                    'trnrf', 'dihrf', 'rt0', 'rtrf', 'quarf', \
                    'select', 'runs', 'rejs']
        value_list = ['200', 0, '100', '2.0', '2.0', '2.0',  \
                    '0.47', '2.0', 'l', '20', '200']

        test_list = [ ('accs', 200), 
                      ('linear_schedule', 0),
                      ('cycles', 100), 
                      ('trnrf', 2.0),
                      ('dihrf', 2.0), 
                      ('rt0', 2.0),
                      ('rtrf', 0.47),
                      ('quarf', 2.0),
                      ('select', 'l'),
                      ('runs', 20), 
                      ('rejs', 200)] 

        test_dict = {}
        for i,j in test_list:
            test_dict[i] = j

            c = self.mv.ADdpf_setSAparameters
            c.guiCallback()
            for i in range(11):
                k = param_list[i]
                v = value_list[i]
                var = getattr(c, k)
                var.set(v)
            # update dpo
            c.Accept_cb()
            dpo = self.mv.dpo
            #check entries in dpo:
            dpo = self.mv.dpo
            for k, v in test_dict.items():
                #print 'testing ', k ,' - ', v, 'against ', dpo[k]['value']
                #print 'type(dpo val)= ', type(dpo[k]['value'])
                self.assertEquals(str(dpo[k]['value']) , str(v))

            


    def test_setLSparameters(self):
        """
        ADdpf_setLSparameters
        """
        #default dpo values:

        #dpo keys:
        param_list = ['do_local_only','sw_max_its', \
                       'sw_max_succ','sw_max_fail','sw_rho',\
                      'sw_lb_rho','ls_search_freq', 'set_psw1', 'set_sw1']

        #test values:
        value_list = ['100', '600', '8', '8', '2.0', '0.02', '0.12', 0, 1]

        test_list = [
                    ('do_local_only', '100'),
                    ('sw_max_its','600'),
                    ('sw_max_succ','8'),
                    ('sw_max_fail','8'),
                    ('sw_rho','2.0'),
                    ('sw_lb_rho','0.02'),
                    ('ls_search_freq','0.12'),
                    ('set_psw1',0),
                    ('set_sw1',1)]


        test_dict = {}
        for i,j in test_list:
            test_dict[i] = j

            c = self.mv.ADdpf_setLSparameters
            c.guiCallback()
            for i in range(len(param_list)):
                k = param_list[i]
                v = value_list[i]
                var = getattr(c, k)
                var.set(v)
            # update dpo
            c.Accept_cb()
            #check entries in dpo:
            dpo = self.mv.dpo
            for k, v in test_dict.items():
                #print 'testing ', k ,' - ', v, 'against ', dpo[k]['value']
                #print 'type(dpo val)= ', type(dpo[k]['value'])
                assert str(dpo[k]['value']) == str(v)


    def test_writeSA(self):
        """
        ADdpf_writeSA
        """
        self.mv.ADdpf_readMacromolecule('hsg1.pdbqs')
        #mol = self.mv.Mols[-1]
        self.mv.ADdpf_readFormattedLigand('ind.out.pdbq')
        lig = self.mv.Mols[-1]
        self.mv.ADdpf_writeSA('test_SA.dpf')
        #test
        fptr = open('test_SA.dpf')
        allLines = fptr.readlines()
        #print 'len(allLines)=', len(allLines)
        rptr = open('ref_SA.dpf')
        refLines = rptr.readlines()
        #print 'len(refLines)=', len(refLines)
        self.assertEquals( len(allLines), len(refLines))
        for i in range(len(refLines)):
            t_line = allLines[i]
            r_line = refLines[i]
            if r_line!=t_line:
                print i, '-', t_line
            self.assertEquals( r_line , t_line)
        #self.mv.deleteMol('ind_out')
        self.mv.deleteMol(lig)


    def test_writeGA(self):
        """
        ADdpf_writeGA
        """
        self.mv.ADdpf_readMacromolecule('hsg1.pdbqs')
        self.mv.ADdpf_readFormattedLigand('ind.out.pdbq')
        lig = self.mv.Mols[-1]
        self.mv.ADdpf_writeGA('test_GA.dpf')
        #test
        fptr = open('test_GA.dpf')
        allLines = fptr.readlines()
        #print 'len(allLines)=', len(allLines)
        rptr = open('ref_GA.dpf')
        refLines = rptr.readlines()
        #print 'len(refLines)=', len(refLines)
        self.assertEquals( len(allLines), len(refLines))
        for i in range(len(refLines)):
            t_line = allLines[i]
            r_line = refLines[i]
            if r_line!=t_line:
                print i, '-', t_line
            self.assertEquals( r_line , t_line)
        #self.mv.deleteMol('ind_out')
        self.mv.deleteMol(lig)



    def test_writeLS(self):
        """
        ADdpf_writeLS
        """
        self.mv.ADdpf_readMacromolecule('hsg1.pdbqs')
        self.mv.ADdpf_readFormattedLigand('ind.out.pdbq')
        lig = self.mv.Mols[-1]
        self.mv.ADdpf_writeLS('test_LS.dpf')
        #test
        fptr = open('test_LS.dpf')
        allLines = fptr.readlines()
        #print 'len(allLines)=', len(allLines)
        rptr = open('ref_LS.dpf')
        refLines = rptr.readlines()
        #print 'len(refLines)=', len(refLines)
        self.assertEquals( len(allLines), len(refLines))
        for i in range(len(refLines)):
            t_line = allLines[i]
            r_line = refLines[i]
            if r_line!=t_line:
                print i, '-', t_line
            self.assertEquals( r_line , t_line)
        #self.mv.deleteMol('ind_out')
        self.mv.deleteMol(lig)


    def test_writeGALS(self):
        """
        ADdpf_writeGALS
        """
        self.mv.ADdpf_readMacromolecule('hsg1.pdbqs')
        self.mv.ADdpf_readFormattedLigand('ind.out.pdbq')
        lig = self.mv.Mols[-1]
        self.mv.ADdpf_writeGALS('test_GALS.dpf')
        #test
        fptr = open('test_GALS.dpf')
        allLines = fptr.readlines()
        #print 'len(allLines)=', len(allLines)
        rptr = open('ref_GALS.dpf')
        refLines = rptr.readlines()
        #print 'len(refLines)=', len(refLines)
        self.assertEquals( len(allLines), len(refLines))
        for i in range(len(refLines)):
            t_line = allLines[i]
            r_line = refLines[i]
            if r_line!=t_line:
                print i, '-', t_line
            self.assertEquals( r_line , t_line)
        #self.mv.deleteMol('ind_out')
        self.mv.deleteMol(lig)

                


class ADanalyze_BaseTests(AD_BaseTests):
    """
    setUp + tearDown form a fixture: working environment for the testing code
    """
    #global mv


    def tearDown(self):
        """
        clean-up
        """
        #print 'in gpf tearDown'
        global ct, totalCt
        #reset docked
        from AutoDockTools.Docking import Docking
        self.mv.docked = None
        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
            print "CLOSING test_result"
            self.logfile.close()
            print "CLOSED test_result"


    def test_readDlg(self):
        self.mv.ADanalyze_readDLG("ind.dlg")
        self.assertEqual(self.mv.docked.dlo_list[0].filename, "ind.dlg")
        self.assertEqual(self.mv.docked.ligMol.name, "ind_out")
        self.assertEqual(len(self.mv.docked.ch.conformations), 10)
        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)
        self.assertEqual(dlo.macroFile, 'hsg1.pdbqs')
        self.assertEqual(dlo.macroStem, 'hsg1')
        self.mv.ADanalyze_deleteDLG('ind.dlg')
        self.assertEqual(self.mv.docked, None)
        #self.mv.deleteMol(mv.Mols[-1])


    def test_readGrid(self):
        self.mv.ADanalyze_readDLG("ind.dlg")
        self.mv.ADanalyze_showGridIsocontours("hsg1.O.map", log=0)
        ##self.mv.deleteMol(mv.Mols[-1])






if __name__ == '__main__':
    unittest.main()


#def test_main(result):
#    if len(sys.argv):
#        directory = os.path.split(sys.argv[0])[0]
#        if len(directory):
#            os.chdir(directory)

#    suite = unittest.TestSuite()
#    from test_ADligands import ADligands
#    suite.addTest(unittest.makeSuite(ADligands))
#    #suite.addTest(unittest.makeSuite(ADtutorial_BaseTests))
#    #suite.addTest(unittest.makeSuite(ADtors_BaseTests))
#    #suite.addTest(unittest.makeSuite(ADgpf_BaseTests))
#    #suite.addTest(unittest.makeSuite(ADdpf_BaseTests))
#    suite.run(result)
#    return suite


#if __name__ == '__main__':
#    #result = unittest.TestResult()
#    #ste = test_main(result)
#    #raise 'abc'
#    unittest.main()
