Exemple #1
0
def main():
    # Command line arguments
    gro_file = sys.argv[1]
    top_file = sys.argv[2]
    mdp_file = sys.argv[3]

    # Parse the .mdp file to inform ParmEd
    defines, sysargs = interpret_mdp(mdp_file)

    # Gromacs calculation
    GMX_Energy, GMX_Force, Ecomps_GMX = Calculate_GMX(gro_file, top_file, mdp_file)

    # Print Gromacs energy components
    printcool_dictionary(Ecomps_GMX, title="GROMACS energy components")

    # ParmEd-OpenMM calculation
    PED_Energy, PED_Force, Ecomps_PED = Calculate_ParmEd(gro_file, top_file, sysargs, defines)
    
    # Analyze force differences
    GMX_Force = GMX_Force.reshape(-1,3)
    D_Force = GMX_Force - PED_Force

    # Final printout
    print "Energy Difference (kJ/mol):"
    print (Ecomps_PED['Potential']-Ecomps_GMX['Potential'])[0]
    print "RMS / Max Force Difference (kJ/mol/nm):"
    print np.sqrt(np.mean([sum(i**2) for i in D_Force])), np.sqrt(np.max(np.array([sum(i**2) for i in D_Force])))
Exemple #2
0
def main():
    # Command line arguments
    gro_file = sys.argv[1]
    top_file = sys.argv[2]
    mdp_file = sys.argv[3]

    # Parse the .mdp file to inform ParmEd
    defines, sysargs, mdp_opts = interpret_mdp(mdp_file)

    # Gromacs calculation
    GMX_Energy, GMX_Force, Ecomps_GMX = Calculate_GMX(gro_file, top_file, mdp_file)
    GMX_Force = GMX_Force.reshape(-1, 3)

    # Print Gromacs energy components
    printcool_dictionary(Ecomps_GMX, title="GROMACS energy components")

    # ParmEd-OpenMM calculation
    Structure, OMM_Energy, OMM_Force, Ecomps_OMM = Calculate_ParmEd_OpenMM(gro_file, top_file, sysargs, defines)

    if args.amber:
        # AMBER calculation (optional)
        AMBER_Energy, AMBER_Force, Ecomps_AMBER = Calculate_AMBER(Structure, mdp_opts)
        AMBER_Force = AMBER_Force.reshape(-1, 3)
        # Print AMBER energy components
        printcool_dictionary(Ecomps_AMBER, title="AMBER energy components")

    # Construct arrays of energy and force differences
    if args.amber:
        Names = ["Gromacs", "OpenMM", "AMBER"]
        Energies = np.array([GMX_Energy, OMM_Energy.value_in_unit(u.kilojoule_per_mole), AMBER_Energy])
        Forces = np.array([GMX_Force, OMM_Force, AMBER_Force])
    else:
        Names = ["Gromacs", "OpenMM"]
        Energies = np.array([GMX_Energy, OMM_Energy.value_in_unit(u.kilojoule_per_mole)])
        Forces = np.array([GMX_Force, OMM_Force])
    D_Energy = []
    D_FrcRMS = []
    D_FrcMax = []
    D_Names = []
    for i in range(1, len(Names)):
        for j in range(i):
            D_Names.append("%s-%s" % (Names[j], Names[i]))
            D_Energy.append(Energies[j] - Energies[i])
            D_Force = Forces[j] - Forces[i]
            D_FrcRMS.append(np.sqrt(np.mean([sum(k ** 2) for k in D_Force])))
            D_FrcMax.append(np.sqrt(np.max(np.array([sum(k ** 2) for k in D_Force]))))

    # Print the net force on the first three atoms (e.g. water molecule)
    # print np.sum(GMX_Force[:3], axis=0)
    # print np.sum(AMBER_Force[:3], axis=0)
    # Final printout
    print "Energy Difference (kJ/mol):"
    for i in range(len(D_Names)):
        print "%-14s % .6e" % (D_Names[i], D_Energy[i])

    print "RMS / Max Force Difference (kJ/mol/nm):"
    for i in range(len(D_Names)):
        print "%-14s % .6e % .6e" % (D_Names[i], D_FrcRMS[i], D_FrcMax[i])
