usage()
        sys.exit()

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

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

    #try a new random state up to ntries times
    # convert trans to space centered on m
    for new_try in range(ntries):
        #reset coords in working slot to original coords for new try
        m.allAtoms.updateCoords(orig_coords, ind=coord_index)
        TRANS = []
        for ind in range(3):
            #do not subtract origin here, i don't understand why not
            #TRANS.append((random.uniform(-1,1)*tscale)-origin[i])
Beispiel #2
0
class PDBINFO:
    def __init__(self, pdb):
        # if not is valid
        self.exception = None
        try:
            self.mol = Read(pdb)[0]
        except Exception as inst:
            self.exception = inst  # the exception instance
        self.het = []
        self.zn_atoms = []
        self.size = None
        self.center = None
        self.selection_center = None
        self.prot = []
        if not self.exception:
            self.get_info()
            self.center = self.mol.getCenter()

    def __call__(self, *args, **kwargs):
        pass

    def check_select(self, selection):
        res_list = selection.split(';')
        for res in res_list:
            res = res.strip()
            if not res:
                return
            res = res.split(':')
            if not res in [[x[0].name, x[1].name[:3], x[2]]
                           for x in self.prot]:
                return
        return True

    def get_info(self):
        for chain in self.mol.chains:
            for res in chain.residues:
                # exclude water residues
                if res.name[:3] in ['WAT', 'HOH', 'SOL']:
                    continue
                if res.name[:3] == ' ZN':
                    self.zn_atoms.append([chain, res])
                elif res.hetatm():
                    self.het.append([chain, res])
                elif res.name[:3] in aa:
                    self.prot.append([chain, res, res.name[3:]])

    def get_het(self):
        if self.exception:
            return
        het = []
        for lst in self.het:
            het.append([lst[0].name, lst[1].name])
        return het

    def get_zn(self):
        if self.exception:
            return
        zn = []
        for lst in self.zn_atoms:
            zn.append([lst[0].name, lst[1].name])
        return zn

    def get_ha(self):
        if self.exception:
            return
        return len([x for x in self.mol.allAtoms if x.element != "H"])

    def get_box(self):
        if self.exception:
            return
        prot = []
        for res in self.mol.chains.residues:
            if res.name[:3] in aa:
                prot.append(res)
        minimx = min([at.coords[0] for res in prot for at in res.atoms]) - 5
        minimy = min([at.coords[1] for res in prot for at in res.atoms]) - 5
        minimz = min([at.coords[2] for res in prot for at in res.atoms]) - 5
        maximx = max([at.coords[0] for res in prot for at in res.atoms]) + 5
        maximy = max([at.coords[1] for res in prot for at in res.atoms]) + 5
        maximz = max([at.coords[2] for res in prot for at in res.atoms]) + 5
        self.size = [
            int(maximx - minimx),
            int(maximy - minimy),
            int(maximz - minimz)
        ]
        self.center = [(minimx + maximx) / 2, (minimy + maximy) / 2,
                       (minimz + maximz) / 2]

    def get_ligand(self, sel, filename):
        selection = sel.split(':')
        new_mol = None
        for chain in self.mol.chains:
            for res in chain.residues:
                # exclude water residues
                if res.name[:3] in ['WAT', 'HOH', 'SOL', ' ZN']:
                    continue
                if selection == [chain.name, res.name[:3], res.name[3:]]:
                    new_mol = makeMoleculeFromAtoms('ligand', res.atoms)
                    writer = PdbWriter()
                    writer.write(filename,
                                 new_mol.allAtoms,
                                 records=['ATOM', 'HETATM'])
        return new_mol

    def get_center_selection(self, selection):
        # check if exist duplicate and deleted it
        res_list = []
        for x in selection.split(';'):
            x = str(x).strip()
            if x and not x in res_list:
                res_list.append(x)
        coords = []
        for res in res_list:
            res = res.split(':')
            for c in self.mol.chains:
                for mkres in self.mol.chains.residues:
                    if res == [c.name, mkres.name[:3], mkres.name[3:]]:
                        for at in mkres.atoms:
                            coords.append(at.coords)
        x = sum([c[0] for c in coords]) / (len(coords) * 1.0)
        y = sum([c[1] for c in coords]) / (len(coords) * 1.0)
        z = sum([c[2] for c in coords]) / (len(coords) * 1.0)
        self.selection_center = [x, y, z]
        for i in range(3):
            self.selection_center[i] = str(round(self.selection_center[i], 4))

    def get_gyrate(self):
        x = [at.coords[0] for at in self.mol.allAtoms if at.element != "H"]
        y = [at.coords[1] for at in self.mol.allAtoms if at.element != "H"]
        z = [at.coords[2] for at in self.mol.allAtoms if at.element != "H"]
        ref = [sum(x) / len(x), sum(y) / len(y), sum(z) / len(z)]
        xm = [((float(i) - ref[0]), (float(j) - ref[1]), (float(k) - ref[2]))
              for (i, j, k) in zip(x, y, z)]
        numerator = sum(i**2 + j**2 + k**2 for (i, j, k) in xm)
        rg = sqrt(numerator / len(x))
        '''Aspect ratio = 0.23 [Feinstein and Brylinski. Calculating an optimal box size for ligand docking and virtual 
            screening against experimental and predicted binding pockets. Journal of Cheminformatics (2015)]
            If we use the automatic way of detemination of the binding site of the ligand, then the aspect ratio 
            changes 0.21 (this difference results in an additional small margin)
        '''
        return rg / 0.21
