Пример #1
0
def callgmx(command, stdin=None, print_to_screen=False, print_command=True, **kwargs):
    # Remove backup files.
    rm_gmx_baks(os.getcwd())
    # Call a GROMACS program as you would from the command line.
    if GMXVERSION == 5:
        csplit = ("gmx " + command.replace("gmx", "")).split()
    else:
        if command.split()[0] in gmxprogs:
            csplit = ("g_%s" % command).split()
        else:
            csplit = command.split()
    prog = os.path.join(gmxpath, csplit[0])
    csplit[0] = prog + gmxsuffix
    return _exec(" ".join(csplit), stdin=stdin, print_to_screen=print_to_screen, print_command=print_command, **kwargs)
Пример #2
0
def callgmx(command, stdin=None, print_to_screen=False, print_command=False, **kwargs):
    # Remove backup files.
    rm_gmx_baks(os.getcwd())
    # Call a GROMACS program as you would from the command line.
    if GMXVERSION == 5:
        csplit = ('gmx ' + command.replace('gmx', '')).split()
    else:
        if command.split()[0] in gmxprogs:
            csplit = ('g_%s' % command).split()
        else:
            csplit = command.split()
    prog = os.path.join(gmxpath, csplit[0])
    csplit[0] = prog + gmxsuffix
    return _exec(' '.join(csplit), stdin=stdin, print_to_screen=print_to_screen, print_command=print_command, **kwargs)
Пример #3
0
def Calculate_AMBER(Structure, mdp_opts):
    pbc = mdp_opts["pbc"].lower() == "xyz"
    # Create AMBER inpcrd file
    inpcrd = amber.AmberAsciiRestart("inpcrd", mode="w")
    inpcrd.coordinates = np.array(Structure.positions.value_in_unit(
        u.angstrom)).reshape(-1, 3)
    inpcrd.box = Structure.box
    inpcrd.close()
    # sander insists on providing a trajectory to iterate over,
    # so we feed it the same coordinates again. But we don't use it
    # because the positions are imprecise.
    mdcrd = amber.AmberMdcrd("mdcrd",
                             natom=len(Structure.atoms),
                             hasbox=pbc,
                             mode="w")
    mdcrd.add_coordinates(
        np.array(Structure.positions.value_in_unit(u.angstrom)).reshape(-1, 3))
    if pbc:
        mdcrd.add_box(Structure.box[:3])
    mdcrd.close()
    # Create AMBER prmtop object from ParmEd Structure :)
    prmtop = amber.AmberParm.from_structure(Structure)
    prmtop.write_parm("prmtop")
    # Create AMBER mdin file and append some stuff
    mdin = Mdin()
    # Single point energies?
    mdin.change('cntrl', 'imin', '5')
    # Periodic boundary conditions?
    if pbc:
        mdin.change('cntrl', 'ntb', '1')
    else:
        mdin.change('cntrl', 'ntb', '0')
    # Cutoff zero is really infinite
    if float(mdp_opts['rlist']) == 0.0:
        mdin.change('cntrl', 'cut', '9999')
    else:
        mdin.change('cntrl', 'cut', str(int(float(mdp_opts['rlist']) * 10)))
    # Take zero MD steps
    mdin.change('cntrl', 'nstlim', '0')
    # Don't update nonbond parameters
    mdin.change('cntrl', 'nsnb', '0')
    # if mdp_opts['coulombtype'].lower() == 'pme':
    #     mdin.change('ewald','order',5)
    #     mdin.change('ewald','skinnb',0)
    mdin.write("mdin")
    # Nonbonded method
    if mdp_opts['coulombtype'].lower() == 'pme':
        with open("mdin", 'a') as f:
            print >> f, """&ewald
 order=5, skinnb=0
/"""
    with open("mdin", 'a') as f:
        print >> f, """&debugf
do_debugf=1, dumpfrc=1
/"""
    # Call sander for energy and force
    os.system('rm -f forcedump.dat')
    _exec("sander -O -y mdcrd", print_command=False)
    # Parse energy and force
    ParseMode = 0
    Energies = []
    Forces = []
    Force = []
    iatom = 0
    isAtom = [atom.atomic_number > 0 for atom in Structure.atoms]
    for line in open('forcedump.dat'):
        line = line.strip()
        sline = line.split()
        if ParseMode == 1:
            if len(sline) == 1 and isfloat(sline[0]):
                Energies.append(float(sline[0]) * 4.184)
                ParseMode = 0
        if ParseMode == 2:
            if len(sline) == 3 and all(isfloat(sline[i]) for i in range(3)):
                if isAtom[iatom]:
                    Force += [float(sline[i]) * 4.184 * 10 for i in range(3)]
                iatom += 1
            if len(Force) == 3 * sum(isAtom):
                Forces.append(np.array(Force))
                Force = []
                ParseMode = 0
                iatom = 0
        if line == '0 START of Energies':
            ParseMode = 1
        elif line == '1 Total Force' or line == '2 Total Force':
            ParseMode = 2
    # Obtain energy components
    ParseMode = 0
    Ecomps = OrderedDict()
    for line in open("mdout").readlines():
        if "NSTEP = " in line:
            ParseMode = 1
        if ParseMode == 1:
            if "=" not in line:
                ParseMode = 0
                continue
            else:
                ieq = None
                wkey = []
                # Assume the line is split-able
                for i, w in enumerate(line.split()):
                    if w == '=':
                        ieq = i
                    elif i - 1 == ieq:
                        Ecomps.setdefault(' '.join(wkey),
                                          []).append(float(w) * 4.184)
                        wkey = []
                    else:
                        wkey.append(w)
    Ecomps_Sav = OrderedDict()
    for key in Ecomps:
        if set(Ecomps[key]) == set([0.0]): continue
        elif key.lower() in ['eptot', 'etot', 'volume', 'density']: continue
        else:
            Ecomps_Sav[key] = Ecomps[key][0]
    Ecomps_Sav['EPTOT'] = Ecomps['EPtot'][0]
    # Save just the first frame from the .mdcrd
    Energies = Energies[0]
    Forces = Forces[0]
    return Energies, Forces, Ecomps_Sav
