#
#
#  $Id: test_AD41dpf.py,v 1.8 2014/04/21 17:34:26 rhuey Exp $
#
#


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

mv = None
ct = 0
totalCt = 42


class AD41dpf_BaseTests(unittest.TestCase):
    """
    setUp + tearDown form a fixture: working environment for the testing code
    """
    
        
    def startViewer(self):
        global mv
        if mv is None:
            from MolKit import Read
            import Tkinter
            from Pmv.moleculeViewer import MoleculeViewer
            mv = MoleculeViewer(trapExceptions=False)
            mv.loadModule('deleteCommands', 'Pmv')
            mv.loadModule('selectionCommands', 'Pmv')
            #change warningMsg format
            mv.setUserPreference(('warningMsgFormat', 'printed'), log = 0)
            mv.GUI.toolbarCheckbuttons['ADT']['Variable'].set(1)
            mv.Add_ADT()
            mv.loadModule('autodpfCommands', 'AutoDockTools')
            from AutoDockTools import setADTmode
            setADTmode("AD4.2", mv)
        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
        self.mv.DPF_LIGAND_TYPES = []
        self.mv.DPF_FLEXRES_TYPES = []
        #delete any molecules left due to errors
        for m in self.mv.Mols:
            self.mv.deleteMol(m)
        ct = ct + 1
        if ct==totalCt:
            print 'destroying mv'
            self.mv.Exit(0)
            del self.mv            
    

    def SA_GA_LS_GALS(self):    
        self.mv.AD41dpf_writeSA("ref41_SA.dpf")
        self.mv.AD41dpf_writeGA("ref41_GA.dpf")
        self.mv.AD41dpf_writeLS("ref41_LS.dpf")
        self.mv.AD41dpf_writeGAlS("ref41_GALS.dpf")