Beispiel #3
0
class DockingParameterFileMaker:
    """Accept a <ligand>.pdbq and <receptor>.pdbqs and create
    <ligand>_<receptor>.dpf
    """

    def __init__(self, verbose = None):
        self.verbose = verbose
        self.dpo = DockingParameters()


    def set_ligand(self, ligand_filename): 
        self.ligand_filename = os.path.basename(ligand_filename)
        if verbose:
            print "set ligand_filename to", self.ligand_filename
        self.dpo.set_ligand(ligand_filename)
        #expect a filename like ind.out.pdbq: get 'ind' from it
        self.ligand_stem = string.split(self.ligand_filename,'.')[0]
        if verbose: print "set ligand_stem to", self.ligand_stem
        self.ligand = Read(ligand_filename)[0]
        if self.ligand==None:
            print 'ERROR reading: ', ligand_filename
            return 
        if verbose: 
            print "read ", self.ligand.name
        #set dpo:
        #move
        self.dpo['move']['value'] = self.ligand_filename
        if verbose: print "set move to ", self.dpo['move']['value']
        #ndihe
        #assumes ligand has torTree
        self.dpo['ndihe']['value'] = self.ligand.parser.keys.count("BRANCH")
        #self.dpo['ndihe']['value'] = len(self.ligand.torTree.torsionMap)
        if verbose: print "set ndihe to ", self.dpo['ndihe']['value']
        #torsdof
        #caution dpo['torsdof']['value'] is a list [ndihe, 0.3113]
        self.dpo['torsdof']['value'][0] = self.ligand.TORSDOF
        if verbose: print "set torsdof to ", self.dpo['torsdof']['value']
        #types
        d = {}
        for a in self.ligand.allAtoms:
            d[a.autodock_element] = 1
        sortKeyList =  ['C','A','N','O','S','H','P','n','f','F','c','b','I','M']
        lig_types = ""
        for t in sortKeyList:
            if t in d.keys():
                lig_types = lig_types + t
        self.ligand.types = lig_types
        self.dpo['types']['value'] = self.ligand.types
        if verbose: print "set types to ", self.dpo['types']['value']
        #about
        self.ligand.getCenter()
        cen = self.ligand.center
        self.dpo['about']['value'] =  [round(cen[0],4), round(cen[1],4),\
                                        round(cen[2],4)]
        if verbose: print "set about to ", self.dpo['about']['value']
        

    def set_receptor(self, receptor_filename):
        self.receptor_filename = os.path.basename(receptor_filename)
        self.receptor_stem = string.split(self.receptor_filename, '.')[0]
        self.dpo.set_receptor(receptor_filename)


    #def set_docking_parameters(self, newdict={}):
    def set_docking_parameters(self, **kw):
        """Any docking paramters should be set here
        """
        # like this: 
        # newdict = {'ga_num_evals':1750000, 'ga_pop_size':150,
        #            'ga_run':20, 'rmstol':2.0}
        # self.dpo['<parameter>']['value'] = <new value>
        # eg self.dpo['rmstol']['value'] = 2.0
        for parm, newvalue in kw.items():
            #print "parm=", parm, ' newvalue=', newvalue
            self.dpo[parm]['value'] = newvalue
            if parm=='set_sw1':
                self.dpo['set_psw1']['value'] = not newvalue
            if parm=='set_psw1':
                self.dpo['set_sw1']['value'] = not newvalue


    def write_dpf(self, dpf_filename,
              parm_list = genetic_algorithm_local_search_list):
        if not dpf_filename:
            dpf_filename = "%s%s%s%s" % \
                           (self.ligand_stem, "_",
                            self.receptor_stem, ".dpf")
        # now that we have a filename...
        if self.verbose:
            print "writing ", dpf_filename
        self.dpo.write(dpf_filename, parm_list)
Beispiel #4
0
class DockingParameter42FileMaker:
    """Accept a <ligand>.pdbqt and <receptor>.pdbqt and create
    <ligand>_<receptor>42.dpf
    """
    def __init__(self, verbose=None):
        self.verbose = verbose
        self.dpo = DockingParameters()

    def getTypes(self, molecule):
        if not len(molecule.allAtoms.bonds[0]):
            molecule.buildBondsByDistance()
        ad4_typer = AutoDock4_AtomTyper(verbose=self.verbose)
        ad4_typer.setAutoDockElements(molecule)
        dict = {}
        for a in molecule.allAtoms:
            dict[a.autodock_element] = 1
        d_types = dict.keys()
        d_types.sort()
        mol_types = d_types[0]
        for t in d_types[1:]:
            mol_types = mol_types + " " + t
        if self.verbose:
            print "end of getTypes: types=", mol_types, ' class=', mol_types.__class__
        return mol_types

    def set_write_all(self, value):
        verbose = self.verbose
        self.dpo['write_all_flag']['value'] = True
        if verbose:
            print "set write_all_flag to", self.dpo['write_all_flag']['value']

    def set_ligand(self, ligand_filename):
        verbose = self.verbose
        self.ligand_filename = os.path.basename(ligand_filename)
        if verbose: print "set ligand_filename to", self.ligand_filename
        self.dpo.set_ligand(ligand_filename)
        #expect a filename like ind.out.pdbq: get 'ind' from it
        self.ligand_stem = string.split(self.ligand_filename, '.')[0]
        if verbose: print "set ligand_stem to", self.ligand_stem
        self.ligand = Read(ligand_filename)[0]
        if self.ligand == None:
            print 'ERROR reading: ', ligand_filename
            return
        if verbose: print "read ", self.ligand.name
        #set dpo:
        #move
        self.dpo['move']['value'] = self.ligand_filename
        if verbose: print "set move to ", self.dpo['move']['value']
        #ndihe
        #assumes ligand has torTree
        self.dpo['ndihe']['value'] = self.ligand.parser.keys.count("BRANCH")
        #self.dpo['ndihe']['value'] = len(self.ligand.torTree.torsionMap)
        if verbose: print "set ndihe to ", self.dpo['ndihe']['value']
        #torsdof
        #caution dpo['torsdof4']['value'] is a list [ndihe, 0.274]
        try:
            self.dpo['torsdof4']['value'][0] = self.ligand.TORSDOF
        except:
            print 'setting torsdof to ligand.ndihe=', self.ligand.ndihe
            self.dpo['torsdof4']['value'][0] = self.ligand.ndihe
        if verbose: print "set torsdof4 to ", self.dpo['torsdof4']['value']
        #types
        self.ligand.types = self.getTypes(self.ligand)
        self.dpo['ligand_types']['value'] = self.ligand.types
        if verbose: print "set types to ", self.dpo['ligand_types']['value']
        #about
        self.ligand.getCenter()
        cen = self.ligand.center
        self.dpo['about']['value'] =  [round(cen[0],4), round(cen[1],4),\
                                        round(cen[2],4)]
        if verbose: print "set about to ", self.dpo['about']['value']

    def set_receptor(self, receptor_filename):
        self.receptor_filename = os.path.basename(receptor_filename)
        self.receptor_stem = string.split(self.receptor_filename, '.')[0]
        self.dpo.set_receptor(receptor_filename)

    def set_flexres(self, flexres_filename):
        flexmol = Read(flexres_filename)[0]
        flexres_filename = os.path.basename(flexres_filename)
        self.dpo['flexres_flag']['value'] = True
        self.dpo['flexres']['value'] = flexres_filename
        #make sure each atom type in flexres molecule is in ligand_types
        d = {}
        current_types = self.dpo['ligand_types']['value'].split()
        for t in current_types:
            d[t] = 1
        for a in flexmol.allAtoms:
            d[a.autodock_element] = 1
        self.dpo['ligand_types']['value'] = string.join(d.keys())

    def set_docking_parameters(self, **kw):
        """Any docking parameters should be set here
        """
        # like this:
        # newdict = {'ga_num_evals':1750000, 'ga_pop_size':150,
        #            'ga_run':20, 'rmstol':2.0}
        # self.mv.dpo['<parameter>']['value'] = <new value>
        for parm, newvalue in kw.items():
            self.dpo[parm]['value'] = newvalue
            if parm == 'set_sw1':
                self.dpo['set_psw1']['value'] = not newvalue
            if parm == 'set_psw1':
                self.dpo['set_sw1']['value'] = not newvalue
            if parm == 'flexres':
                self.set_flexres(newvalue)
            if parm == 'write_all':
                self.set_write_all(newvalue)

    def write_dpf(self,
                  dpf_filename,
                  parm_list=genetic_algorithm_local_search_list4_2,
                  pop_seed=False):
        if not dpf_filename:
            dpf_filename = "%s%s%s%s" % \
                           (self.ligand_stem, "_",
                            self.receptor_stem, ".dpf")
        # now that we have a filename...
        # set initial conformation
        if pop_seed:
            self.dpo['tran0']['value'] = self.dpo['about']['value']
            self.dpo['axisangle0']['value'] = '0 0 0 0'
            #self.dpo['quat0']['value'] = '1.0 0. 0. 0.'
            dihe0 = '0. ' * self.dpo['ndihe']['value']
            dihe0.rstrip()
            self.dpo['dihe0']['value'] = dihe0
        if self.verbose:
            print "writing ", dpf_filename
        self.dpo.write42(dpf_filename, parm_list)