Пример #4
0
                gmx_pdb.atomname[anum] = amb_gmx_amap[k][aname]
        anameInResidue = []
        anumInResidue = []

# Write the Gromacs-compatible PDB file
gmx_pdbfnm = os.path.splitext(sys.argv[1])[0] + "-gmx.pdb"
gmx_pdb.write(gmx_pdbfnm)

gmx_ffnames = {
    'fb15': 'amberfb15',
    'fb15ni': 'amberfb15ni',
    'ildn': 'amber99sb-ildn'
}
amber_ffnames = {'fb15': 'fb15', 'fb15ni': 'fb15ni', 'ildn': 'ff99SBildn'}
# Set up the system in Gromacs
_exec("pdb2gmx -ff %s -f %s" % (gmx_ffnames[args.ff], gmx_pdbfnm), stdin="1\n")

# Set up the system in AMBER
amb_outpdbfnm = os.path.splitext(sys.argv[1])[0] + "-amb.pdb"

with open("stage.leap", 'w') as f:
    print >> f, """source leaprc.{choice}
pdb = loadpdb {pdbin}
savepdb pdb {pdbout}
saveamberparm pdb prmtop inpcrd
quit
""".format(choice=amber_ffnames[args.ff],
           pdbin=sys.argv[1],
           pdbout=amb_outpdbfnm)

_exec("tleap -f stage.leap")
Пример #5
0
                break
        if mapped:
            for anum, aname in zip(anumInResidue, anameInResidue):
                gmx_pdb.atomname[anum] = amb_gmx_amap[k][aname]
        anirs.append(anameInResidue)
        anameInResidue = []
        anumInResidue = []

# Write the Gromacs-compatible PDB file
gmx_pdbfnm = os.path.splitext(sys.argv[1])[0]+"-gmx.pdb"
gmx_pdb.write(gmx_pdbfnm)

gmx_ffnames = {'fb15':'amberfb15', 'fb15ni':'amberfb15ni', 'ildn':'amber99sb-ildn'}
amber_ffnames = {'fb15' : 'fb15', 'fb15ni':'fb15ni', 'ildn':'ff99SBildn'}
# Set up the system in Gromacs
_exec("pdb2gmx -ff %s -f %s" % (gmx_ffnames[args.ff], gmx_pdbfnm), stdin="1\n")

# Set up the system in AMBER
amb_outpdbfnm = os.path.splitext(sys.argv[1])[0]+"-amb.pdb"

with open("stage.leap", 'w') as f:
    print >> f, """source leaprc.{choice}
pdb = loadpdb {pdbin}
savepdb pdb {pdbout}
saveamberparm pdb prmtop inpcrd
quit
""".format(choice = amber_ffnames[args.ff], 
           pdbin = sys.argv[1], pdbout = amb_outpdbfnm)

_exec("tleap -f stage.leap")
Пример #6
0
                # raise RuntimeError
        if gmx_acharge != chrm_acharge:
            print "Atomic charges don't match for", resname, gmx_atom, chrm_atom
            # raise RuntimeError
        # Print the atoms that are renamed
        # if gmx_aname != chrm_aname:
        #     print "%s (AMBER) %s <-> %s (CHARMM)" % (resname, chrm_aname, gmx_aname)
        gmx_chrm_amap.setdefault(resname, OrderedDict())[gmx_aname] = chrm_aname
        chrm_gmx_amap.setdefault(resname, OrderedDict())[chrm_aname] = gmx_aname

chrm_atomnames = OrderedDict([(k, set(v.keys())) for k, v in chrm_gmx_amap.items()])
max_reslen = max([len(v) for v in chrm_atomnames.values()])

pdb_in = sys.argv[1]
# rewrite the gmx pdb using mdtraj
_exec('python ~/scripts/manip_proteins/mdt_rewrite_pdb.py --p0 %s --pf mdt_%s' % (pdb_in, pdb_in))

# run pdb thru/chrm charmming
_exec('python ~/local/charmming/parser_v3.py mdt_%s' % (pdb_in))

