Example #1
0
def build_gmx(protein, outdir, forcefield='ffamber99p', protocol='racecar2'):
    """Builds a gromacs project according to the specs in the pipelineProtein object.  Assumes
    the protein.pdbfile is in the right (AMBER) format."""

    if os.path.exists(outdir) == False:
        os.mkdir(outdir)

    baseName = protein.getBasename(protein.pdbfile)
    gromacsOut = baseName + "_final"
    g = System(protein.pdbfile,
               finalOutputDir=outdir,
               finalOutputName=gromacsOut,
               useff=forcefield)
    g.setup.setSaltConditions(protein.salt, protein.saltconc)
    if protein.boxProtocol == 'small':
        g.setup.set_boxType = 'octahedron'
        g.setup.set_boxSoluteDistance(
            1.5)  # periodic box margin distance, in nanometers
    elif protein.boxProtocol == 'big':
        g.setup.set_boxType = 'octahedron'
        g.setup.setUseAbsBoxSize(True)
        g.setup.setAbsBoxSize(
            '8.0')  # periodic box absolute size, in nanometers (string)

    g.prepare(outname=gromacsOut,
              outdir=outdir,
              verbose=True,
              cleanup=False,
              debug=DEBUG,
              protocol='racecar2',
              checkForFatalErrors=True)
Example #2
0
def shoveItThrough(protein, forcefield):

    thisdir = os.curdir

    # determine base name
    print "PDB File: " + protein.pdbfile
    print "Sequence File: " + protein.seqfile
    extInd = protein.seqfile.rindex(".")
    baseName = protein.seqfile[0:extInd]

    # run gromacs setup
    if (1):
        outname = baseName + "_final"
        g = System(protein.pdbfile, useff=forcefield)
        g.setup.setSaltConditions(protein.salt, protein.saltconc)
        g.setup.set_boxSoluteDistance(
            0.9
        )  # <--- ***Greg!!!*** <--- periodic box margin distance, in nanometers
        outdir = os.path.abspath(os.path.join(thisdir, baseName))
        print 'Writing equilibration directory to', outdir, '...'
        if os.path.exists(outdir) == False:
            os.mkdir(outdir)
        g.prepare(outname=outname,
                  outdir=outdir,
                  verbose=True,
                  cleanup=False,
                  debug=DEBUG,
                  protocol='racecar2',
                  checkForFatalErrors=True)
Example #3
0
def shoveItThrough(protein):

    # determine base name
    print "PDB File: " + protein.pdbfile
    print "Sequence File: " + protein.seqfile
    extInd = protein.seqfile.rindex(".")
    baseName = protein.seqfile[0:extInd]

    # run modelPDB
    if (1):
        modelPDBOut = baseName + "_modelPDB_out.pdb"
        myModel = modelPDB.ModelPDB()
        myModel.makeModel(protein.pdbfile, protein.seqfile, modelPDBOut)

    # run mcce
    if (1):
        mcceOut = baseName + "_mcce_out.pdb"
        mcceOut = os.path.abspath(mcceOut)
        prmFile = '../../mccetools/prmfiles/run.prm.quick'
        prmFile = os.path.abspath(prmFile)
        params = mcce.read_paramfile(prmFile)
        mcce.print_prm(params)
        mcce.protonatePDB(modelPDBOut,
                          mcceOut,
                          protein.pH,
                          os.environ['MCCE_LOCATION'],
                          cleanup=True,
                          prmfile=prmFile)

    # run gromacs setup
    if (1):
        gromacsOut = baseName + "_final.pdb"
        forcefield = 'ffamber99p'
        # g = system.GromacsSystem(mcceOut, useff=forcefield)    # the old gromacstools way
        g = System(mcceOut, useff=forcefield)
        g.setup.setSaltConditions(protein.salt, protein.saltconc)
        g.setup.set_boxSoluteDistance(
            0.9
        )  # <--- ***Greg!!!*** <--- periodic box margin distance, in nanometers
        thisOutDir = os.path.join(thisdir, baseName)
        print 'Writing equilibration directory to', thisOutDir, '...'
        if os.path.exists(thisOutDir) == False:
            os.mkdir(thisOutDir)

        g.prepare(outname=gromacsOut,
                  outdir=thisOutDir,
                  verbose=True,
                  cleanup=False,
                  debug=DEBUG,
                  protocol='racecar2',
                  checkForFatalErrors=True)

    # cleanup
    if not DEBUG:
        os.remove(modelPDBOut)
        os.remove(mcceOut)