Exemple #3
0
def main():
    # Command line arguments
    gro_file = sys.argv[1]
    top_file = sys.argv[2]
    mdp_file = sys.argv[3]

    # Parse the .mdp file to inform ParmEd
    defines, sysargs, mdp_opts = interpret_mdp(mdp_file)

    # Gromacs calculation
    GMX_Energy, GMX_Force, Ecomps_GMX = Calculate_GMX(gro_file, top_file, mdp_file)
    GMX_Force = GMX_Force.reshape(-1,3)

    # Print Gromacs energy components
    printcool_dictionary(Ecomps_GMX, title="GROMACS energy components")

    # ParmEd-OpenMM calculation
    Structure, OMM_Energy, OMM_Force, Ecomps_OMM = Calculate_ParmEd_OpenMM(gro_file, top_file, sysargs, defines)
    
    if args.amber:
        # AMBER calculation (optional)
        AMBER_Energy, AMBER_Force, Ecomps_AMBER = Calculate_AMBER(Structure, mdp_opts)
        AMBER_Force = AMBER_Force.reshape(-1,3)
        # Print AMBER energy components
        printcool_dictionary(Ecomps_AMBER, title="AMBER energy components")

    # Construct arrays of energy and force differences
    if args.amber:
        Names = ['Gromacs', 'OpenMM', 'AMBER']
        Energies = np.array([GMX_Energy, OMM_Energy.value_in_unit(u.kilojoule_per_mole), AMBER_Energy])
        Forces = np.array([GMX_Force, OMM_Force, AMBER_Force])
    else:
        Names = ['Gromacs', 'OpenMM']
        Energies = np.array([GMX_Energy, OMM_Energy.value_in_unit(u.kilojoule_per_mole)])
        Forces = np.array([GMX_Force, OMM_Force])
    D_Energy = []
    D_FrcRMS = []
    D_FrcMax = []
    D_Names = []
    for i in range(1, len(Names)):
        for j in range(i):
            D_Names.append('%s-%s' % (Names[j],Names[i]))
            D_Energy.append(Energies[j]-Energies[i])
            D_Force = Forces[j]-Forces[i]
            D_FrcRMS.append(np.sqrt(np.mean([sum(k**2) for k in D_Force])))
            D_FrcMax.append(np.sqrt(np.max(np.array([sum(k**2) for k in D_Force]))))

    # Print the net force on the first three atoms (e.g. water molecule)
    # print np.sum(GMX_Force[:3], axis=0)
    # print np.sum(AMBER_Force[:3], axis=0)
    # Final printout
    print "Energy Difference (kJ/mol):"
    for i in range(len(D_Names)):
        print "%-14s % .6e" % (D_Names[i], D_Energy[i])

    print "RMS / Max Force Difference (kJ/mol/nm):"
    for i in range(len(D_Names)):
        print "%-14s % .6e % .6e" % (D_Names[i], D_FrcRMS[i], D_FrcMax[i])
Exemple #4
0
def Calculate_ParmEd_OpenMM(gro_file, top_file, sysargs, defines):
    #===============================#
    #|   ParmEd object creation    |#
    #===============================#
    # Make sure the proper defines from the .mdp file are passed into the GromacsTopologyFile() :)
    ParmEd_GmxTop = gromacs.GromacsTopologyFile(top_file, defines=defines)
    ParmEd_GmxGro = gromacs.GromacsGroFile.parse(gro_file)
    ParmEd_GmxTop.box = ParmEd_GmxGro.box
    ParmEd_GmxTop.positions = ParmEd_GmxGro.positions
    #===============================#
    #|   OpenMM simulation setup   |#
    #===============================#
    # ParmEd creates System object
    system = ParmEd_GmxTop.createSystem(**sysargs)
    # Keep a record of which atoms are real (not virtual sites)
    isAtom = []
    for i in range(system.getNumParticles()):
        isAtom.append(system.getParticleMass(i).value_in_unit(u.dalton) > 0.0)
    # Setting force groups enables energy components analysis
    for i, f in enumerate(system.getForces()):
        f.setForceGroup(i)
        if isinstance(f, mm.NonbondedForce):
            f.setUseDispersionCorrection(True)
        elif isinstance(f, mm.CustomNonbondedForce):
            f.setUseLongRangeCorrection(True)
    integ = mm.VerletIntegrator(1.0 * u.femtosecond)
    plat = mm.Platform.getPlatformByName('Reference')
    # Create Simulation object
    simul = app.Simulation(ParmEd_GmxTop.topology, system, integ, plat)
    simul.context.setPositions(ParmEd_GmxGro.positions)
    simul.context.applyConstraints(1e-12)
    # Obtain OpenMM potential energy
    state = simul.context.getState(getPositions=True,
                                   getEnergy=True,
                                   getForces=True)
    parmed_energy = state.getPotentialEnergy()
    parmed_forces = state.getForces()
    pos = np.array(state.getPositions().value_in_unit(u.angstrom)).reshape(
        -1, 3)
    # Obtain and save constrained positions
    # M = Molecule(gro_file)
    # M.xyzs[0] = pos
    # M.write('constrained.gro')
    # Print OpenMM-via-ParmEd energy components
    Ecomps_OMM = energy_components(simul)
    printcool_dictionary(Ecomps_OMM,
                         title="OpenMM energy components via ParmEd")
    parmed_forces = np.array([
        f for i, f in enumerate(
            parmed_forces.value_in_unit(u.kilojoule_per_mole / u.nanometer))
        if isAtom[i]
    ])
    return ParmEd_GmxTop, parmed_energy, parmed_forces, Ecomps_OMM