# Begin with an GMX-compatible PDB file
# Please ensure by hand :)
pdb = Molecule(pdb_in, build_topology=False)
gmx_pdb = copy.deepcopy(pdb)
del gmx_pdb.Data['elem']

# Convert to a GROMACS-compatible PDB file
# This mainly involves renaming atoms and residues,
# notably hydrogen names.

# List of atoms in the current residue
Пример #7
0
def Calculate_AMBER(Structure, mdp_opts):
    pbc = mdp_opts["pbc"].lower() == "xyz"
    # Create AMBER inpcrd file
    inpcrd = amber.AmberAsciiRestart("inpcrd", mode="w")
    inpcrd.coordinates = np.array(Structure.positions.value_in_unit(u.angstrom)).reshape(-1, 3)
    inpcrd.box = Structure.box
    inpcrd.close()
    # sander insists on providing a trajectory to iterate over,
    # so we feed it the same coordinates again. But we don't use it
    # because the positions are imprecise.
    mdcrd = amber.AmberMdcrd("mdcrd", natom=len(Structure.atoms), hasbox=pbc, mode="w")
    mdcrd.add_coordinates(np.array(Structure.positions.value_in_unit(u.angstrom)).reshape(-1, 3))
    if pbc:
        mdcrd.add_box(Structure.box[:3])
    mdcrd.close()
    # Create AMBER prmtop object from ParmEd Structure :)
    prmtop = amber.AmberParm.from_structure(Structure)
    prmtop.write_parm("prmtop")
    # Create AMBER mdin file and append some stuff
    mdin = Mdin()
    # Single point energies?
    mdin.change("cntrl", "imin", "5")
    # Periodic boundary conditions?
    if pbc:
        mdin.change("cntrl", "ntb", "1")
    else:
        mdin.change("cntrl", "ntb", "0")
    # Cutoff zero is really infinite
    if float(mdp_opts["rlist"]) == 0.0:
        mdin.change("cntrl", "cut", "9999")
    else:
        mdin.change("cntrl", "cut", str(int(float(mdp_opts["rlist"]) * 10)))
    # Take zero MD steps
    mdin.change("cntrl", "nstlim", "0")
    # Don't update nonbond parameters
    mdin.change("cntrl", "nsnb", "0")
    # if mdp_opts['coulombtype'].lower() == 'pme':
    #     mdin.change('ewald','order',5)
    #     mdin.change('ewald','skinnb',0)
    mdin.write("mdin")
    # Nonbonded method
    if mdp_opts["coulombtype"].lower() == "pme":
        with open("mdin", "a") as f:
            print >> f, """&ewald
 order=5, skinnb=0
/"""
    with open("mdin", "a") as f:
        print >> f, """&debugf
do_debugf=1, dumpfrc=1
/"""
    # Call sander for energy and force
    os.system("rm -f forcedump.dat")
    _exec("sander -O -y mdcrd", print_command=False)
    # Parse energy and force
    ParseMode = 0
    Energies = []
    Forces = []
    Force = []
    iatom = 0
    isAtom = [atom.atomic_number > 0 for atom in Structure.atoms]
    for line in open("forcedump.dat"):
        line = line.strip()
        sline = line.split()
        if ParseMode == 1:
            if len(sline) == 1 and isfloat(sline[0]):
                Energies.append(float(sline[0]) * 4.184)
                ParseMode = 0
        if ParseMode == 2:
            if len(sline) == 3 and all(isfloat(sline[i]) for i in range(3)):
                if isAtom[iatom]:
                    Force += [float(sline[i]) * 4.184 * 10 for i in range(3)]
                iatom += 1
            if len(Force) == 3 * sum(isAtom):
                Forces.append(np.array(Force))
                Force = []
                ParseMode = 0
                iatom = 0
        if line == "0 START of Energies":
            ParseMode = 1
        elif line == "1 Total Force" or line == "2 Total Force":
            ParseMode = 2
    # Obtain energy components
    ParseMode = 0
    Ecomps = OrderedDict()
    for line in open("mdout").readlines():
        if "NSTEP = " in line:
            ParseMode = 1
        if ParseMode == 1:
            if "=" not in line:
                ParseMode = 0
                continue
            else:
                ieq = None
                wkey = []
                # Assume the line is split-able
                for i, w in enumerate(line.split()):
                    if w == "=":
                        ieq = i
                    elif i - 1 == ieq:
                        Ecomps.setdefault(" ".join(wkey), []).append(float(w) * 4.184)
                        wkey = []
                    else:
                        wkey.append(w)
    Ecomps_Sav = OrderedDict()
    for key in Ecomps:
        if set(Ecomps[key]) == set([0.0]):
            continue
        elif key.lower() in ["eptot", "etot", "volume", "density"]:
            continue
        else:
            Ecomps_Sav[key] = Ecomps[key][0]
    Ecomps_Sav["EPTOT"] = Ecomps["EPtot"][0]
    # Save just the first frame from the .mdcrd
    Energies = Energies[0]
    Forces = Forces[0]
    return Energies, Forces, Ecomps_Sav