class GridParameter4FileMaker:
    """Accept a <ligand>.pdbqt, <receptor>.pdbqt, reference4.gpf and create
    <receptor>4.gpf
    sets gridcenter to center of bounding box
    sets npts according to bounding box
    """
    def __init__(self, verbose=None, size_box_to_include_ligand=True):
        self.verbose = verbose
        self.gpo = GridParameters()
        self.size_box_to_include_ligand = size_box_to_include_ligand

    def read_reference(self, reference_filename):
        if self.verbose: print "reading ", reference_filename
        self.gpo.read4(reference_filename)

    def set_types_from_directory(self, directory):
        if self.verbose:
            print "reading directory ", directory
        filelist = glob.glob(directory + "/*.pdb*")
        if self.verbose:
            print "len(filelist)=", len(filelist)
        ad4_typer = AutoDock4_AtomTyper()
        type_dict = {}
        for f in filelist:
            m = Read(f)[0]
            m.buildBondsByDistance()
            ad4_typer.setAutoDockElements(m)
            for a in m.allAtoms:
                type_dict[a.autodock_element] = 1
            self.getSideLengths(m)  #sets ligand.center
            npts = m.npts
            #only make the box bigger, do NOT make it smaller
            for ix, val in enumerate(self.gpo['npts']['value']):
                if npts[ix] > val:
                    self.gpo['npts']['value'][ix] = npts[ix]
                    if self.verbose:
                        print m.name, " increased grid dimension ", ix, " to ", npts[
                            ix]
        d_types = type_dict.keys()
        if self.verbose:
            print "found ", d_types, " atom types in directory ", directory
        self.gpo['ligand_types']['value'] = string.join(d_types)
        if self.verbose:
            print "now ligand_types is ", self.gpo['ligand_types']['value']

    def set_ligand(self, ligand_filename, center_on_ligand=False):
        self.ligand = Read(ligand_filename)[0]
        if self.ligand == None:
            print 'ERROR reading: ', ligand_filename
            return
        if self.verbose:
            print "read ", self.ligand.name
        ligand_types = self.getTypes(self.ligand)
        self.gpo.set_ligand4(ligand_filename, types=ligand_types)
        #this sets ligand_types, gpo.ligand_stem and gpo.ligand_filename
        if self.verbose:
            print "set gpo.ligand_stem to", self.gpo.ligand_stem
            print "set gpo.ligand_filename to", self.gpo.ligand_filename
            print "set gpo.ligand_types to", self.gpo['ligand_types'][
                'value'].__class__
        #need to get npts
        if self.size_box_to_include_ligand:
            self.getSideLengths(self.ligand)  #sets ligand.center
        #gridcenter IS NOT SET BY THIS!!!
        if center_on_ligand:
            cen = self.ligand.getCenter()
            self.gpo['gridcenter']['value'] =  [round(cen[0],4), round(cen[1],4),\
                                            round(cen[2],4)]
            self.gpo['gridcenterAuto']['value'] = 0
            if self.verbose:
                print "set gridcenter to ", self.gpo['gridcenter']['value']
        #only make the box bigger, do NOT make it smaller
        for ix, val in enumerate(self.gpo['npts']['value']):
            #npts
            if hasattr(self.ligand, 'npts'):
                npts = self.ligand.npts
                if npts[ix] > val:
                    self.gpo['npts']['value'][ix] = npts[ix]
        if self.verbose: print "set npts to ", self.gpo['npts']['value']

    def getTypes(self, molecule):
        if not len(molecule.allAtoms.bonds[0]):
            molecule.buildBondsByDistance()
        ad4_typer = AutoDock4_AtomTyper(verbose=self.verbose)
        ad4_typer.setAutoDockElements(molecule)
        dict = {}
        for a in molecule.allAtoms:
            dict[a.autodock_element] = 1
        d_types = dict.keys()
        d_types.sort()
        mol_types = d_types[0]
        for t in d_types[1:]:
            mol_types = mol_types + " " + t
        if self.verbose:
            print "end of getTypes: types=", mol_types, ' class=', mol_types.__class__
        return mol_types

    def getSideLengths(self, mol):
        c = mol.allAtoms.coords
        maxo = Numeric.maximum.reduce(c)
        mino = Numeric.minimum.reduce(c)
        sideLengths = maxo - mino
        mol.npts = map(int,
                       map(ceil, sideLengths / (self.gpo['spacing']['value'])))
        for ix, npts in enumerate(mol.npts):
            if npts > 126:
                mol.npts[ix] = 126
        #FIX THIS:
        #use this center instead of mol.getCenter which returns averaged
        #coords:
        #this should make sure the ligand fits inside the box
        #mino+(maxo-mino)/2.0
        mol.center = mino + (maxo - mino) / 2.0

    def set_receptor(self, receptor_filename, gpf_filename=None):
        self.receptor = Read(receptor_filename)[0]
        receptor_filename = os.path.basename(receptor_filename)
        if self.receptor == None:
            print 'ERROR reading: ', receptor_filename
            return
        if self.verbose: print "set_receptor filename to ", receptor_filename
        receptor_types = self.getTypes(self.receptor)
        self.gpo.set_receptor4(receptor_filename, types=receptor_types)
        self.receptor_filename = os.path.basename(receptor_filename)
        if hasattr(self, 'receptor'):
            self.receptor_stem = self.receptor.name
        else:
            self.receptor_stem = os.path.splitext(self.receptor_filename)[0]
        #all of this is handled by set_receptor4
        #self.gpo['gridfld']['value'] = self.receptor_stem + '.maps.fld'
        #self.gpo['elecmap']['value'] = self.receptor_stem + '.e.map'
        #self.gpo['dsolvmap']['value'] = self.receptor_stem + '.d.map'
        #this sets gpo.receptor_types, gpo.receptor_stem and gpo.receptor_filename

    def set_grid_parameters(self, **kw):
        """Any grid parameters should be set here
        """
        # like this:
        # should it be **kw
        # kw = {'spacing':1.0, 'receptor_types':'C A NA OA N SA HD MG'}
        # self.mv.gpo['parm']['value'] = <new value>
        # EXCEPT for 'npts' for which value must be 60,60,60
        for parm, newvalue in kw.items():
            if self.verbose:
                print "parm=", parm
                print "newvalue=", newvalue
            if parm == 'gridcenter':
                self.gpo['gridcenterAuto']['value'] = newvalue == 'auto'
            self.gpo[parm]['value'] = newvalue
            if parm == 'npts':
                self.gpo['npts']['value'] = map(int, newvalue.split(','))
            if parm == 'ligand_types':
                if newvalue.find(',') > -1:
                    newvalue = newvalue.replace(',', ' ')
                print "setting ligand_types: newvalue=", newvalue
                self.gpo[parm]['value'] = newvalue

    def write_gpf(self, gpf_filename=None, parm_list=grid_parameter_list4):
        if not gpf_filename:
            gpf_filename = self.receptor_stem + ".gpf"
        # now that we have a filename...
        if self.verbose:
            print "writing ", gpf_filename
            for item in parm_list:
                print item,
            print
        self.gpo.write4(gpf_filename, parm_list)
        usage()
        sys.exit()

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

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

    #try a new random state up to ntries times
    # convert trans to space centered on m
    for new_try in range(ntries):
        #reset coords in working slot to original coords for new try
        m.allAtoms.updateCoords(orig_coords, ind=coord_index)
        TRANS = []
        for ind in range(3):
            #do not subtract origin here, i don't understand why not
            #TRANS.append((random.uniform(-1,1)*tscale)-origin[i])
