#
#
#  $Id: test_ADdpf.py,v 1.9 2014/04/21 17:20:00 rhuey Exp $
#
#


import unittest, glob, os
import time
from string import find, split

mv = None
ct = 0
totalCt = 27


class ADdpf_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)
            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


    def setUp(self):
        """
        clean-up
        """
        if not hasattr(self, 'mv'):
            self.startViewer()


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

    def SA_GA_LS_GALS(self):    
        self.mv.ADdpf_writeSA("ref_SA.dpf")
        self.mv.ADdpf_writeGA("ref_GA.dpf")
        self.mv.ADdpf_writeLS("ref_LS.dpf")
        self.mv.ADdpf_writeGAlS("ref_GALS.dpf")



class ADdpf_readDLGTests(ADdpf_BaseTests):
    
    
    
    
    def test_dpf_readdpf(self):
        """reads a dpf and checks
        """ 
        self.mv.ADdpf_read('hsg1_ind.dpf')
        c=self.mv.dpo
        self.assertEqual(c.dpf_filename, "hsg1_ind.dpf")


    def test_dpf_read_empty_dpf(self):
        """checks empty dpf entry
        """
        self.assertRaises(IOError, self.mv.ADdpf_read, " ")

    def test_dpf_read_non_existent_dpf(self):
        """checks non-existent dpf
        """
        self.assertRaises(IOError, self.mv.ADdpf_read, "asd.hfd.dpf")

   
    def test_dpf_set_macro_molecule_file_name(self):
        """checks  macro mols filename
        """
        self.mv.ADdpf_readMacromolecule("hsg1.pdbqs")
        self.assertEqual(self.mv.dpo.receptor_filename,"hsg1.pdbqs")
             
    def test_dpf_read_empty_macro_mol(self):
   
        """checks empty macro mol entry
        """
        self.assertRaises(IOError, self.mv.ADdpf_readMacromolecule, " ")

    def test_dpf_read_non_existent_macro_mol(self):
        """checks non-existent macro mol        """
        self.assertRaises(IOError, self.mv.ADdpf_readMacromolecule, "asd.hfd.dpf")
    

    def test_choosen_macro_name(self):
        filename = 'hsg1.pdbqs'
        self.mv.ADdpf_readMacromolecule(filename)
        self.assertEqual('hsg1', self.mv.dpo.receptor_stem)
        

    def test_dpf_replace_random(self):
        """ checks by setting some values in place of random
        """
                       
        self.mv.ADdpf_read('hsg1_ind.dpf')
        self.mv.ADdpf_readFormattedLigand("ind.out.pdbq")
        teststring = "1.0 2.0 3.0"
        self.mv.ADdpf_setDpo(tran0=teststring)
        testfile = "whateveryouwant.dpf"
        self.mv.ADdpf_writeGALS(testfile)
        fptr = open(testfile)
        alllines = fptr.readlines()
        fptr.close()
        for l in alllines:
            if find(l, 'tran0')==0:
                break
        ll = split(l)
        testsplit = split(teststring)
        for i in range(1, 4):
            self.assertEqual(ll[i], testsplit[i-1])
   

    def test_choosen_ligand_name(self):
        
        """checks choosen ligand name
        """
        filename = 'ind.out.pdbq'
        self.mv.readMolecule(filename)
        lig_name = self.mv.Mols[0].name
        self.mv.ADdpf_chooseFormattedLigand(lig_name)
        self.assertEqual(self.mv.dpo.ligand.name, lig_name)
        
    def test_dpf_set_ligand_parameters(self):
        """ checks ligand name, ndihe, center, types
        """
        self.mv.readMolecule('ind.out.pdbq')
        self.mv.ADdpf_chooseFormattedLigand("ind_out")
        m=self.mv.Mols[0]
        #4assertions: move is ligand.parser.filename
        #ndihe == ligand.ndihe
        #types == ligand.types
        #about==ligand.center
        oldcen = m.getCenter()
        newcen = []
        for i in range(3):
            newcen.append(round(oldcen[i],3))
        m.center = newcen
        self.assertEqual(m.ndihe, self.mv.dpo['ndihe']['value'])
        self.assertEqual(m.types, self.mv.dpo['types']['value'])
        self.assertEqual(m.center, self.mv.dpo['about']['value'])
        self.assertEqual(os.path.basename(m.parser.filename), self.mv.dpo.ligand_filename)
   
    def test_dpf_read_empty_ligand(self):
   
        """checks empty ligand
        """
        self.assertRaises(IOError, self.mv.ADdpf_readFormattedLigand, " ")

    def test_dpf_read_non_existent_ligand(self):
        """checks non-existent ligand
        """
        self.assertRaises(IOError, self.mv.ADdpf_readFormattedLigand, "asd.hfd.dpf")

    
    def test_dpf_read_ligand_widget_exists(self):
        """checks for widget when read ligand called
        """
        self.mv.ADdpf_readFormattedLigand('ind.out.pdbq')
        c =self.mv.ADdpf_initLigand
        self.assertEqual(c.form.root.winfo_ismapped(),1)
        self.assertEqual(c.form.root.withdraw(),'')
     
   
    def test_search_parameters_simulated_annealing_replace(self):
        """checks after replacing rtrf value
        """
        self.mv.ADdpf_setDpo(rtrf='0.5')
        self.assertEqual(self.mv.dpo['rtrf']['value'],'0.5')

    
    def test_search_parameters_ga_parameters_change(self):
        """checks dpo value after replacing 'ga_mutation_rate'
        """
        d={}
        d['ga_mutation_rate'] = 0.5 
        apply(self.mv.ADdpf_setGAparameters, (), d)
        self.assertEqual(self.mv.dpo['ga_mutation_rate']['value'],0.5)
               
    
        
    def test_search_parameters_ga_parameters_values(self):
        """checks values in widget and file are same
        """
        self.mv.ADdpf_readFormattedLigand("ind.out.pdbq")
        self.mv.ADdpf_readMacromolecule("hsg1.pdbqs")
        testfile = "somename.dpf"
        self.mv.ADdpf_writeGALS(testfile)
        fptr=open(testfile)
        alllines=fptr.readlines()
        ll = [0,0]
        for i in alllines:        
            if find(i,'ga_window_size')==0:
                ll = split(i)
                break
        self.assertEqual(str(mv.dpo['ga_window_size']['value']), ll[1])
    

    def test_search_parameters_ga_parameters_replace(self):
        """checks in file after replacing in widget
        """
        self.mv.ADdpf_readFormattedLigand("ind.out.pdbq")
        self.mv.ADdpf_readMacromolecule("hsg1.pdbqs")
        d={}
        d['ga_pop_size'] = 2
        apply(mv.ADdpf_setGAparameters, (), d)
        testfile = "somename.dpf"
        self.mv.ADdpf_writeGALS(testfile)
        fptr=open(testfile)
        alllines=fptr.readlines()
        ll = [0,0]
        for i in alllines:        
            if find(i,'ga_pop_size')==0:
                ll=split(i)
                break
        self.assertEqual(ll[1],'2')
        
   
    def test_search_parameters_ls_parameters_values(self):
        """checks after replacing ls parameter
        """
        d={}
        d['ls_search_freq'] =0.5 
        apply(mv.ADdpf_setLSparameters, (), d)
        self.assertEqual(self.mv.dpo['ls_search_freq']['value'],0.5)
   

    def test_search_parameters_ls_parameters_replace(self):
        """checks ls  paarmeters in widget and file are same
        """
        self.mv.ADdpf_readFormattedLigand("ind.out.pdbq")
        self.mv.ADdpf_readMacromolecule("hsg1.pdbqs")
        d={}
        d['ls_search_freq'] = 0.02 
        apply(mv.ADdpf_setLSparameters, (), d)
        testfile = "somename.dpf"
        self.mv.ADdpf_writeGALS(testfile)
        fptr=open(testfile)
        alllines=fptr.readlines()
        fptr.close()
        ll = [0,0]
        for i in alllines:        
            if find(i,'ls_search_freq')==0:
                ll=split(i)
                break
        self.assertEqual(str(round(mv.dpo['ls_search_freq']['value'],2)),ll[1])

        
    def test_search_parameters_ls_parameters_change(self):
        """checks in file after replacing ls parameters in widget
        """
        self.mv.ADdpf_readFormattedLigand("ind.out.pdbq")
        self.mv.ADdpf_readMacromolecule("hsg1.pdbqs")
        d={}
        d['ls_search_freq'] = 0.02
        apply(mv.ADdpf_setLSparameters, (), d)
        testfile = "somename.dpf"
        self.mv.ADdpf_writeGALS(testfile)
        fptr=open(testfile)
        alllines=fptr.readlines()
        fptr.close()
        ll = [0,0]
        for i in alllines:        
            if find(i,'ls_search_freq')==0:
                ll=split(i)
                break
        self.assertEqual(ll[1], '0.02')
   

    def test_search_parameters_docking_parameters_values(self):
        """checks docking parameters after replacing
        """
        d={}
        d['rmstol'] =4.5 
        apply(mv.ADdpf_setDockingParameters, (), d)
        self.assertEqual(self.mv.dpo['rmstol']['value'],4.5)


    def test_search_parameters_docking_parameters_replace(self):
        """checks docking  paarmeters in widget and file are same
        """
        self.mv.ADdpf_readFormattedLigand("ind.out.pdbq")
        self.mv.ADdpf_readMacromolecule("hsg1.pdbqs")
        test_val = 222
        d={}
        d['sw_max_fail'] = test_val 
        apply(mv.ADdpf_setDockingParameters, (), d)
        testfile = "somename.dpf"
        self.mv.ADdpf_writeGALS(testfile)
        fptr=open(testfile)
        alllines=fptr.readlines()
        fptr.close()
        ll = [0,0]
        for line in alllines:        
            if find(line,'sw_max_fail')>-1:
                ll=split(line)
                break
        self.assertEqual(test_val,int(ll[1]))
        self.assertEqual(self.mv.dpo['sw_max_fail']['value'],test_val)
         

    def test_search_parameters_docking_parameters_change(self):
        """checks in file after replacing ls parameters in widget
        """
        self.mv.ADdpf_read('hsg1_ind.dpf')
        self.mv.ADdpf_readFormattedLigand("ind.out.pdbq")
        test_val = 333
        d={}
        d['sw_max_its'] = test_val
        apply(mv.ADdpf_setDockingParameters, (), d)
        testfile = "somename.dpf"
        self.mv.ADdpf_writeGALS(testfile)
        fptr=open(testfile)
        alllines=fptr.readlines()
        fptr.close()
        ll = [0,0]
        for i in alllines:        
            if find(i,'sw_max_its')==0:
                ll=split(i)
                break
        self.assertEqual(int(ll[1]),test_val)


    def test_sa_dpf_compare_lines(self):
        
        """checks ref_SA file and test_SA file are same
        """
        self.mv.ADdpf_readMacromolecule("hsg1.pdbqs")
        self.mv.ADdpf_readFormattedLigand("ind.out.pdbq")
        self.mv.ADdpf_writeSA("test_SA.dpf")
        testptr = open("test_SA.dpf")
        testlines = testptr.readlines()
        refptr = open("ref_SA.dpf")
        reflines = refptr.readlines()
        for refline,testline in zip(reflines,testlines):
            self.assertEqual(refline,testline)
            

    def test_ga_dpf_compare_lines(self):
        
        """checks ref_GA file and test_GA file are same
        """
        self.mv.ADdpf_readMacromolecule("hsg1.pdbqs")
        self.mv.ADdpf_readFormattedLigand("ind.out.pdbq")
        self.mv.ADdpf_writeGA("test_GA.dpf")
        testptr = open("test_GA.dpf")
        testlines = testptr.readlines()
        refptr = open("ref_GA.dpf")
        reflines = refptr.readlines()
        for refline,testline in zip(reflines,testlines):
            self.assertEqual(refline,testline)

    def test_ls_dpf_compare_lines(self):
        
        """checks ref_LS file and test_LS file are same
        """
        self.mv.ADdpf_readMacromolecule("hsg1.pdbqs")
        self.mv.ADdpf_readFormattedLigand("ind.out.pdbq")
        self.mv.ADdpf_writeLS("test_LS.dpf")
        testptr = open("test_LS.dpf")
        testlines = testptr.readlines()
        refptr = open("ref_LS.dpf")
        reflines = refptr.readlines()
        for refline,testline in zip(reflines,testlines):
            self.assertEqual(refline,testline)


    def test_gals_dpf_compare_lines(self):
        
        """checks ref_GALS file and test_GALS file are same
        """
        self.mv.ADdpf_readFormattedLigand("ind.out.pdbq")
        self.mv.ADdpf_readMacromolecule("hsg1.pdbqs")
        self.mv.ADdpf_readFormattedLigand("ind.out.pdbq")
        self.mv.ADdpf_writeGALS("test_GALS.dpf")
        testptr = open("test_GALS.dpf")
        testlines = testptr.readlines()
        refptr = open("ref_GALS.dpf")
        reflines = refptr.readlines()
        for refline,testline in zip(reflines,testlines):
            self.assertEqual(refline,testline)

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