Example #4
0
def shoveItThrough(protein):

    # determine base name
    print "PDB File: " + protein.pdbfile
    print "Sequence File: " + protein.seqfile
    extInd = protein.seqfile.rindex(".")
    baseName = protein.seqfile[0:extInd]

    # run modelPDB
    if 1:
        modelPDBOut = baseName + "_modelPDB_out.pdb"
        myModel = modelPDB.ModelPDB()
        myModel.makeModel(protein.pdbfile, protein.seqfile, modelPDBOut)

    # run mcce
    if 1:
        mcceOut = baseName + "_mcce_out.pdb"
        mcceOut = os.path.abspath(mcceOut)
        prmFile = "../../mccetools/prmfiles/run.prm.quick"
        prmFile = os.path.abspath(prmFile)
        params = mcce.read_paramfile(prmFile)
        mcce.print_prm(params)
        mcce.protonatePDB(modelPDBOut, mcceOut, protein.pH, os.environ["MCCE_LOCATION"], cleanup=True, prmfile=prmFile)

    # run gromacs setup
    if 1:
        gromacsOut = baseName + "_final.pdb"
        forcefield = "ffamber99p"
        # g = system.GromacsSystem(mcceOut, useff=forcefield)    # the old gromacstools way
        g = System(mcceOut, useff=forcefield)
        g.setup.setSaltConditions(protein.salt, protein.saltconc)
        g.setup.set_boxSoluteDistance(0.9)  # <--- ***Greg!!!*** <--- periodic box margin distance, in nanometers
        thisOutDir = os.path.join(thisdir, baseName)
        print "Writing equilibration directory to", thisOutDir, "..."
        if os.path.exists(thisOutDir) == False:
            os.mkdir(thisOutDir)

        g.prepare(
            outname=gromacsOut,
            outdir=thisOutDir,
            verbose=True,
            cleanup=False,
            debug=DEBUG,
            protocol="racecar2",
            checkForFatalErrors=True,
        )

    # cleanup
    if not DEBUG:
        os.remove(modelPDBOut)
        os.remove(mcceOut)
Example #5
0
def build_gmx(protein, outdir, forcefield='ffamber99p', protocol='racecar2'):
    """Builds a gromacs project according to the specs in the pipelineProtein object.  Assumes
    the protein.pdbfile is in the right (AMBER) format."""


    if os.path.exists(outdir) == False:
        os.mkdir(outdir)

    baseName = protein.getBasename( protein.pdbfile )
    gromacsOut = baseName + "_final"
    g = System(protein.pdbfile, finalOutputDir=outdir, finalOutputName=gromacsOut, useff=forcefield)
    g.setup.setSaltConditions(protein.salt, protein.saltconc)
    if protein.boxProtocol == 'small':
        g.setup.set_boxType = 'octahedron'
        g.setup.set_boxSoluteDistance(1.5)   # periodic box margin distance, in nanometers
    elif protein.boxProtocol == 'big':
        g.setup.set_boxType = 'octahedron'
        g.setup.setUseAbsBoxSize(True)
        g.setup.setAbsBoxSize('8.0')   # periodic box absolute size, in nanometers (string)

    g.prepare(outname=gromacsOut, outdir=outdir, verbose=True, cleanup=False, debug=DEBUG, protocol='racecar2', checkForFatalErrors=True)
Example #6
0
def shoveItThrough(protein, forcefield):
    
    thisdir = os.curdir
    
    # determine base name
    print "PDB File: " + protein.pdbfile
    print "Sequence File: " + protein.seqfile
    extInd = protein.seqfile.rindex(".")
    baseName = protein.seqfile[0:extInd]
        
    # run gromacs setup
    if (1):
        outname = baseName + "_final"
        g = System(protein.pdbfile, useff=forcefield)
        g.setup.setSaltConditions(protein.salt, protein.saltconc)
        g.setup.set_boxSoluteDistance(0.9)   # <--- ***Greg!!!*** <--- periodic box margin distance, in nanometers 
        outdir = os.path.abspath(os.path.join(thisdir, baseName))
        print 'Writing equilibration directory to',outdir,'...'
        if os.path.exists(outdir) == False:
            os.mkdir(outdir)
        g.prepare(outname=outname, outdir=outdir, verbose=True, cleanup=False, debug=DEBUG, protocol='racecar2', checkForFatalErrors=True)