class DockingParameter4FileMaker:
    """Accept a <ligand>.pdbqt and <receptor>.pdbqt and create
    <ligand>_<receptor>4.dpf
    """

    def __init__(self, verbose = None):
        self.verbose = verbose
        self.dpo = DockingParameters()


    def getTypes(self, molecule):
        if not len(molecule.allAtoms.bonds[0]):
            molecule.buildBondsByDistance()
        ad4_typer = AutoDock4_AtomTyper(verbose=self.verbose)
        ad4_typer.setAutoDockElements(molecule)
        dict = {}
        for a in molecule.allAtoms:
            dict[a.autodock_element] = 1
        d_types = dict.keys()
        d_types.sort()
        mol_types = d_types[0]
        for t in d_types[1:]:
            mol_types = mol_types + " " + t
        if self.verbose: print "end of getTypes: types=", mol_types, ' class=', mol_types.__class__
        return mol_types


    def set_write_all(self, value):
        verbose = self.verbose
        self.dpo['write_all_flag']['value'] = True
        if verbose: print "set write_all_flag to", self.dpo['write_all_flag']['value']


    def set_ligand(self, ligand_filename): 
        verbose = self.verbose
        self.ligand_filename = os.path.basename(ligand_filename)
        if verbose: print "set ligand_filename to", self.ligand_filename
        self.dpo.set_ligand(ligand_filename)
        #expect a filename like ind.out.pdbq: get 'ind' from it
        self.ligand_stem = string.split(self.ligand_filename,'.')[0]
        if verbose: print "set ligand_stem to", self.ligand_stem
        self.ligand = Read(ligand_filename)[0]
        if self.ligand==None:
            print 'ERROR reading: ', ligand_filename
            return 
        if verbose: print "read ", self.ligand.name
        #set dpo:
        #move
        self.dpo['move']['value'] = self.ligand_filename
        if verbose: print "set move to ", self.dpo['move']['value']
        #ndihe
        #assumes ligand has torTree
        self.dpo['ndihe']['value'] = self.ligand.parser.keys.count("BRANCH")
        #self.dpo['ndihe']['value'] = len(self.ligand.torTree.torsionMap)
        if verbose: print "set ndihe to ", self.dpo['ndihe']['value']
        #torsdof
        #caution dpo['torsdof4']['value'] is a list [ndihe, 0.274]
        try:
            self.dpo['torsdof4']['value'][0] = self.ligand.TORSDOF
        except:
            print 'setting torsdof to ligand.ndihe=', self.ligand.ndihe
            self.dpo['torsdof4']['value'][0] = self.ligand.ndihe
        if verbose: print "set torsdof4 to ", self.dpo['torsdof4']['value']
        #types
        self.ligand.types = self.getTypes(self.ligand)
        self.dpo['ligand_types']['value'] = self.ligand.types
        if verbose: print "set types to ", self.dpo['ligand_types']['value']
        #about
        self.ligand.getCenter()
        cen = self.ligand.center
        self.dpo['about']['value'] =  [round(cen[0],4), round(cen[1],4),\
                                        round(cen[2],4)]
        if verbose: print "set about to ", self.dpo['about']['value']
        

    def set_receptor(self, receptor_filename):
        self.receptor_filename = os.path.basename(receptor_filename)
        self.receptor_stem = string.split(self.receptor_filename, '.')[0]
        self.dpo.set_receptor(receptor_filename)


    def set_flexres(self, flexres_filename):
        flexmol = Read(flexres_filename)[0]
        flexres_filename = os.path.basename(flexres_filename)
        self.dpo['flexres_flag']['value'] = True
        self.dpo['flexres']['value'] = flexres_filename
        #make sure each atom type in flexres molecule is in ligand_types
        d = {}
        current_types = self.dpo['ligand_types']['value'].split()
        for t in current_types:
            d[t] = 1
        for a in flexmol.allAtoms:
            d[a.autodock_element] = 1
        self.dpo['ligand_types']['value'] = string.join(d.keys())


    def set_docking_parameters(self, **kw):
        """Any docking parameters should be set here
        """
        # like this: 
        # newdict = {'ga_num_evals':1750000, 'ga_pop_size':150,
        #            'ga_run':20, 'rmstol':2.0}
        # self.mv.dpo['<parameter>']['value'] = <new value>
        for parm, newvalue in kw.items():
            self.dpo[parm]['value'] = newvalue
            if parm=='set_sw1':
                self.dpo['set_psw1']['value'] = not newvalue
            if parm=='set_psw1':
                self.dpo['set_sw1']['value'] = not newvalue
            if parm=='flexres':
                self.set_flexres(newvalue) 
            if parm=='write_all':
                self.set_write_all(newvalue) 


    def write_dpf(self, dpf_filename,
              parm_list = genetic_algorithm_local_search_list4, 
              pop_seed = False):
        if not dpf_filename:
            dpf_filename = "%s%s%s%s" % \
                           (self.ligand_stem, "_",
                            self.receptor_stem, ".dpf")
        # now that we have a filename...
        # set initial conformation
        if pop_seed:
            self.dpo['tran0']['value'] = self.dpo['about']['value']
            self.dpo['axisangle0']['value'] = '0 0 0 0'
            #self.dpo['quat0']['value'] = '1.0 0. 0. 0.'
            dihe0 = '0. '*self.dpo['ndihe']['value']
            dihe0.rstrip()
            self.dpo['dihe0']['value'] = dihe0 
        if self.verbose:
            print "writing ", dpf_filename
        self.dpo.write4(dpf_filename, parm_list)