def main():
    """Input file parser for ForceBalance program.  We will simply read the options and print them back out.
    
    """
    print "\x1b[1;98mCalling Input File Parser as a standalone script\x1b[0m\n"
    if len(sys.argv) != 2:
        print "Please call this script with one argument - that is the input file"
        sys.exit(1)
    else:
        options, tgt_opts = parse_inputs(sys.argv[1])
        printcool_dictionary(options, "General options")
        for this_tgt_opt in tgt_opts:
            printcool_dictionary(this_tgt_opt, "Target options for %s" % this_tgt_opt["name"])
def main():
    """Input file parser for ForceBalance program.  We will simply read the options and print them back out.
    
    """
    print "\x1b[1;98mCalling Input File Parser as a standalone script\x1b[0m\n"
    if len(sys.argv) != 2:
        print "Please call this script with one argument - that is the input file"
        sys.exit(1)
    else:
        options, tgt_opts = parse_inputs(sys.argv[1])
        printcool_dictionary(options,"General options")
        for this_tgt_opt in tgt_opts:
            printcool_dictionary(this_tgt_opt,"Target options for %s" % this_tgt_opt['name'])
Exemple #7
0
def Calculate_ParmEd_OpenMM(gro_file, top_file, sysargs, defines):
    # ===============================#
    # |   ParmEd object creation    |#
    # ===============================#
    # Make sure the proper defines from the .mdp file are passed into the GromacsTopologyFile() :)
    ParmEd_GmxTop = gromacs.GromacsTopologyFile(top_file, defines=defines)
    ParmEd_GmxGro = gromacs.GromacsGroFile.parse(gro_file)
    ParmEd_GmxTop.box = ParmEd_GmxGro.box
    ParmEd_GmxTop.positions = ParmEd_GmxGro.positions
    # ===============================#
    # |   OpenMM simulation setup   |#
    # ===============================#
    # ParmEd creates System object
    system = ParmEd_GmxTop.createSystem(**sysargs)
    # Keep a record of which atoms are real (not virtual sites)
    isAtom = []
    for i in range(system.getNumParticles()):
        isAtom.append(system.getParticleMass(i).value_in_unit(u.dalton) > 0.0)
    # Setting force groups enables energy components analysis
    for i, f in enumerate(system.getForces()):
        f.setForceGroup(i)
        if isinstance(f, mm.NonbondedForce):
            f.setUseDispersionCorrection(True)
        elif isinstance(f, mm.CustomNonbondedForce):
            f.setUseLongRangeCorrection(True)
    integ = mm.VerletIntegrator(1.0 * u.femtosecond)
    plat = mm.Platform.getPlatformByName("Reference")
    # Create Simulation object
    simul = app.Simulation(ParmEd_GmxTop.topology, system, integ, plat)
    simul.context.setPositions(ParmEd_GmxGro.positions)
    simul.context.applyConstraints(1e-12)
    # Obtain OpenMM potential energy
    state = simul.context.getState(getPositions=True, getEnergy=True, getForces=True)
    parmed_energy = state.getPotentialEnergy()
    parmed_forces = state.getForces()
    pos = np.array(state.getPositions().value_in_unit(u.angstrom)).reshape(-1, 3)
    # Obtain and save constrained positions
    # M = Molecule(gro_file)
    # M.xyzs[0] = pos
    # M.write('constrained.gro')
    # Print OpenMM-via-ParmEd energy components
    Ecomps_OMM = energy_components(simul)
    printcool_dictionary(Ecomps_OMM, title="OpenMM energy components via ParmEd")
    parmed_forces = np.array(
        [f for i, f in enumerate(parmed_forces.value_in_unit(u.kilojoule_per_mole / u.nanometer)) if isAtom[i]]
    )
    return ParmEd_GmxTop, parmed_energy, parmed_forces, Ecomps_OMM