Example #7
0
def shoveit(protein,
            outdir,
            forcefield='ffamber99p',
            protocol='racecar2',
            captermini=False,
            debug=False,
            verbose=True,
            cleanup=False,
            implicitOptions=None,
            useTable=None,
            MultiChain=False,
            SkipMCCE=False):
    """Shoves a pipelineProtein object through the entire MODELLER -> MCCE --> gromacs pipeline.

    For capping the termini with ACE and NH2:
    
    The Modeller program has a nice way of doing
    residue 'patches', so this will be used for adding the caps.  The program will do the following:

    1. Thread the sequence via Modeller, which will patch the termini caps--> PDB
    2. Calculate the protonation state via MCCE (which will know how to handle ACE and NH2 residues because
       of the patches ace.tpl and nh2.tpl in param04 and param08 --> PDB with ffamber-named residues
    3. feed through gromacstools in normal fashion

    OPTIONS

    MultiChain     If set to True, will thread a multichain model.  NOTE: the sequence of the 
                   mutiple chains (in the protein object) must be demarcated by '/'.  Example:
                   AKEEFWVY/AWEKKLELEQVID

    """

    thisdir = '%s' % os.path.abspath(os.curdir)
    protein.setup(
        outdir
    )  # Set up modelPDBout filenames and such using the basename of the outdir
    protein.print_info()

    # Build a PDB model from the pdbTemplate using MODELLER
    if MultiChain:
        thread_model(protein.pdbfile,
                     protein.seqfile,
                     protein.modelPDBout,
                     captermini=captermini)
    else:
        thread_model(protein.pdbfile,
                     protein.seqfile,
                     protein.modelPDBout,
                     captermini=captermini)

    # run mcce
    mcceOut = os.path.abspath(protein.mccePDBout)
    if SkipMCCE:
        # reformat the MODELLER PDB with the right names
        fin = open(protein.modelPDBout, 'r')
        modelPDBlines = fin.readlines()
        fin.close()
        npdb = mcce.rename.nest_pdb(modelPDBlines)
        outlines = mcce.rename.unnest_pdb(
            mcce.rename.rename_MODELLER_termini(npdb))
        fout = open(mcceOut, 'w')
        fout.writelines(outlines)
        fout.close()
        print 'Writing PDB to', mcceOut
    else:
        prmFile = '../../mccetools/prmfiles/run.prm.quick'
        prmFile = os.path.abspath(prmFile)
        if (captermini):
            mcce.protonatePDB(protein.modelPDBout,
                              mcceOut,
                              protein.pH,
                              os.environ['MCCE_LOCATION'],
                              cleanup=cleanup,
                              prmfile=prmFile,
                              renameTermini=False)
        else:
            mcce.protonatePDB(protein.modelPDBout,
                              mcceOut,
                              protein.pH,
                              os.environ['MCCE_LOCATION'],
                              cleanup=cleanup,
                              prmfile=prmFile)

    # run gromacs setup
    if (1):
        gromacsOut = protein.basename + "_final.pdb"
        # g = system.GromacsSystem(mcceOut, useff=forcefield)    # the old gromacstools way
        g = System(mcceOut,
                   finalOutputDir=outdir,
                   finalOutputName=protein.basename,
                   useff=forcefield)
        g.setup.setSaltConditions(protein.salt, protein.saltconc)
        if protein.cosolvent != None:
            g.setup.setCosolventConditions(protein.cosolvent,
                                           protein.cosolventconc)

        if protein.boxProtocol == 'small':
            g.setup.set_boxType = 'octahedron'
            g.setup.set_boxSoluteDistance(
                1.5)  # periodic box margin distance, in nanometers
        elif protein.boxProtocol == 'big':
            g.setup.set_boxType = 'octahedron'
            g.setup.setUseAbsBoxSize(True)
            g.setup.setAbsBoxSize(
                '7.0')  # periodic box absolute size, in nanometers (string)
        elif protein.boxProtocol[0:3] == 'unf':
            g.setup.set_boxType = 'octahedron'
            g.setup.setUseAbsBoxSize(True)
            if protein.boxProtocol == 'unf100':
                g.setup.setAbsBoxSize('10.0')
            if protein.boxProtocol == 'unf110':
                g.setup.setAbsBoxSize('11.0')
            if protein.boxProtocol == 'unf120':
                g.setup.setAbsBoxSize('12.0')

        thisOutDir = os.path.join(thisdir, protein.basename)
        print 'Writing equilibration directory to', thisOutDir, '...'
        if os.path.exists(thisOutDir) == False:
            os.mkdir(thisOutDir)
        os.chdir(thisOutDir)
        g.prepare(verbose=verbose,
                  cleanup=cleanup,
                  debug=debug,
                  protocol=protocol,
                  checkForFatalErrors=True,
                  implicitOptions=implicitOptions,
                  useTable=useTable)

    if (1):
        # cleanup
        if not DEBUG:
            if os.path.exists(protein.modelPDBout):
                os.remove(protein.modelPDBout)
            if os.path.exists(protein.mccePDBout):
                os.remove(protein.mccePDBout)

    os.chdir(thisdir)