class GridParameterFileMaker:
    """Accept a <ligand>.pdbq , <receptor>.pdbqs, reference.gpf and create
    <receptor>.gpf
    sets gridcenter to center of bounding box
    sets npts according to bounding box
    """
    def __init__(self, verbose=None, size_box_to_include_ligand=True):
        self.verbose = verbose
        self.gpo = GridParameters()
        self.size_box_to_include_ligand = size_box_to_include_ligand

    def read_reference(self, reference_filename):
        if self.verbose: print "reading ", reference_filename
        self.gpo.read(reference_filename)

    def set_ligand(self, ligand_filename):
        self.ligand_filename = os.path.basename(ligand_filename)
        if self.verbose:
            print "set ligand_filename to", self.ligand_filename
        self.gpo.set_ligand(ligand_filename)
        #expect a filename like ind.out.pdbq: get 'ind' from it
        self.ligand_stem = string.split(self.ligand_filename, '.')[0]
        if self.verbose: print "set ligand_stem to", self.ligand_stem
        self.ligand = Read(ligand_filename)[0]
        #IS THIS USEFUL???
        self.gpo.ligand = self.ligand
        if self.verbose: print "read ", self.ligand.name
        #set gpo:
        #types
        d = {}
        for a in self.ligand.allAtoms:
            d[a.autodock_element] = 1
        sortKeyList = [
            'C', 'A', 'N', 'O', 'S', 'H', 'P', 'n', 'f', 'F', 'c', 'b', 'I',
            'M'
        ]
        lig_types = ""
        for t in sortKeyList:
            if t in d.keys():
                lig_types = lig_types + t
        self.ligand.types = lig_types
        self.gpo['types']['value'] = self.ligand.types
        if self.verbose: print "set types to ", self.gpo['types']['value']
        #gridcenter
        self.ligand.center = self.ligand.getCenter()
        if self.size_box_to_include_ligand:
            self.getSideLengths(self.ligand)  #sets ligand.center
        cen = self.ligand.center
        self.gpo['gridcenter']['value'] =  [round(cen[0],4), round(cen[1],4),\
                                        round(cen[2],4)]
        self.gpo['gridcenterAuto']['value'] = 0
        if self.verbose:
            print "set gridcenter to ", self.gpo['gridcenter']['value']
        #only make the box bigger from npts, do not make it smaller
        for ix, val in enumerate(self.gpo['npts']['value']):
            if hasattr(self.ligand, 'npts'):
                npts = self.ligand.npts
                if npts[ix] > val:
                    if self.verbose:
                        print "increasing ", ix, " grid dimension to ", val
                    self.gpo['npts']['value'][ix] = npts[ix]
        #if self.verbose: print "set npts to ", self.gpo['npts']['value']

    def getSideLengths(self, mol):
        c = mol.allAtoms.coords
        maxo = Numeric.maximum.reduce(c)
        mino = Numeric.minimum.reduce(c)
        sideLengths = maxo - mino
        mol.npts = map(int,
                       map(ceil, sideLengths / (self.gpo['spacing']['value'])))
        for ix, npts in enumerate(mol.npts):
            if npts > 126:
                mol.npts[ix] = 126
        #FIX THIS:
        #use this center instead of mol.getCenter which returns averaged
        #coords:
        #this should make sure the ligand fits inside the box
        #mino+(maxo-mino)/2.0
        mol.center = mino + (maxo - mino) / 2.0

    def set_receptor(self, receptor_filename, gpf_filename=None):
        self.receptor_filename = os.path.basename(receptor_filename)
        self.receptor_stem = string.split(self.receptor_filename, '.')[0]
        self.gpo.set_receptor(receptor_filename)
        #FIX THIS
        #self.gpo['mset']['value'] = self.receptor.types
        self.gpo['types']['value'] = self.ligand.types

    def set_grid_parameters(self, **kw):
        """Any grid parameters should be set here
        """
        # like this:
        # should it be **kw
        # kw = {'spacing':1.0, 'mset':'CNOSHXM'}
        # self.mv.gpo['parm']['value'] = <new value>
        # EXCEPT for 'npts' for which value must be 60,60,60
        for parm, newvalue in kw.items():
            self.gpo[parm]['value'] = newvalue
            if parm == 'npts':
                self.gpo['npts']['value'] = map(int, newvalue.split(','))

    def write_gpf(self, gpf_filename=None, parm_list=grid_parameter_list):
        if not gpf_filename:
            gpf_filename = self.receptor_stem + ".gpf"
        # now that we have a filename...
        if self.verbose:
            print "writing ", gpf_filename
        self.gpo.write(gpf_filename, parm_list)