def Calculate_ParmEd_Amber(crd_file, prmtop_file, sysargs):
    #===============================#
    #|   ParmEd object creation    |#
    #===============================#
    ParmEd_ambertop = amber.AmberParm( prmtop_file, crd_file)    

    system = ParmEd_ambertop.createSystem(**sysargs)

    #===============================#
    #|   OpenMM simulation setup   |#
    #===============================#
    # Keep a record of which atoms are real (not virtual sites)
    isAtom = []
    for i in range(system.getNumParticles()):
        isAtom.append(system.getParticleMass(i).value_in_unit(u.dalton) > 0.0)
    # Setting force groups enables energy components analysis
    for i, f in enumerate(system.getForces()):
        f.setForceGroup(i)
        if isinstance(f, mm.NonbondedForce):
            f.setUseDispersionCorrection(True)
    integ = mm.VerletIntegrator(1.0*u.femtosecond)
    plat = mm.Platform.getPlatformByName('Reference')
    # Create Simulation object
    simul = app.Simulation(ParmEd_ambertop.topology, system, integ, plat)
    simul.context.setPositions(ParmEd_ambertop.positions)
    simul.context.applyConstraints(1e-12)
    # Obtain OpenMM potential energy
    state = simul.context.getState(getPositions=True,getEnergy=True,getForces=True)
    parmed_energy = state.getPotentialEnergy()
    parmed_forces = state.getForces()
    pos = np.array(state.getPositions().value_in_unit(u.angstrom)).reshape(-1,3)
    # Obtain and save constrained positions
    # M = Molecule(gro_file)
    # M.xyzs[0] = pos
    # M.write('constrained.gro')
    # Print OpenMM-via-ParmEd energy components
    Ecomps_OMM = energy_components(simul)
    printcool_dictionary(Ecomps_OMM, title="AMBER topology, AMBER positions")
    parmed_forces = np.array([f for i, f in enumerate(parmed_forces.value_in_unit(u.kilojoule_per_mole/u.nanometer)) if isAtom[i]])
    return parmed_energy, parmed_forces, Ecomps_OMM
Exemple #9
0
def Calculate_CHARMM(params, psf, crd, sysargs, defines):
    # Compute the box dimensions from the coordinates and set the box lengths (only
    # orthorhombic boxes are currently supported in OpenMM)
    coords = crd.positions

    # Create the OpenMM system
    system = psf.createSystem(params, **sysargs)

    # Keep a record of which atoms are real (not virtual sites)
    isAtom = []
    for i in range(system.getNumParticles()):
        isAtom.append(system.getParticleMass(i).value_in_unit(u.dalton) > 0.0)
    # Setting force groups enables energy components analysis
    for i, f in enumerate(system.getForces()):
        f.setForceGroup(i)
        if isinstance(f, mm.NonbondedForce):
            f.setUseDispersionCorrection(True)
        elif isinstance(f, mm.CustomNonbondedForce):
            f.setUseLongRangeCorrection(True)

    integ = mm.VerletIntegrator(1.0 * u.femtosecond)
    plat = mm.Platform.getPlatformByName("Reference")
    # Create Simulation object
    simul = app.Simulation(psf.topology, system, integ, plat)
    simul.context.setPositions(coords)
    simul.context.applyConstraints(1e-12)

    # Obtain OpenMM potential energy
    state = simul.context.getState(getPositions=True, getEnergy=True, getForces=True)
    parmed_energy = state.getPotentialEnergy()
    parmed_forces = state.getForces()
    pos = np.array(state.getPositions().value_in_unit(u.angstrom)).reshape(-1, 3)
    Ecomps_OMM = energy_components(simul)
    printcool_dictionary(Ecomps_OMM, title="CHARMM energy components via ParmEd OpenMM")
    parmed_forces = np.array(
        [f for i, f in enumerate(parmed_forces.value_in_unit(u.kilojoule_per_mole / u.nanometer)) if isAtom[i]]
    )

    return ParmEd_GmxTop, parmed_energy, parmed_forces, Ecomps_OMM