Example #8
0
# copy the box dimensions from the template to the coil groStructure
g.boxstring = boxstr

# write the coil.gro (no solvent yet) to a tmpdir
tmpdir = tempfile.mkdtemp()   # temporary directory for unfolded pdbs 
coilgrofile = os.path.join(tmpdir,'coil')
print 'Writing', coilgrofile, '...'
g.write( coilgrofile )   # gromacstools.GromacsData forces us to save this using only the basename
coilgrofile = coilgrofile + '.gro'     # correct to reflect the full name

# write a single molecule of water *.gro to the tmpdir
growater = os.path.join(tmpdir,'ffamber_tip3p_single.gro')
fout = open( growater, 'w')
fout.write("""TIP3P 
3
    1SOL     OW    1   1.336   1.583   0.888  0.1910 -0.3183 -0.5328
    1SOL    HW1    2   1.399   1.553   0.953 -0.9817 -0.4598  0.5822
    1SOL    HW2    3   1.287   1.652   0.933 -2.0169 -1.8033 -0.5086
   2.48706   2.48706   2.48706

""")
fout.close()

# prepare a resolvated grofile from the tempolate grofile -- this will correct the protonation state too
s = System(coilgrofile, finalOutputDir=outdir, finalOutputName=protein.basename, useff=forcefield)   # a gromacstools.System.System() object
s.prepareResolvatedFromTemplate( coilgrofile, groTemplate, growater, protocol=protocol)



Example #9
0
tmpdir = tempfile.mkdtemp()  # temporary directory for unfolded pdbs
coilgrofile = os.path.join(tmpdir, 'coil')
print 'Writing', coilgrofile, '...'
g.write(
    coilgrofile
)  # gromacstools.GromacsData forces us to save this using only the basename
coilgrofile = coilgrofile + '.gro'  # correct to reflect the full name

# write a single molecule of water *.gro to the tmpdir
growater = os.path.join(tmpdir, 'ffamber_tip3p_single.gro')
fout = open(growater, 'w')
fout.write("""TIP3P 
3
    1SOL     OW    1   1.336   1.583   0.888  0.1910 -0.3183 -0.5328
    1SOL    HW1    2   1.399   1.553   0.953 -0.9817 -0.4598  0.5822
    1SOL    HW2    3   1.287   1.652   0.933 -2.0169 -1.8033 -0.5086
   2.48706   2.48706   2.48706

""")
fout.close()

# prepare a resolvated grofile from the tempolate grofile -- this will correct the protonation state too
s = System(coilgrofile,
           finalOutputDir=outdir,
           finalOutputName=protein.basename,
           useff=forcefield)  # a gromacstools.System.System() object
s.prepareResolvatedFromTemplate(coilgrofile,
                                groTemplate,
                                growater,
                                protocol=protocol)