Beispiel #9
0
class DockingParameterFileMaker:
    """Accept a <ligand>.pdbq and <receptor>.pdbqs and create
    <ligand>_<receptor>.dpf
    """
    def __init__(self, verbose=None):
        self.verbose = verbose
        self.dpo = DockingParameters()

    def set_ligand(self, ligand_filename):
        self.ligand_filename = os.path.basename(ligand_filename)
        if verbose:
            print "set ligand_filename to", self.ligand_filename
        self.dpo.set_ligand(ligand_filename)
        #expect a filename like ind.out.pdbq: get 'ind' from it
        self.ligand_stem = string.split(self.ligand_filename, '.')[0]
        if verbose: print "set ligand_stem to", self.ligand_stem
        self.ligand = Read(ligand_filename)[0]
        if self.ligand == None:
            print 'ERROR reading: ', ligand_filename
            return
        if verbose:
            print "read ", self.ligand.name
        #set dpo:
        #move
        self.dpo['move']['value'] = self.ligand_filename
        if verbose: print "set move to ", self.dpo['move']['value']
        #ndihe
        #assumes ligand has torTree
        self.dpo['ndihe']['value'] = self.ligand.parser.keys.count("BRANCH")
        #self.dpo['ndihe']['value'] = len(self.ligand.torTree.torsionMap)
        if verbose: print "set ndihe to ", self.dpo['ndihe']['value']
        #torsdof
        #caution dpo['torsdof']['value'] is a list [ndihe, 0.3113]
        self.dpo['torsdof']['value'][0] = self.ligand.TORSDOF
        if verbose: print "set torsdof to ", self.dpo['torsdof']['value']
        #types
        d = {}
        for a in self.ligand.allAtoms:
            d[a.autodock_element] = 1
        sortKeyList = [
            'C', 'A', 'N', 'O', 'S', 'H', 'P', 'n', 'f', 'F', 'c', 'b', 'I',
            'M'
        ]
        lig_types = ""
        for t in sortKeyList:
            if t in d.keys():
                lig_types = lig_types + t
        self.ligand.types = lig_types
        self.dpo['types']['value'] = self.ligand.types
        if verbose: print "set types to ", self.dpo['types']['value']
        #about
        self.ligand.getCenter()
        cen = self.ligand.center
        self.dpo['about']['value'] =  [round(cen[0],4), round(cen[1],4),\
                                        round(cen[2],4)]
        if verbose: print "set about to ", self.dpo['about']['value']

    def set_receptor(self, receptor_filename):
        self.receptor_filename = os.path.basename(receptor_filename)
        self.receptor_stem = string.split(self.receptor_filename, '.')[0]
        self.dpo.set_receptor(receptor_filename)

    #def set_docking_parameters(self, newdict={}):
    def set_docking_parameters(self, **kw):
        """Any docking paramters should be set here
        """
        # like this:
        # newdict = {'ga_num_evals':1750000, 'ga_pop_size':150,
        #            'ga_run':20, 'rmstol':2.0}
        # self.dpo['<parameter>']['value'] = <new value>
        # eg self.dpo['rmstol']['value'] = 2.0
        for parm, newvalue in kw.items():
            #print "parm=", parm, ' newvalue=', newvalue
            self.dpo[parm]['value'] = newvalue
            if parm == 'set_sw1':
                self.dpo['set_psw1']['value'] = not newvalue
            if parm == 'set_psw1':
                self.dpo['set_sw1']['value'] = not newvalue

    def write_dpf(self,
                  dpf_filename,
                  parm_list=genetic_algorithm_local_search_list):
        if not dpf_filename:
            dpf_filename = "%s%s%s%s" % \
                           (self.ligand_stem, "_",
                            self.receptor_stem, ".dpf")
        # now that we have a filename...
        if self.verbose:
            print "writing ", dpf_filename
        self.dpo.write(dpf_filename, parm_list)
Beispiel #10
0
    lig = lig[0]
    if not hasattr(lig, 'ndihe'):
        print ligandfile + "molecule has no torsion tree"
        sys.exit()
    lig.buildBondsByDistance()
    # add extra slot to ._coords for changing coordinates
    lig.allAtoms.addConformation(lig.allAtoms.coords)
    #?is this necessary
    lig.allAtoms.setConformation(1)
    ntors = lig.ndihe
    length_of_state = 7 + lig.ndihe
    # @@ handle to the input ligLines
    ligLines = lig.parser.allLines

    #setup StateToCoords object
    origin = lig.getCenter()
    if use_zero_origin or interim_state:
        origin = [0., 0., 0.]
    #note: index of _coords to use is always 1
    lig.stoc = StateToCoords(lig, origin, 1)
    outptr = sys.stdout
    if outputfile:
        outptr = open(outputfile, 'w')

    #if SINGLESTATE:
    # eg:
    #"State: 29.303 14.415 23.603 0.5609 0.4518 0.2662 -0.6406 -20.89 -0.65 81.86 -17.36 28.83 -10.80 -23.98 114.21"
    #states = state.split()
    #['State:', '29.303', '14.415', '23.603', '0.5609', '0.4518', '0.2662', '-0.6406', '-20.89', '-0.65', '81.86', '-17.36', '28.83', '-10.80', '-23.98', '114.21']

    if statefile:
class GridParameter4FileMaker:
    """Accept a <ligand>.pdbqt, <receptor>.pdbqt, reference4.gpf and create
    <receptor>4.gpf
    sets gridcenter to center of bounding box
    sets npts according to bounding box
    """

    def __init__(self, verbose = None, size_box_to_include_ligand=True):
        self.verbose = verbose
        self.gpo = GridParameters()
        self.size_box_to_include_ligand = size_box_to_include_ligand


    def read_reference(self, reference_filename):
        if self.verbose: print "reading ", reference_filename
        self.gpo.read4(reference_filename)


    def set_types_from_directory(self, directory):
        if self.verbose: 
            print "reading directory ", directory
        filelist = glob.glob(directory + "/*.pdb*")
        if self.verbose: 
            print "len(filelist)=", len(filelist)
        ad4_typer = AutoDock4_AtomTyper()
        type_dict = {}
        for f in filelist:
            m = Read(f)[0]
            m.buildBondsByDistance()
            ad4_typer.setAutoDockElements(m)
            for a in m.allAtoms:
                type_dict[a.autodock_element] = 1
            self.getSideLengths(m) #sets ligand.center
            npts = m.npts
            #only make the box bigger, do NOT make it smaller
            for ix, val in enumerate(self.gpo['npts']['value']):
                if npts[ix]>val:
                    self.gpo['npts']['value'][ix] =  npts[ix]
                    if self.verbose: 
                        print m.name, " increased grid dimension ", ix, " to ", npts[ix]
        d_types = type_dict.keys()
        if self.verbose: 
            print "found ", d_types, " atom types in directory ", directory
        self.gpo['ligand_types']['value'] =  string.join(d_types)
        if self.verbose: 
            print "now ligand_types is ", self.gpo['ligand_types']['value']


    def set_ligand(self, ligand_filename, center_on_ligand=False): 
        self.ligand = Read(ligand_filename)[0]
        if self.ligand==None:
            print 'ERROR reading: ', ligand_filename
            return 
        if self.verbose: 
            print "read ", self.ligand.name
        ligand_types = self.getTypes(self.ligand)
        self.gpo.set_ligand4(ligand_filename, types=ligand_types)
        #this sets ligand_types, gpo.ligand_stem and gpo.ligand_filename
        if self.verbose: 
            print "set gpo.ligand_stem to", self.gpo.ligand_stem
            print "set gpo.ligand_filename to", self.gpo.ligand_filename
            print "set gpo.ligand_types to", self.gpo['ligand_types']['value'].__class__
        #need to get npts
        if self.size_box_to_include_ligand:
            self.getSideLengths(self.ligand) #sets ligand.center
        #gridcenter IS NOT SET BY THIS!!!
        if center_on_ligand:
            cen = self.ligand.getCenter()
            self.gpo['gridcenter']['value'] =  [round(cen[0],4), round(cen[1],4),\
                                            round(cen[2],4)]
            self.gpo['gridcenterAuto']['value'] =  0
            if self.verbose: print "set gridcenter to ", self.gpo['gridcenter']['value']
        #only make the box bigger, do NOT make it smaller
        for ix, val in enumerate(self.gpo['npts']['value']):
            #npts
            if hasattr(self.ligand, 'npts'):
                npts = self.ligand.npts
                if npts[ix]>val:
                    self.gpo['npts']['value'][ix] =  npts[ix]
        if self.verbose: print "set npts to ", self.gpo['npts']['value']
        

    def getTypes(self, molecule):
        if not len(molecule.allAtoms.bonds[0]):
            molecule.buildBondsByDistance()
        ad4_typer = AutoDock4_AtomTyper(verbose=self.verbose)
        ad4_typer.setAutoDockElements(molecule)
        dict = {}
        for a in molecule.allAtoms:
            dict[a.autodock_element] = 1
        d_types = dict.keys()
        d_types.sort()
        mol_types = d_types[0]
        for t in d_types[1:]:
            mol_types = mol_types + " " + t
        if self.verbose: 
            print "end of getTypes: types=", mol_types, ' class=', mol_types.__class__
        return mol_types


    def getSideLengths(self, mol):
        c = mol.allAtoms.coords
        maxo = Numeric.maximum.reduce(c)
        mino = Numeric.minimum.reduce(c)
        sideLengths = maxo-mino
        mol.npts = map(int, map(ceil, sideLengths/(self.gpo['spacing']['value'])))
        for ix, npts in enumerate(mol.npts):
            if npts>126:
                mol.npts[ix] = 126
        #FIX THIS:
        #use this center instead of mol.getCenter which returns averaged
        #coords:
        #this should make sure the ligand fits inside the box
        #mino+(maxo-mino)/2.0
        mol.center = mino + (maxo - mino)/2.0


    def set_receptor(self, receptor_filename, gpf_filename=None):
        self.receptor = Read(receptor_filename)[0]
        receptor_filename = os.path.basename(receptor_filename)
        if self.receptor==None:
            print 'ERROR reading: ', receptor_filename
            return 
        if self.verbose: print "set_receptor filename to ", receptor_filename
        receptor_types = self.getTypes(self.receptor)
        self.gpo.set_receptor4(receptor_filename, types=receptor_types)
        self.receptor_filename = os.path.basename(receptor_filename)
        if hasattr(self, 'receptor'):
            self.receptor_stem = self.receptor.name
        else:
            self.receptor_stem = os.path.splitext(self.receptor_filename)[0]
        #all of this is handled by set_receptor4
        #self.gpo['gridfld']['value'] = self.receptor_stem + '.maps.fld'
        #self.gpo['elecmap']['value'] = self.receptor_stem + '.e.map'
        #self.gpo['dsolvmap']['value'] = self.receptor_stem + '.d.map'
        #this sets gpo.receptor_types, gpo.receptor_stem and gpo.receptor_filename


    def set_grid_parameters(self, **kw):
        """Any grid parameters should be set here
        """
        # like this: 
        # should it be **kw
        # kw = {'spacing':1.0, 'receptor_types':'C A NA OA N SA HD MG'}
        # self.mv.gpo['parm']['value'] = <new value>
        # EXCEPT for 'npts' for which value must be 60,60,60
        for parm, newvalue in kw.items():
            if self.verbose:
                print "parm=", parm
                print "newvalue=", newvalue
            if parm=='gridcenter':
                self.gpo['gridcenterAuto']['value'] = newvalue=='auto'
            self.gpo[parm]['value'] = newvalue
            if parm=='npts':
                self.gpo['npts']['value']= map(int, newvalue.split(','))
            if parm=='ligand_types':
                if newvalue.find(',')>-1:
                    newvalue = newvalue.replace(',', ' ')
                print "setting ligand_types: newvalue=", newvalue
                self.gpo[parm]['value']= newvalue


    def write_gpf(self, gpf_filename=None,
              parm_list = grid_parameter_list4):
        if not gpf_filename:
            gpf_filename = self.receptor_stem + ".gpf"
        # now that we have a filename...
        if self.verbose:
            print "writing ", gpf_filename
            for item in parm_list:
                print item,
            print
        self.gpo.write4(gpf_filename, parm_list)