Exemple #10
0
def edit_mdp(fin=None, fout=None, options={}, defaults={}, verbose=False):
    """
    Read, create or edit a Gromacs MDP file.  The MDP file contains GROMACS run parameters.
    If the input file exists, it is parsed and options are replaced where "options" overrides them.
    If the "options" dictionary contains more options, they are added at the end.
    If the "defaults" dictionary contains more options, they are added at the end.
    Keys are standardized to lower-case strings where all dashes are replaced by underscores.
    The output file contains the same comments and "dressing" as the input.
    Also returns a dictionary with the final key/value pairs.

    Parameters
    ----------
    fin : str, optional
        Input .mdp file name containing options that are more important than "defaults", but less important than "options"
    fout : str, optional
        Output .mdp file name.
    options : dict, optional
        Dictionary containing mdp options. Existing options are replaced, new options are added at the end, None values are deleted from output mdp.
    defaults : dict, optional
        defaults Dictionary containing "default" mdp options, added only if they don't already exist.
    verbose : bool, optional
        Print out additional information        

    Returns
    -------
    OrderedDict
        Key-value pairs combined from the input .mdp and the supplied options/defaults and equivalent to what's printed in the output mdp.
    """
    clashes = ["pbc"]
    # Make sure that the keys are lowercase, and the values are all strings.
    options = OrderedDict([(key.lower().replace('-', '_'),
                            str(val) if val is not None else None)
                           for key, val in options.items()])
    # List of lines in the output file.
    out = []
    # List of options in the output file.
    haveopts = []
    # List of all options in dictionary form, to be returned.
    all_options = OrderedDict()
    if fin is not None and os.path.isfile(fin):
        for line in open(fin).readlines():
            line = line.strip().expandtabs()
            # The line structure should look something like this:
            # key   = value  ; comments
            # First split off the comments.
            if len(line) == 0:
                out.append('')
                continue
            s = line.split(';', 1)
            data = s[0]
            comms = s[1] if len(s) > 1 else None
            # Pure comment lines or empty lines get appended to the output.
            if set(data).issubset([' ']):
                out.append(line)
                continue
            # Now split off the key and value fields at the equals sign.
            keyf, valf = data.split('=', 1)
            key = keyf.strip().lower().replace('-', '_')
            haveopts.append(key)
            if key in options:
                val = options[key]
                val0 = valf.strip()
                if key in clashes and val != val0:
                    logger.error(
                        "edit_mdp tried to set %s = %s but its original value was %s = %s\n"
                        % (key, val, key, val0))
                    raise RuntimeError
                # Passing None as the value causes the option to be deleted
                if val is None: continue
                if len(val) < len(valf):
                    valf = ' ' + val + ' ' * (len(valf) - len(val) - 1)
                else:
                    valf = ' ' + val + ' '
                lout = [keyf, '=', valf]
                if comms is not None:
                    lout += [';', comms]
                out.append(''.join(lout))
            else:
                out.append(line)
                val = valf.strip()
            all_options[key] = val
    for key, val in options.items():
        key = key.lower().replace('-', '_')
        if key not in haveopts:
            haveopts.append(key)
            out.append("%-20s = %s" % (key, val))
            all_options[key] = val
    # Fill in some default options.
    for key, val in defaults.items():
        key = key.lower().replace('-', '_')
        options[key] = val
        if key not in haveopts:
            out.append("%-20s = %s" % (key, val))
            all_options[key] = val
    if fout != None:
        file_out = wopen(fout)
        for line in out:
            print >> file_out, line
        file_out.close()
    if verbose:
        printcool_dictionary(options,
                             title="%s -> %s with options:" % (fin, fout))
    return all_options
Exemple #11
0
simul = app.Simulation(OMM_prmtop.topology, system, integ)
simul.context.setPositions(OMM_eqgro.positions)
simul.context.applyConstraints(1e-12)
state = simul.context.getState(getPositions=True)
pos = np.array(state.getPositions().value_in_unit(u.angstrom)).reshape(-1, 3)
M = Molecule('eq.gro')
M.xyzs[0] = pos
M.write('constrained.gro')