Example #10
0
def shoveit(protein, outdir, forcefield='ffamber99p', protocol='racecar2', captermini=False, debug=False, verbose=True, cleanup=False, implicitOptions=None, useTable=None, MultiChain=False, SkipMCCE=False):
    """Shoves a pipelineProtein object through the entire MODELLER -> MCCE --> gromacs pipeline.

    For capping the termini with ACE and NH2:
    
    The Modeller program has a nice way of doing
    residue 'patches', so this will be used for adding the caps.  The program will do the following:

    1. Thread the sequence via Modeller, which will patch the termini caps--> PDB
    2. Calculate the protonation state via MCCE (which will know how to handle ACE and NH2 residues because
       of the patches ace.tpl and nh2.tpl in param04 and param08 --> PDB with ffamber-named residues
    3. feed through gromacstools in normal fashion

    OPTIONS

    MultiChain     If set to True, will thread a multichain model.  NOTE: the sequence of the 
                   mutiple chains (in the protein object) must be demarcated by '/'.  Example:
                   AKEEFWVY/AWEKKLELEQVID

    """

    thisdir = '%s'%os.path.abspath(os.curdir)
    protein.setup(outdir)    # Set up modelPDBout filenames and such using the basename of the outdir
    protein.print_info()

    # Build a PDB model from the pdbTemplate using MODELLER
    if MultiChain:
        thread_model(protein.pdbfile, protein.seqfile, protein.modelPDBout, captermini=captermini)
    else:
        thread_model(protein.pdbfile, protein.seqfile, protein.modelPDBout, captermini=captermini)
    

    # run mcce
    mcceOut = os.path.abspath(protein.mccePDBout)
    if SkipMCCE:
        # reformat the MODELLER PDB with the right names
        fin = open(protein.modelPDBout,'r')
        modelPDBlines = fin.readlines()
        fin.close()
        npdb = mcce.rename.nest_pdb(modelPDBlines)
        outlines = mcce.rename.unnest_pdb(mcce.rename.rename_MODELLER_termini(npdb))
        fout = open(mcceOut,'w')
        fout.writelines(outlines)
        fout.close() 
        print 'Writing PDB to', mcceOut
    else:
        prmFile = '../../mccetools/prmfiles/run.prm.quick'
        prmFile = os.path.abspath(prmFile)
        if (captermini):
            mcce.protonatePDB(protein.modelPDBout, mcceOut, protein.pH, os.environ['MCCE_LOCATION'], cleanup=cleanup, prmfile=prmFile, renameTermini=False)
        else:
            mcce.protonatePDB(protein.modelPDBout, mcceOut, protein.pH, os.environ['MCCE_LOCATION'], cleanup=cleanup, prmfile=prmFile)
       
    # run gromacs setup
    if (1):
        gromacsOut = protein.basename + "_final.pdb"
        # g = system.GromacsSystem(mcceOut, useff=forcefield)    # the old gromacstools way
        g = System(mcceOut, finalOutputDir=outdir, finalOutputName=protein.basename, useff=forcefield)
        g.setup.setSaltConditions(protein.salt, protein.saltconc)
        if protein.cosolvent != None:
            g.setup.setCosolventConditions(protein.cosolvent, protein.cosolventconc)
 
        if protein.boxProtocol == 'small':
            g.setup.set_boxType = 'octahedron'
            g.setup.set_boxSoluteDistance(1.5)   # periodic box margin distance, in nanometers
        elif protein.boxProtocol == 'big':
            g.setup.set_boxType = 'octahedron'
            g.setup.setUseAbsBoxSize(True)
            g.setup.setAbsBoxSize('7.0')   # periodic box absolute size, in nanometers (string)
        elif protein.boxProtocol[0:3] == 'unf':
            g.setup.set_boxType = 'octahedron'
            g.setup.setUseAbsBoxSize(True)
            if protein.boxProtocol == 'unf100':
                g.setup.setAbsBoxSize('10.0') 
            if protein.boxProtocol == 'unf110':
                g.setup.setAbsBoxSize('11.0')
            if protein.boxProtocol == 'unf120':
                g.setup.setAbsBoxSize('12.0')

        thisOutDir = os.path.join(thisdir, protein.basename)
        print 'Writing equilibration directory to',thisOutDir,'...'
        if os.path.exists(thisOutDir) == False:
            os.mkdir(thisOutDir)
        os.chdir(thisOutDir)
        g.prepare(verbose=verbose, cleanup=cleanup, debug=debug, protocol=protocol, checkForFatalErrors=True, implicitOptions=implicitOptions, useTable=useTable)
     

    if(1):
        # cleanup
        if not DEBUG:
            if os.path.exists(protein.modelPDBout):
                os.remove(protein.modelPDBout)
            if os.path.exists(protein.mccePDBout):
                os.remove(protein.mccePDBout)

    os.chdir(thisdir) 