class GridParameterFileMaker:
    """Accept a <ligand>.pdbq , <receptor>.pdbqs, reference.gpf and create
    <receptor>.gpf
    sets gridcenter to center of bounding box
    sets npts according to bounding box
    """

    def __init__(self, verbose = None, size_box_to_include_ligand=True):
        self.verbose = verbose
        self.gpo = GridParameters()
        self.size_box_to_include_ligand = size_box_to_include_ligand


    def read_reference(self, reference_filename):
        if self.verbose: print "reading ", reference_filename
        self.gpo.read(reference_filename)


    def set_ligand(self, ligand_filename): 
        self.ligand_filename = os.path.basename(ligand_filename)
        if self.verbose:
            print "set ligand_filename to", self.ligand_filename
        self.gpo.set_ligand(ligand_filename)
        #expect a filename like ind.out.pdbq: get 'ind' from it
        self.ligand_stem = string.split(self.ligand_filename,'.')[0]
        if self.verbose: print "set ligand_stem to", self.ligand_stem
        self.ligand = Read(ligand_filename)[0]
        #IS THIS USEFUL???
        self.gpo.ligand = self.ligand
        if self.verbose: print "read ", self.ligand.name
        #set gpo:
        #types
        d = {}
        for a in self.ligand.allAtoms:
            d[a.autodock_element] = 1
        sortKeyList =  ['C','A','N','O','S','H','P','n','f','F','c','b','I','M']
        lig_types = ""
        for t in sortKeyList:
            if t in d.keys():
                lig_types = lig_types + t
        self.ligand.types = lig_types
        self.gpo['types']['value'] = self.ligand.types
        if self.verbose: print "set types to ", self.gpo['types']['value']
        #gridcenter
        self.ligand.center = self.ligand.getCenter()
        if self.size_box_to_include_ligand:
            self.getSideLengths(self.ligand) #sets ligand.center
        cen = self.ligand.center
        self.gpo['gridcenter']['value'] =  [round(cen[0],4), round(cen[1],4),\
                                        round(cen[2],4)]
        self.gpo['gridcenterAuto']['value'] =  0
        if self.verbose: print "set gridcenter to ", self.gpo['gridcenter']['value']
        #only make the box bigger from npts, do not make it smaller
        for ix, val in enumerate(self.gpo['npts']['value']):
            if hasattr(self.ligand, 'npts'):
                npts = self.ligand.npts
                if npts[ix]>val:
                    if self.verbose: print "increasing ", ix, " grid dimension to ", val
                    self.gpo['npts']['value'][ix] =  npts[ix]
        #if self.verbose: print "set npts to ", self.gpo['npts']['value']
        

    def getSideLengths(self, mol):
        c = mol.allAtoms.coords
        maxo = Numeric.maximum.reduce(c)
        mino = Numeric.minimum.reduce(c)
        sideLengths = maxo-mino
        mol.npts = map(int, map(ceil, sideLengths/(self.gpo['spacing']['value'])))
        for ix, npts in enumerate(mol.npts):
            if npts>126:
                mol.npts[ix] = 126
        #FIX THIS:
        #use this center instead of mol.getCenter which returns averaged
        #coords:
        #this should make sure the ligand fits inside the box
        #mino+(maxo-mino)/2.0
        mol.center = mino + (maxo - mino)/2.0


    def set_receptor(self, receptor_filename, gpf_filename=None):
        self.receptor_filename = os.path.basename(receptor_filename)
        self.receptor_stem = string.split(self.receptor_filename, '.')[0]
        self.gpo.set_receptor(receptor_filename)
        #FIX THIS
        #self.gpo['mset']['value'] = self.receptor.types
        self.gpo['types']['value'] = self.ligand.types


    def set_grid_parameters(self, **kw):
        """Any grid parameters should be set here
        """
        # like this: 
        # should it be **kw
        # kw = {'spacing':1.0, 'mset':'CNOSHXM'}
        # self.mv.gpo['parm']['value'] = <new value>
        # EXCEPT for 'npts' for which value must be 60,60,60
        for parm, newvalue in kw.items():
            self.gpo[parm]['value'] = newvalue
            if parm=='npts':
                self.gpo['npts']['value']= map(int, newvalue.split(','))


    def write_gpf(self, gpf_filename=None,
              parm_list = grid_parameter_list):
        if not gpf_filename:
            gpf_filename = self.receptor_stem + ".gpf"
        # now that we have a filename...
        if self.verbose:
            print "writing ", gpf_filename
        self.gpo.write(gpf_filename, parm_list)
    lig = lig[0]
    if not hasattr(lig, 'ndihe'):
        print ligandfile + "molecule has no torsion tree"
        sys.exit()
    lig.buildBondsByDistance()
    # add extra slot to ._coords for changing coordinates
    lig.allAtoms.addConformation(lig.allAtoms.coords)
    #?is this necessary
    lig.allAtoms.setConformation(1)
    ntors = lig.ndihe
    length_of_state = 7+lig.ndihe
    # @@ handle to the input ligLines
    ligLines = lig.parser.allLines

    #setup StateToCoords object
    origin = lig.getCenter()
    if use_zero_origin or interim_state:
        origin = [0.,0.,0.]    
    #note: index of _coords to use is always 1
    lig.stoc = StateToCoords(lig, origin, 1)
    outptr = sys.stdout
    if outputfile:
        outptr = open(outputfile, 'w')


    #if SINGLESTATE:
        # eg:
        #"State: 29.303 14.415 23.603 0.5609 0.4518 0.2662 -0.6406 -20.89 -0.65 81.86 -17.36 28.83 -10.80 -23.98 114.21"
        #states = state.split()
        #['State:', '29.303', '14.415', '23.603', '0.5609', '0.4518', '0.2662', '-0.6406', '-20.89', '-0.65', '81.86', '-17.36', '28.83', '-10.80', '-23.98', '114.21']