# Gromacs calculation
GMX_Energy, GMX_Force, Ecomps_GMX = Calculate_GMX('constrained.gro',
                                                  'topol.top', 'shot.mdp')
GMX_Force = GMX_Force.reshape(-1, 3)

# Print Gromacs energy components
printcool_dictionary(Ecomps_GMX, title="GROMACS energy components")

# Parse the .mdp file to inform ParmEd
defines, sysargs, mdp_opts = interpret_mdp('shot.mdp')

parm = parmed.amber.AmberParm('prmtop', 'inpcrd')
GmxGro = parmed.gromacs.GromacsGroFile.parse('constrained.gro')
parm.box = GmxGro.box
parm.positions = GmxGro.positions

inpcrd_out = parmed.amber.AmberAsciiRestart("inpcrd_out", mode="w")
inpcrd_out.coordinates = np.array(GmxGro.positions.value_in_unit(
    u.angstrom)).reshape(-1, 3)
inpcrd_out.box = GmxGro.box
inpcrd_out.close()
plat = mm.Platform.getPlatformByName('Reference')
simul = app.Simulation(OMM_prmtop.topology, system, integ)
simul.context.setPositions(OMM_eqgro.positions)
simul.context.applyConstraints(1e-12)
state = simul.context.getState(getPositions=True)
pos = np.array(state.getPositions().value_in_unit(u.angstrom)).reshape(-1,3)
M = Molecule('eq.gro')
M.xyzs[0] = pos
M.write('constrained.gro')

# Gromacs calculation
GMX_Energy, GMX_Force, Ecomps_GMX = Calculate_GMX('constrained.gro', 'topol.top', 'shot.mdp')
GMX_Force = GMX_Force.reshape(-1,3)

# Print Gromacs energy components
printcool_dictionary(Ecomps_GMX, title="GROMACS energy components")

# Parse the .mdp file to inform ParmEd
defines, sysargs, mdp_opts = interpret_mdp('shot.mdp')

parm = parmed.amber.AmberParm('prmtop', 'inpcrd')
GmxGro = parmed.gromacs.GromacsGroFile.parse('constrained.gro')
parm.box = GmxGro.box
parm.positions = GmxGro.positions

# AMBER calculation (optional)
AMBER_Energy, AMBER_Force, Ecomps_AMBER = Calculate_AMBER(parm, mdp_opts)
AMBER_Force = AMBER_Force.reshape(-1,3)
# Print AMBER energy components
printcool_dictionary(Ecomps_AMBER, title="AMBER energy components")
plat = mm.Platform.getPlatformByName('Reference')
simul = app.Simulation(OMM_prmtop.topology, system, integ)
simul.context.setPositions(OMM_eqgro.positions)
simul.context.applyConstraints(1e-12)
state = simul.context.getState(getPositions=True)
pos = np.array(state.getPositions().value_in_unit(u.angstrom)).reshape(-1,3)
M = Molecule('eq.gro')
M.xyzs[0] = pos
M.write('constrained.gro')

# Gromacs calculation
GMX_Energy, GMX_Force, Ecomps_GMX = Calculate_GMX('constrained.gro', 'topol.top', 'shot.mdp')
GMX_Force = GMX_Force.reshape(-1,3)

# Print Gromacs energy components
printcool_dictionary(Ecomps_GMX, title="GROMACS energy components")

# Parse the .mdp file to inform ParmEd
defines, sysargs, mdp_opts = interpret_mdp('shot.mdp')

GmxGro = parmed.gromacs.GromacsGroFile.parse('constrained.gro')
# CHARMM calculation
parm = CharmmParameterSet('fb15.prm', 'fb15.rtf')
psf = CharmmPsfFile('sys-full.psf')
crd = CharmmCrdFile('sys-full.crd')
parm.box = GmxGro.box
parm.positions = GmxGro.positions