class AD41dpf_readDPFTests(AD41dpf_BaseTests):
    
    
    def test_dpf_readdpf(self):
        """reads a dpf and checks
        """ 
        filename = 'ref_1ebg.dpf'
        self.mv.ADdpf_read(filename)
        c=self.mv.dpo
        self.assertEqual(c.dpf_filename, filename)


    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
        """
        filename = "1ebg_rec.pdbqt"
        self.mv.AD41dpf_readMacromolecule(filename)
        self.assertEqual(self.mv.dpo.receptor_filename, filename)
             

    def test_dpf_read_empty_macro_mol(self):
   
        """checks empty macro mol entry
        """
        self.assertRaises(IOError, self.mv.AD41dpf_readMacromolecule, " ")


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

    def test_dpf_replace_random(self):
        """ checks by setting some values in place of random
        """
        self.mv.ADdpf_read('ref41_1ebg.dpf')
        self.mv.AD41dpf_readFormattedLigand("1ebg_lig.pdbqt")
        teststring = "1.0 2.0 3.0"
        self.mv.ADdpf_setDpo(tran0=teststring)
        testfile = "whateveryouwant.dpf"
        self.mv.AD41dpf_writeGALS(testfile)
        fptr=open(testfile)
        alllines=fptr.readlines()
        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_chosen_ligand_name(self):
        
        """checks chosen ligand name
        """
        self.mv.readMolecule('1ebg_lig.pdbqt')
        lig_name = self.mv.Mols[0].name
        self.mv.AD41dpf_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
        """
        filename = '1ebg_lig.pdbqt'
        self.mv.readMolecule(filename)
        m=self.mv.Mols[0]
        self.mv.AD41dpf_chooseFormattedLigand(m.name)
        #4assertions: move is ligand.parser.filename
        #ndihe == ligand.ndihe
        #types == ligand.types
        #about==ligand.center
        mcen = []
        for v in m.center:
            mcen.append(round(v,3))
        self.assertEqual(m.ndihe, self.mv.dpo['ndihe']['value'])
        self.assertEqual(m.types, self.mv.dpo['types']['value'])
        self.assertEqual(mcen, self.mv.dpo['about']['value'])
        #self.assertEqual(m.center, self.mv.dpo['about']['value'])
        self.assertEqual(filename, self.mv.dpo.ligand_filename)
   

    def test_dpf_read_empty_ligand(self):
        """checks empty ligand
        """
        self.assertRaises(IOError, self.mv.AD41dpf_readFormattedLigand, " ")


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

    
#    def test_dpf_read_ligand_widget_exists(self):
#        """checks for widget when read ligand called
#        """
#        self.mv.AD41dpf_readFormattedLigand('1ebg_lig.pdbqt')
#        c = self.mv.AD41dpf_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
        """
        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 after replacing
        """
        d={}
        d['ga_mutation_rate'] =0.5 
        apply(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.AD41dpf_readFormattedLigand("1ebg_lig.pdbqt")
        self.mv.AD41dpf_readMacromolecule("1ebg_rec.pdbqt")
        testfile = "somename.dpf"
        self.mv.AD41dpf_writeGALS(testfile)
        fptr = open(testfile)
        alllines = fptr.readlines()
        fptr.close()
        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.AD41dpf_readFormattedLigand("1ebg_lig.pdbqt")
        self.mv.AD41dpf_readMacromolecule("1ebg_rec.pdbqt")
        d={}
        d['ga_pop_size'] = 2
        apply(self.mv.ADdpf_setGAparameters, (), d)
        testfile = "somename.dpf"
        self.mv.AD41dpf_writeGALS(testfile)
        fptr=open(testfile)
        alllines=fptr.readlines()
        fptr.close()
        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.AD41dpf_readFormattedLigand("1ebg_lig.pdbqt")
        self.mv.AD41dpf_readMacromolecule("1ebg_rec.pdbqt")
        d={}
        d['ls_search_freq'] = 0.02 
        apply(mv.ADdpf_setLSparameters, (), d)
        testfile = "somename.dpf"
        self.mv.AD41dpf_writeGALS(testfile)
        fptr=open(testfile)
        alllines=fptr.readlines()
        ll = [0, 0]
        for i in alllines:        
            if find(i,'ls_search_freq')==0:
                ll=split(i)
        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.AD41dpf_readFormattedLigand("1ebg_lig.pdbqt")
        self.mv.AD41dpf_readMacromolecule("1ebg_rec.pdbqt")
        d={}
        d['ls_search_freq'] = 0.02
        apply(mv.ADdpf_setLSparameters, (), d)
        testfile = "somename.dpf"
        self.mv.AD41dpf_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.0 
        apply(mv.ADdpf_setDockingParameters, (), d)
        self.assertEqual(self.mv.dpo['rmstol']['value'], 4.0)


    def test_search_parameters_docking_parameters_replace(self):
        """checks docking  paarmeters in widget and file are same
        """
        self.mv.AD41dpf_readFormattedLigand("1ebg_lig.pdbqt")
        self.mv.AD41dpf_readMacromolecule("1ebg_rec.pdbqt")
        test_val = 213        
        d={}
        d['sw_max_fail'] =  test_val 
        apply(mv.ADdpf_setDockingParameters, (), d)
        testfile = "somename.dpf"
        self.mv.AD41dpf_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.AD41dpf_readFormattedLigand("1ebg_lig.pdbqt")
        self.mv.AD41dpf_readMacromolecule("1ebg_rec.pdbqt")
        test_val = 312
        d={}
        d['sw_max_its'] =  test_val
        apply(mv.ADdpf_setDockingParameters, (), d)
        testfile = "somename.dpf"
        self.mv.AD41dpf_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 ref41_SA file and test_SA file are same
        """
        self.mv.AD41dpf_readFormattedLigand("1ebg_lig.pdbqt")
        self.mv.AD41dpf_readMacromolecule("1ebg_rec.pdbqt")
        self.mv.AD41dpf_writeSA("test_SA.dpf")
        testptr = open("test_SA.dpf")
        testlines = testptr.readlines()
        refptr = open("ref41_SA.dpf")
        reflines = refptr.readlines()
        refptr.close()
        for refline,testline in zip(reflines,testlines):
            self.assertEqual(refline.split(),testline.split())
            

    def test_ga_dpf_compare_lines(self):
        
        """checks ref41_GA file and test_GA file are same
        """
        self.mv.AD41dpf_readFormattedLigand("1ebg_lig.pdbqt")
        self.mv.AD41dpf_readMacromolecule("1ebg_rec.pdbqt")
        self.mv.AD41dpf_writeGA("test_GA.dpf")
        testptr = open("test_GA.dpf")
        testlines = testptr.readlines()
        refptr = open("ref41_GA.dpf")
        reflines = refptr.readlines()
        refptr.close()
        for refline,testline in zip(reflines,testlines):
            self.assertEqual(refline.split(),testline.split())


    def test_ls_dpf_compare_lines(self):
        
        """checks ref41_LS file and test_LS file are same
        """
        self.mv.AD41dpf_readFormattedLigand("1ebg_lig.pdbqt")
        self.mv.AD41dpf_readMacromolecule("1ebg_rec.pdbqt")
        self.mv.AD41dpf_writeLS("test_LS.dpf")
        testptr = open("test_LS.dpf")
        testlines = testptr.readlines()
        refptr = open("ref41_LS.dpf")
        reflines = refptr.readlines()
        refptr.close()
        for refline,testline in zip(reflines,testlines):
            self.assertEqual(refline.split(),testline.split())


    def test_gals_dpf_compare_lines(self):
        
        """checks ref41_GALS file and test_GALS file are same
        """
        self.mv.AD41dpf_readFormattedLigand("1ebg_lig.pdbqt")
        self.mv.AD41dpf_readMacromolecule("1ebg_rec.pdbqt")
        self.mv.AD41dpf_writeGALS("test_GALS.dpf")
        testptr = open("test_GALS.dpf")
        testlines = testptr.readlines()
        refptr = open("ref41dpf_GALS.dpf")
        reflines = refptr.readlines()
        refptr.close()
        for refline,testline in zip(reflines,testlines):
            self.assertEqual(refline.split(),testline.split())



class AD41dpf_flexResTests(AD41dpf_BaseTests):

    #read receptor
    def test_dpf4_select_rigid_macro_mol(self):
        """select a rigid receptor and checks dpo receptor_filename 
        """
        filename = 'hsg1_rigid.pdbqt'
        self.mv.AD41dpf_readMacromolecule(filename)
        self.assertEqual(self.mv.dpo.receptor_filename,filename)


    #read ligand
    def test_dpf4_read_flex_mol(self):
        """reads flexible input file and checks dpo ligand_filename 
        """
        filename = 'hsg1_flex.pdbqt'
        self.mv.AD41dpf_readFormattedLigand(filename)
        ligand_name = self.mv.Mols[-1].name
        self.assertEqual(self.mv.dpo.ligand.name, ligand_name)
        self.assertEqual('ARG8' in self.mv.Mols[-1].chains.residues.name, True)
        #print "self.mv.Mols[-1].name=", self.mv.Mols[0].name
        args = self.mv.Mols[-1].chains.residues.get(lambda x:x.name=='ARG8')
        self.assertEqual(len(args), 2)
        self.assertEqual(len(args.atoms.bonds[0])>0, True)
    

    #choose ligand
    def test_dpf4_choose_flex_mol(self):
        """read then choose flexible input file; check dpo ligand_filename 
        """
        filename = 'hsg1_flex.pdbqt'
        self.mv.readMolecule(filename)
        ligand_name = self.mv.Mols[-1].name
        self.assertEqual('ARG8' in self.mv.Mols[-1].chains.residues.name, True)
        args = self.mv.Mols[-1].chains.residues.get(lambda x:x.name=='ARG8')
        self.assertEqual(len(args), 2)
        self.assertEqual(len(args.atoms.bonds[0])>0, True)
        self.mv.AD41dpf_chooseFormattedLigand(ligand_name)
        self.assertEqual(self.mv.dpo.ligand.name, ligand_name)



class AD41dpf_formatting_flexResTests(AD41dpf_BaseTests):

    def setUp(self):
        """
        clean-up
        """
        if not hasattr(self, 'mv'):
            self.startViewer()
        for m in self.mv.Mols:
            self.mv.deleteMol(m)
        self.mv.loadModule('autoflexCommands', 'AutoDockTools')
        self.mv.readMolecule('hsg1.pdbqt', ask=0, parser=None)
        self.mv.ADflex_chooseMacro("hsg1")
        from MolKit.molecule import Atom
        self.mv.setIcomLevel(Atom, KlassSet=None)
        self.mv.ADflex_setResidues("::ARG8")
        self.mv.ADflex_setBondRotatableFlag("hsg1:B:ARG8:NE,CZ;", False)
        self.mv.ADflex_setBondRotatableFlag("hsg1:B:ARG8:CZ,NH1;", False)
        self.mv.ADflex_setBondRotatableFlag("hsg1:B:ARG8:CZ,NH2;", False)
        self.mv.ADflex_setBondRotatableFlag("hsg1:A:ARG8:NE,CZ;", False)
        self.mv.ADflex_setBondRotatableFlag("hsg1:A:ARG8:CZ,NH1;", False)
        self.mv.ADflex_setBondRotatableFlag("hsg1:A:ARG8:CZ,NH2;", False)
        self.mv.ADflex_setBondRotatableFlag("hsg1:B:ARG8:CA,CB;", False)
        self.mv.ADflex_setBondRotatableFlag("hsg1:A:ARG8:CA,CB;", False)
        self.mv.ADflex_writeFlexFile('temp_FLEX.pdbqt')
        self.mv.ADflex_writeRigidFile('temp_RIGID.pdbqt')


    #choose receptor
    def test_dpf4_choose_rigid_mol(self):
        """choose new rigid file. check dpo macro_filename 
        """
        written_macro_name = "temp_RIGID.pdbqt"
        self.mv.AD41dpf_readMacromolecule(written_macro_name)
        macro_name = "temp_RIGID"
        self.assertEqual(self.mv.dpo.receptor_stem, macro_name)
        self.assertEqual(self.mv.dpo['fld']['value'], macro_name+".maps.fld")



class AD41dpf_FlexRes_Lig_Order_Tests(AD41dpf_BaseTests):

    def test_gpf4_lig_flexres(self):
        """flexResTests: read a ligand file then a flexres file and check written types
        """
        rigid_filename = 'CathepsinB_rigid.pdbqt'
        flexres_filename = 'CathepsinB_flex.pdbqt'
        ligand_filename = 'FGA3.pdbqt'
        output_filename = 'lig_flexres.dpf'
        self.mv.AD41dpf_readMacromolecule(rigid_filename)
        self.mv.AD41dpf_readFormattedLigand(ligand_filename)
        self.mv.AD41dpf_readFlexRes(flexres_filename)
        self.mv.AD41dpf_writeGALS(output_filename, log=0)
        fptr = open(output_filename)
        lines = fptr.readlines()
        types_line = lines[4]
        ref_line = "ligand_types A C OA HD N SA          # atoms types in ligand\n"
        self.assertEqual(types_line,ref_line)


    def test_gpf4_flexres_lig(self):
        """flexResTests: read a flexres file then a ligand file and check written types
        """
        rigid_filename = 'CathepsinB_rigid.pdbqt'
        flexres_filename = 'CathepsinB_flex.pdbqt'
        ligand_filename = 'FGA3.pdbqt'
        output_filename = 'flexres_lig.dpf'
        self.mv.AD41dpf_readMacromolecule(rigid_filename)
        self.mv.AD41dpf_readFlexRes(flexres_filename)
        self.mv.AD41dpf_readFormattedLigand(ligand_filename)
        self.mv.AD41dpf_writeGALS(output_filename)
        fptr = open(output_filename)
        lines = fptr.readlines()
        types_line = lines[4]
        ref_line = "ligand_types A C OA HD N SA          # atoms types in ligand\n"
        self.assertEqual(types_line,ref_line)


    
    
    def test_rig_flex_lig(self):
        """set rigid filename, flexfilename and open ligand
        """ 
        self.mv.AD41dpf_readMacromolecule('./hsg1_rigid.pdbqt', log=0)
        self.mv.AD41dpf_readFlexRes('./hsg1_FE.pdbqt', log=0)
        self.assertEqual(self.mv.DPF_FLEXRES_TYPES, ['FE'])
        self.mv.AD41dpf_readFormattedLigand('./ind_zero.pdbqt', log=0)
        self.assertEqual(self.mv.DPF_LIGAND_TYPES, ['C'])
        self.assertEqual(self.mv.DPF_FLEXRES_TYPES, ['FE'])
        self.mv.AD41dpf_writeGALS('./zero_FE_rig_GALS.dpf', log=0)
        c=self.mv.dpo
        self.assertEqual(c['ligand_types']['value'], 'C FE')

    
    def test_rig_lig_flex(self):
        """set rigid filename, open ligand and set flexfilename
        """ 
        self.mv.AD41dpf_readMacromolecule('./hsg1_rigid.pdbqt', log=0)
        self.mv.AD41dpf_readFormattedLigand('./ind_zero.pdbqt', log=0)
        self.assertEqual(self.mv.DPF_LIGAND_TYPES, ['C'])
        self.mv.AD41dpf_readFlexRes('./hsg1_FE.pdbqt', log=0)
        self.assertEqual(self.mv.DPF_FLEXRES_TYPES, ['FE'])
        self.mv.AD41dpf_writeGALS('./zero_FE_rig_GALS.dpf', log=0)
        c=self.mv.dpo
        self.assertEqual(c['ligand_types']['value'], 'C FE')

    
    def test_flex_rig_lig(self):
        """set  flex filename, rigid filename and open ligand
        """ 
        self.mv.AD41dpf_readFlexRes('./hsg1_FE.pdbqt', log=0)
        self.assertEqual(self.mv.DPF_FLEXRES_TYPES, ['FE'])
        self.mv.AD41dpf_readMacromolecule('./hsg1_rigid.pdbqt', log=0)
        self.mv.AD41dpf_readFormattedLigand('./ind_zero.pdbqt', log=0)
        self.assertEqual(self.mv.DPF_LIGAND_TYPES, ['C'])
        c=self.mv.dpo
        self.mv.AD41dpf_writeGALS('./zero_rig_GALS.dpf', log=0)
        self.assertEqual(c['ligand_types']['value'], 'C FE')

    
    def test_flex_lig_rig(self):
        """set  flex filename, open ligand and set rigid filename
        """ 
        self.mv.AD41dpf_readFlexRes('./hsg1_FE.pdbqt', log=0)
        self.assertEqual(self.mv.DPF_FLEXRES_TYPES, ['FE'])
        self.mv.AD41dpf_readFormattedLigand('./ind_zero.pdbqt', log=0)
        self.assertEqual(self.mv.DPF_LIGAND_TYPES, ['C'])
        self.mv.AD41dpf_readMacromolecule('./hsg1_rigid.pdbqt', log=0)
        c=self.mv.dpo
        self.mv.AD41dpf_writeGALS('./zero_rig_GALS.dpf', log=0)
        self.assertEqual(c['ligand_types']['value'], 'C FE')

    
    def test_lig_rig_flex(self):
        """set open ligand, set rigid filename and set flex filename
        """ 
        self.mv.AD41dpf_readFormattedLigand('./ind_zero.pdbqt', log=0)
        self.assertEqual(self.mv.DPF_LIGAND_TYPES, ['C'])
        self.mv.AD41dpf_readMacromolecule('./hsg1_rigid.pdbqt', log=0)
        self.mv.AD41dpf_readFlexRes('./hsg1_FE.pdbqt', log=0)
        self.assertEqual(self.mv.DPF_FLEXRES_TYPES, ['FE'])
        self.mv.AD41dpf_writeGALS('./zero_rig_FE_GALS.dpf', log=0)
        c=self.mv.dpo
        self.assertEqual(c['ligand_types']['value'], 'C FE')

    
    def test_lig_flex_rig(self):
        """set open ligand, set flex filename and set rigid filename
        """ 
        self.mv.AD41dpf_readFormattedLigand('./ind_zero.pdbqt', log=0)
        self.assertEqual(self.mv.DPF_LIGAND_TYPES, ['C'])
        self.mv.AD41dpf_readFlexRes('./hsg1_FE.pdbqt', log=0)
        self.assertEqual(self.mv.DPF_FLEXRES_TYPES, ['FE'])
        self.mv.AD41dpf_readMacromolecule('./hsg1_rigid.pdbqt', log=0)
        self.mv.AD41dpf_writeGALS('./zero_FE_rig_GALS.dpf', log=0)
        c=self.mv.dpo
        self.assertEqual(c['ligand_types']['value'], 'C FE')



class AD41dpf_choose_mol2_ligand_Tests(AD41dpf_BaseTests):

    def test_mol2_ligand_test(self):    
        """chooses ligand from mol2 file; checks written dpf
        """
        filename = "zma_test.dpf"
        if os.path.exists(filename):
            cmd = 'rm -f ' + filename
            os.system(cmd)
            print "removed dpf:", filename
        ligfilename = "1xyz_lig.pdbqt"
        if os.path.exists(ligfilename):
            cmd = 'rm -f ' + ligfilename
            os.system(cmd)
            print "removed ligfile: ", ligfilename

        self.mv.readMolecule('zma.mol2')
        self.mv.AD41tors_chooseLigand("zma")
        self.mv.AD41tors_autoRoot()
        self.mv.AD41tors_writeFormattedPDBQT('1xyz_lig.pdbqt')
        self.assertEqual(os.path.exists(ligfilename),True)
        self.mv.AD41dpf_readMacromolecule('./1xyz_rec.pdbqt')
        self.mv.AD41dpf_chooseFormattedLigand("zma", 1)
        self.mv.AD41dpf_writeGALS(filename)
        self.assertEqual(os.path.exists(filename),True)


class AD41dpf_ConfigBaseTests(unittest.TestCase):
    """
    setUp + tearDown form a fixture: working environment for the testing code
    """
    
        
    def startViewer(self):
        global mv
        #print 'in AD41dpf_ConfigBaseTests startViewer'
        if mv is None:
            from MolKit import Read
            import Tkinter
            from Pmv.moleculeViewer import MoleculeViewer
            mv = MoleculeViewer(trapExceptions=False)
            mv.loadModule('deleteCommands', 'Pmv')
            mv.loadModule('selectionCommands', 'Pmv')
            #change warningMsg format
            mv.setUserPreference(('warningMsgFormat', 'printed'), log = 0)
            mv.GUI.toolbarCheckbuttons['ADT']['Variable'].set(1)
            mv.Add_ADT()
            mv.loadModule('autodpfCommands', 'AutoDockTools')
            from AutoDockTools import setADTmode
            setADTmode("AD4.2", mv)
        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, totalConfigCt
        #remove vinaDict
        try:
            delattr(self.mv, 'vinaDict')
        except:
            pass
        from AutoDockTools.DockingParameters import DockingParameters
        self.mv.dpo = DockingParameters()
        self.mv.dpo.vf = self.mv
        #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            
    


class AD41dpf_VinaConfigFileTests(AD41dpf_ConfigBaseTests):
    
    def test_vanilla_config(self):
        """write vanilla config file:
               load ligand + receptor 
               set search space
               write config file
               check whether new config file exists
        """ 
        filename = 'vanilla_config.txt'
        if os.path.exists(filename):
            cmd = "rm " + filename
            os.system(cmd)
        receptorfilename= 'hsg1.pdbqt'
        self.mv.AD41gpf_readMacromolecule(receptorfilename,preserve_input_charges=1)
        ligandfilename= 'ind.pdbqt'
        ligand_in_viewer = False
        for m in self.mv.Mols:
            if m.parser.filename==ligandfilename:
                self.mv.AD41gpf_chooseFormattedLigand('ind', 1, log=0)
                ligand_in_viewer = True
        if not ligand_in_viewer: self.mv.AD41gpf_readFormattedLigand(ligandfilename)
        self.mv.ADgpf_setGpo(gridcenterAuto=0, gridcenter=[2.5, 6.5, -7.5],npts=[50,50,50])
        self.mv.AD41dpf_readMacromolecule('./hsg1.pdbqt', log=0)
        self.mv.AD41dpf_writeCONFIG(filename, center_z='-7.5', 
                                     center_x='2.5', center_y='6.5', size_x='18.75', 
                                     size_y='18.75', size_z='18.75', receptor='hsg1.pdbqt', 
                                     out='ind_out.pdbqt', ligand='ind.pdbqt')
        self.assertEqual(os.path.exists(filename), True)
        for m in self.mv.Mols: self.mv.deleteMol(m)


    def test_vanilla_config_content(self):
        """write vanilla config file:
               load ligand + receptor 
               set search space
               write config file
               check whether new config file matches reference
        """ 
        filename = 'vanilla_config.txt'
        receptorfilename= 'hsg1.pdbqt'
        if os.path.exists(filename):
            cmd = "rm " + filename
            os.system(cmd)
        self.mv.AD41gpf_readMacromolecule(receptorfilename,preserve_input_charges=1)
        ligandfilename= 'ind.pdbqt'
        ligand_in_viewer = False
        for m in self.mv.Mols:
            if m.parser.filename==ligandfilename:
                self.mv.AD41gpf_chooseFormattedLigand('ind', 1, log=0)
                ligand_in_viewer = True
        if not ligand_in_viewer: self.mv.AD41gpf_readFormattedLigand(ligandfilename)
        self.mv.ADgpf_setGpo(gridcenterAuto=0, gridcenter=[2.5, 6.5, -7.5],npts=[50,50,50])
        self.mv.AD41dpf_readMacromolecule('./hsg1.pdbqt', log=0)
        self.mv.AD41dpf_writeCONFIG(filename, center_z='-7.5', 
                                     center_x='2.5', center_y='6.5', size_x='18.75', 
                                     size_y='18.75', size_z='18.75', receptor='hsg1.pdbqt', 
                                     out='ind_out.pdbqt', ligand='ind.pdbqt')
        self.assertEqual(os.path.exists(filename), True)
        testptr = open(filename)
        testlines = testptr.readlines()
        reffilename = 'ref_vanilla_config.txt'
        refptr = open(reffilename)
        reflines = refptr.readlines()
        for tline, rline in zip(testlines, reflines):
            self.assertEqual(tline, rline)
        for m in self.mv.Mols: self.mv.deleteMol(m)


    def test_score_only_config(self):
        """write score_only config file:
               load ligand + receptor 
               set search space
               write score_only config file
               check whether new config file matches reference
        """ 
        filename = 'config_score_only.txt'
        if os.path.exists(filename):
            cmd = "rm " + filename
            os.system(cmd)
        receptorfilename= 'hsg1.pdbqt'
        if 'hsg1' not in self.mv.Mols.name:
            self.mv.AD41gpf_readMacromolecule(receptorfilename,preserve_input_charges=1)
        ligandfilename= 'ind.pdbqt'
        ligand_in_viewer = False
        for m in self.mv.Mols:
            if m.parser.filename==ligandfilename:
                self.mv.AD41gpf_chooseFormattedLigand('ind', log=0)
                ligand_in_viewer = True
        if not ligand_in_viewer: self.mv.AD41gpf_readFormattedLigand(ligandfilename)
        self.mv.ADgpf_setGpo(gridcenterAuto=0, gridcenter=[2.5, 6.5, -7.5],npts=[50,50,50])
        self.mv.AD41dpf_readMacromolecule('./hsg1.pdbqt', log=0)
        self.mv.AD41dpf_writeCONFIG(filename, receptor='hsg1.pdbqt', ligand='ind.pdbqt',score_only=1)
        self.assertEqual(os.path.exists(filename), True)
        testptr = open(filename)
        testlines = testptr.readlines()
        reffilename = 'ref_config_score_only.txt'
        refptr = open(reffilename)
        reflines = refptr.readlines()
        for tline, rline in zip(testlines, reflines):
            self.assertEqual(tline, rline)
        for m in self.mv.Mols: self.mv.deleteMol(m)


    def test_local_only_config(self):
        """write local_only config file:
               load ligand + receptor 
               set search space
               write local_only config file
               check whether new config file matches reference
        """ 
        filename = 'config_local_only.txt'
        if os.path.exists(filename):
            cmd = "rm " + filename
            os.system(cmd)
        receptorfilename= 'hsg1.pdbqt'
        if 'hsg1' not in self.mv.Mols.name:
            self.mv.AD41gpf_readMacromolecule(receptorfilename,preserve_input_charges=1)
        ligandfilename= 'ind.pdbqt'
        ligand_in_viewer = False
        for m in self.mv.Mols:
            if m.parser.filename==ligandfilename:
                self.mv.AD41gpf_chooseFormattedLigand('ind', log=0)
                ligand_in_viewer = True
        if not ligand_in_viewer: self.mv.AD41gpf_readFormattedLigand(ligandfilename)
        self.mv.ADgpf_setGpo(gridcenterAuto=0, gridcenter=[2.5, 6.5, -7.5],npts=[50,50,50])
        self.mv.AD41dpf_readMacromolecule('./hsg1.pdbqt', log=0)
        self.mv.AD41dpf_writeCONFIG(filename, center_z='-7.5', 
                                     center_x='2.5', center_y='6.5', size_x='18.75', 
                                     size_y='18.75', size_z='18.75', receptor='hsg1.pdbqt', 
                                     out='ind_local_only.pdbqt', ligand='ind.pdbqt',
                                     local_only=True)
        self.assertEqual(os.path.exists(filename), True)
        testptr = open(filename)
        testlines = testptr.readlines()
        reffilename = 'ref_config_local_only.txt'
        refptr = open(reffilename)
        reflines = refptr.readlines()
        for tline, rline in zip(testlines, reflines):
            self.assertEqual(tline, rline)
        for m in self.mv.Mols: self.mv.deleteMol(m)


if __name__ == '__main__':
    test_cases = [
        'AD41dpf_BaseTests',
        'AD41dpf_readDPFTests',
        'AD41dpf_flexResTests',
        'AD41dpf_formatting_flexResTests',
        'AD41dpf_FlexRes_Lig_Order_Tests',
        'AD41dpf_choose_mol2_ligand_Tests',
        'AD41dpf_VinaConfigFileTests',
            ]
    unittest.main( argv=([__name__ ,] + test_cases) )