Example #11
0
def setup_binding_free_energy(protein_pdb_filename, ligand_filename, work_path, nreplicates_solvent = 1, nreplicates_complex = 1):
    """Set up generalized ensemble simulation to calculate a protein-ligand binding free energy.

    ARGUMENTS
      protein_pdb_filename (string) - filename of PDB file for the protein, without any missing heavy atoms and with appropriate protonation state already assigned
      ligand_filename (string) - filename of some type OpenEye can read (e.g. mol2) describing the ligand with suitable docked coordinates
      work_path (string) - directory to place files for binding free energy calculation (created if does not already exist)

    OPTIONAL ARGUMENTS
      nreplicates_solvent (int) - number of replicates to set up of solvated ligand (default: 1)
      nreplicates_complex (int) - number of replicates to set up of the complexed ligand (default: 1)
    """

    # parameters
    forcefield = 'ffamber96' # forcefield
    box_clearance_in_nm = 0.3 # clearance from system to box edges (in nm) # DEBUG set to 1.0

    # gromacs filenames
    pdb2gmx = 'pdb2gmx_d'
    editconf = 'editconf_d'
    genbox = 'genbox_d'
    grompp = 'grompp_d'
    mdrun = 'mdrun_d'

    # Create directory for binding free energy calculation if it doesn't exist.
    #DEBUG os.makedirs(work_path)

    # SET UP PROTEIN TOPOLOGY

    print "\nConstructing protein topology..."

    # Create .top and .gro files for protein using pdb2gmx and desired forcefield
    # look up forcefield index
    lines = readFile(os.path.join(os.environ['GMXDATA'], 'top', 'FF.dat'))
    for forcefield_index in range(1, len(lines)):
        if lines[forcefield_index].find(forcefield) != -1: break
    forcefield_index -= 1
    # run pdb2gmx
    protein_gro_filename = os.path.join(work_path, 'protein.gro')
    protein_top_filename = os.path.join(work_path, 'protein.top')
    command = 'echo %(forcefield_index)d | %(pdb2gmx)s -f %(protein_pdb_filename)s -o %(protein_gro_filename)s -p %(protein_top_filename)s -ignh -H14' % vars()
    print command
    #DEBUG output = commands.getoutput(command)
    #DEBUG print output

    # SET UP LIGAND TOPOLOGY

    print "\nConstructing ligand topology..."

    # Read the ligand into OEMol.
    ligand = readMolecule(ligand_filename, normalize = True)
    
    # Generate GAFF parameters for gromacs for small molecule, using antechamber to generate AM1-BCC charges.
    ligand_top_filename = os.path.join(work_path,'ligand.top')
    ligand_gro_filename = os.path.join(work_path,'ligand.gro')
    #DEBUG parameterizeForGromacs(ligand, topology_filename = ligand_top_filename, coordinate_filename = ligand_gro_filename, charge_model = 'bcc', resname = 'LIG')

    # Modify gromacs topology file for alchemical free energy calculation.
    #DEBUG perturbGromacsTopology(os.path.join(work_path,'ligand.top'), ligand)
    
    # SET UP SOLVATED LIGAND

    print "\nSetting up solvated ligand..."

    # Create directory to contain ligand in solution.
    solvated_ligand_path = os.path.join(work_path, 'solvated-ligand')
    #DEBUG os.makedirs(solvated_ligand_path)

    # Convert gromacs topology to an .itp file suitable for inclusion.
    top_to_itp(os.path.join(work_path,'ligand.top'), os.path.join(solvated_ligand_path,'solute.itp'), moleculetype = 'solute')

    # write enlarged box for solvent
    system_gro_filename = os.path.join(solvated_ligand_path, 'system.gro')
    system_top_filename = os.path.join(solvated_ligand_path, 'system.top')
    command = '%(editconf)s -f %(ligand_gro_filename)s -o %(system_gro_filename)s -bt octahedron -d %(box_clearance_in_nm)f' % vars()
    print command
    output = commands.getoutput(command)
    print output

    # write topology for system
    contents = """
; amber forcefield
#include "ffamber03.itp"

; my molecule
#include "solute.itp"

; TIP3P water
#include "ffamber_tip3p.itp"

[ system ]
solute

[ molecules ]
; Compound        nmols
solute            1
""" % vars()
    writeFile(system_top_filename, contents)

    # solvate
    command = '%(genbox)s -cp %(system_gro_filename)s -cs ffamber_tip3p.gro -o %(system_gro_filename)s -p %(system_top_filename)s' % vars()
    print command
    output = commands.getoutput(command)
    print output
    
    # construct .mdp files
    mdpfile = MdpFile(compose_blocks(['header', 'minimization', 'nonbonded-solvent', 'output']))
    mdpfile.write(os.path.join(solvated_ligand_path, 'minimization-unconstrained.mdp'))

    mdpfile = MdpFile(compose_blocks(['header', 'minimization', 'nonbonded-solvent', 'constraints', 'output']))
    mdpfile.write(os.path.join(solvated_ligand_path, 'minimization-constrained.mdp'))

    mdpfile = MdpFile(compose_blocks(['header', 'dynamics', 'nonbonded-solvent', 'constraints', 'thermostat', 'barostat', 'free-energy', 'output']))
    mdpfile.randomizeSeed() # randomize velocities
    mdpfile.write(os.path.join(solvated_ligand_path, 'production.mdp'))

    # write run script
    contents = """\
#/bin/tcsh

source /Users/jchodera/local/gromacs-3.1.4-fe/i386-apple-darwin8.11.1/bin/GMXRC.csh
    
# unconstrained minimization
%(grompp)s -f minimization-unconstrained.mdp -c system.gro -p system.top -o minimization-unconstrained.tpr -maxwarn 10000
%(mdrun)s -s minimization-unconstrained.tpr -x minimization-unconstrained.xtc -c minimized-unconstrained.gro -e minimization-unconstrained.edr -g minimization-unconstrained.log

# constrained minimization
%(grompp)s -f minimization-constrained.mdp -c minimized-unconstrained.gro -p system.top -o minimization-constrained.tpr -maxwarn 10000
%(mdrun)s -s minimization-constrained.tpr -x minimization-constrained.xtc -c minimized-constrained.gro -e minimization-constrained.edr -g minimization-constrained.log

# production
%(grompp)s -f production.mdp -c minimized-unconstrained.gro -p system.top -o production.tpr -maxwarn 10000
%(mdrun)s -s production.tpr -o production.trr -x production.xtc -c production.gro -e production.edr -g production.log
echo 0 | trjconv_d -f production.xtc -o production.pdb -s production.tpr
""" % vars()
    writeFile(os.path.join(solvated_ligand_path, 'run.sh'), contents)

    # SET UP SOLVATED COMPLEX

    # Create directory to contain complex.
    complex_path = os.path.join(work_path, 'solvated-complex')
    #DEBUG os.makedirs(complex_path)

    # Merge protein and liand .top files.
    complex_top_filename = os.path.join(complex_path, 'complex.top')
    complex_gro_filename = os.path.join(complex_path, 'complex.gro')
    merge_protein_ligand_topologies(protein_top_filename, protein_gro_filename, ligand_top_filename, ligand_gro_filename, complex_top_filename, complex_gro_filename)

    # Alter topology file to use ffamber TIP3P.
    # system.useTIP3P(complex_top_filename)

    # Determine total charge.
    total_charge = totalCharge(complex_top_filename)
    print "total_charge = %f" % total_charge
    
    # Create a System object to help us out.
    system = System(protein_pdb_filename, finalOutputDir = complex_path, finalOutputName = "protein", useff = forcefield)
    system.setup.setSaltConditions('MgCl2', 0.010)
    system.setup.set_boxType = 'octahedron'
    system.setup.set_boxSoluteDistance(box_clearance_in_nm)
    system.files.topfile = complex_top_filename
    system.totalChargeBeforeIons = total_charge

    # Create a periodic boundary conditions box.
    command = '%(editconf)s -bt octahedron -f %(complex_gro_filename)s -o %(complex_gro_filename)s -d %(box_clearance_in_nm)f' % vars()
    output = commands.getoutput(command)    
    print output

    # solvate the box with TIP3P water
    command = '%(genbox)s -cp %(complex_gro_filename)s -cs ffamber_tip3p.gro -o %(complex_gro_filename)s -p %(complex_top_filename)s' % vars()
    output = commands.getoutput(command)
    print output    

    # calculate how many ions to add to the box
    [np, nn, nwaters] = system.counterions()	 
    print "Adding %(np)d positive and %(nn)d negative to %(nwaters)d waters" % vars()
    

    # minimize the system
    ### make a tpr file with grompp
    #grompp = '%s/grompp -f %s -c %s -o %s -p %s '%(os.environ['GMXPATH'], self.files.mdpfile_Minimization, self.files.grofile, self.files.tprfile, self.files.topfile)
    #self.rungmx( grompp, mockrun=self.mockrun, checkForFatalErrors=self.checkForFatalErrors )	

    ### run minimization
    #minimize = '%s/mdrun -v -s %s -c %s '%(os.environ['GMXPATH'], self.files.tprfile, self.files.next_gro() )
    #self.rungmx( minimize, mockrun=self.mockrun, checkForFatalErrors=self.checkForFatalErrors )
    #self.files.increment_gro()    # must increment filename for any new gmx file 
    
    # do the rest of the preparation steps
    #self.postSolvationPreparationSteps()


    # construct .mdp files
    mdpfile = MdpFile(compose_blocks(['header', 'minimization', 'nonbonded-solvent', 'output']))
    mdpfile.write(os.path.join(complex_path, 'minimization-unconstrained.mdp'))

    mdpfile = MdpFile(compose_blocks(['header', 'minimization', 'nonbonded-solvent', 'constraints', 'output']))
    mdpfile.write(os.path.join(complex_path, 'minimization-constrained.mdp'))

    mdpfile = MdpFile(compose_blocks(['header', 'dynamics', 'nonbonded-solvent', 'constraints', 'thermostat', 'barostat', 'free-energy', 'output']))
    mdpfile.randomizeSeed() # randomize velocities
    mdpfile.write(os.path.join(complex_path, 'production.mdp'))    

    # write run script for minimization and production
    contents = """\
#/bin/tcsh

source /Users/jchodera/local/gromacs-3.1.4-fe/i386-apple-darwin8.11.1/bin/GMXRC.csh
    
# unconstrained minimization
%(grompp)s -f minimization-unconstrained.mdp -c system.gro -p system.top -o minimization-unconstrained.tpr -maxwarn 10000
%(mdrun)s -s minimization-unconstrained.tpr -x minimization-unconstrained.xtc -c minimized-unconstrained.gro -e minimization-unconstrained.edr -g minimization-unconstrained.log

# constrained minimization
%(grompp)s -f minimization-constrained.mdp -c minimized-unconstrained.gro -p system.top -o minimization-constrained.tpr -maxwarn 10000
%(mdrun)s -s minimization-constrained.tpr -x minimization-constrained.xtc -c minimized-constrained.gro -e minimization-constrained.edr -g minimization-constrained.log

# production
%(grompp)s -f production.mdp -c minimized-unconstrained.gro -p system.top -o production.tpr -maxwarn 10000
%(mdrun)s -s production.tpr -o production.trr -x production.xtc -c production.gro -e production.edr -g production.log
echo 0 | trjconv_d -f production.xtc -o production.pdb -s production.tpr
""" % vars()
    writeFile(os.path.join(complex_path, 'run.sh'), contents)



    
         
    # Convert gromacs topology to an .itp file suitable for inclusion.
    # top_to_itp(os.path.join(molecule_path,'solute.top'), os.path.join(molecule_path,'solute.itp'), moleculetype = molecule_name)

    return