IPython.embed()
CHARMM_Energy, CHARMM_Force, Ecomps_CHARMM = Calculate_CHARMM(parm, psf, crd, sysargs, defines)
CHARMM_Force = CHARMM_Force.reshape(-1,3)
Exemple #14
0
def edit_mdp(fin=None, fout=None, options={}, defaults={}, verbose=False):
    """
    Read, create or edit a Gromacs MDP file.  The MDP file contains GROMACS run parameters.
    If the input file exists, it is parsed and options are replaced where "options" overrides them.
    If the "options" dictionary contains more options, they are added at the end.
    If the "defaults" dictionary contains more options, they are added at the end.
    Keys are standardized to lower-case strings where all dashes are replaced by underscores.
    The output file contains the same comments and "dressing" as the input.
    Also returns a dictionary with the final key/value pairs.

    Parameters
    ----------
    fin : str, optional
        Input .mdp file name containing options that are more important than "defaults", but less important than "options"
    fout : str, optional
        Output .mdp file name.
    options : dict, optional
        Dictionary containing mdp options. Existing options are replaced, new options are added at the end, None values are deleted from output mdp.
    defaults : dict, optional
        defaults Dictionary containing "default" mdp options, added only if they don't already exist.
    verbose : bool, optional
        Print out additional information        

    Returns
    -------
    OrderedDict
        Key-value pairs combined from the input .mdp and the supplied options/defaults and equivalent to what's printed in the output mdp.
    """
    clashes = ["pbc"]
    # Make sure that the keys are lowercase, and the values are all strings.
    options = OrderedDict(
        [(key.lower().replace("-", "_"), str(val) if val is not None else None) for key, val in options.items()]
    )
    # List of lines in the output file.
    out = []
    # List of options in the output file.
    haveopts = []
    # List of all options in dictionary form, to be returned.
    all_options = OrderedDict()
    if fin is not None and os.path.isfile(fin):
        for line in open(fin).readlines():
            line = line.strip().expandtabs()
            # The line structure should look something like this:
            # key   = value  ; comments
            # First split off the comments.
            if len(line) == 0:
                out.append("")
                continue
            s = line.split(";", 1)
            data = s[0]
            comms = s[1] if len(s) > 1 else None
            # Pure comment lines or empty lines get appended to the output.
            if set(data).issubset([" "]):
                out.append(line)
                continue
            # Now split off the key and value fields at the equals sign.
            keyf, valf = data.split("=", 1)
            key = keyf.strip().lower().replace("-", "_")
            haveopts.append(key)
            if key in options:
                val = options[key]
                val0 = valf.strip()
                if key in clashes and val != val0:
                    logger.error(
                        "edit_mdp tried to set %s = %s but its original value was %s = %s\n" % (key, val, key, val0)
                    )
                    raise RuntimeError
                # Passing None as the value causes the option to be deleted
                if val is None:
                    continue
                if len(val) < len(valf):
                    valf = " " + val + " " * (len(valf) - len(val) - 1)
                else:
                    valf = " " + val + " "
                lout = [keyf, "=", valf]
                if comms is not None:
                    lout += [";", comms]
                out.append("".join(lout))
            else:
                out.append(line)
                val = valf.strip()
            all_options[key] = val
    for key, val in options.items():
        key = key.lower().replace("-", "_")
        if key not in haveopts:
            haveopts.append(key)
            out.append("%-20s = %s" % (key, val))
            all_options[key] = val
    # Fill in some default options.
    for key, val in defaults.items():
        key = key.lower().replace("-", "_")
        options[key] = val
        if key not in haveopts:
            out.append("%-20s = %s" % (key, val))
            all_options[key] = val
    if fout != None:
        file_out = wopen(fout)
        for line in out:
            print >> file_out, line
        file_out.close()
    if verbose:
        printcool_dictionary(options, title="%s -> %s with options:" % (fin, fout))
    return all_options
Exemple #15
0
    def __init__(self,options,Objective,FF):
        """ Create an Optimizer object.
        
        The optimizer depends on both the FF and the fitting targets so there
        is a chain of dependencies: FF --> FitSim --> Optimizer, and FF --> Optimizer
        
        Here's what we do:
        - Take options from the parser
        - Pass in the objective function, force field, all fitting targets

        """
        super(Optimizer, self).__init__(options)

        ## A list of all the things we can ask the optimizer to do.
        self.OptTab    = {'NEWTONRAPHSON'     : self.NewtonRaphson, 
                          'NEWTON'            : self.NewtonRaphson, 
                          'NR'                : self.NewtonRaphson, 
                          'BFGS'              : self.BFGS,
                          'POWELL'            : self.Powell,
                          'SIMPLEX'           : self.Simplex,
                          'ANNEAL'            : self.Anneal,
                          'GENETIC'           : self.GeneticAlgorithm,
                          'CONJUGATEGRADIENT' : self.ConjugateGradient,
                          'SCAN_MVALS'        : self.ScanMVals,
                          'SCAN_PVALS'        : self.ScanPVals,
                          'SINGLE'            : self.SinglePoint,
                          'GRADIENT'          : self.Gradient,
                          'HESSIAN'           : self.Hessian,
                          'FDCHECKG'          : self.FDCheckG,
                          'FDCHECKH'          : self.FDCheckH
                          }
        
        #======================================#
        # Options that are given by the parser #
        #======================================#
        ## The root directory
        self.set_option(options,'root','root')
        ## The job type
        self.set_option(options,'jobtype','jobtype')
        ## Initial step size trust radius
        self.set_option(options,'trust0','trust0')
        ## Minimum trust radius (for noisy objective functions)
        self.set_option(options,'mintrust','mintrust')
        ## Lower bound on Hessian eigenvalue (below this, we add in steepest descent)
        self.set_option(options,'eig_lowerbound','eps')
        ## Guess value for Brent
        self.set_option(options,'lm_guess','lmg')
        ## Step size for numerical finite difference
        self.set_option(options,'finite_difference_h','h')
        ## Number of steps to average over
        self.set_option(options,'objective_history','hist')
        ## Function value convergence threshold
        self.set_option(options,'convergence_objective','conv_obj')
        ## Step size convergence threshold
        self.set_option(options,'convergence_step','conv_stp')
        ## Gradient convergence threshold
        self.set_option(options,'convergence_gradient','conv_grd')
        ## Maximum number of optimization steps
        self.set_option(options,'maxstep','maxstep')
        ## For scan[mp]vals: The parameter index to scan over
        self.set_option(options,'scanindex_num','idxnum')
        ## For scan[mp]vals: The parameter name to scan over, it just looks up an index
        self.set_option(options,'scanindex_name','idxname')
        ## For scan[mp]vals: The values that are fed into the scanner
        self.set_option(options,'scan_vals','scan_vals')
        ## Name of the checkpoint file that we're reading in
        self.set_option(options,'readchk','rchk_fnm')
        ## Name of the checkpoint file that we're writing out
        self.set_option(options,'writechk','wchk_fnm')
        ## Whether to write the checkpoint file at every step
        self.set_option(options,'writechk_step','wchk_step')
        ## Adaptive trust radius adjustment factor
        self.set_option(options,'adaptive_factor','adapt_fac')
        ## Adaptive trust radius adjustment damping
        self.set_option(options,'adaptive_damping','adapt_damp')
        ## Whether to print gradient during each step of the optimization
        self.set_option(options,'print_gradient','print_grad')
        ## Whether to print Hessian during each step of the optimization
        self.set_option(options,'print_hessian','print_hess')
        ## Whether to print parameters during each step of the optimization
        self.set_option(options,'print_parameters','print_vals')
        ## Error tolerance (if objective function rises by less than this, then the optimizer will forge ahead!)
        self.set_option(options,'error_tolerance','err_tol')
        ## Search tolerance (The nonlinear search will stop if the change is below this threshold)
        self.set_option(options,'search_tolerance','search_tol')
        self.set_option(options,'read_mvals')
        self.set_option(options,'read_pvals')
        
        #======================================#
        #     Variables which are set here     #
        #======================================#
        ## The objective function (needs to pass in when I instantiate)
        self.Objective = Objective
        ## Whether the penalty function is hyperbolic
        self.bhyp      = Objective.Penalty.ptyp != 2
        ## The force field itself
        self.FF        = FF
        
        #======================================#
        #    Variables from the force field    #
        #======================================#
        ## The indices to be excluded from the Hessian update
        self.excision  = list(FF.excision)

        ## Number of parameters
        self.np        = FF.np
        ## The original parameter values
        if options['read_mvals'] != None:
            self.mvals0    = np.array(options['read_mvals'])
        elif options['read_pvals'] != None:
            self.mvals0    = FF.create_mvals(options['read_pvals'])
        else:
            self.mvals0    = np.zeros(self.FF.np)

        ## Print the optimizer options.
        printcool_dictionary(self.PrintOptionDict, title="Setup for optimizer")
        ## Load the checkpoint file.
        self.readchk()