예제 #1
0
def test_gromacs_merge():
    etoh_filename = utils.get_data_filename("chemicals/etoh/etoh.mol2")
    benzene_filename = utils.get_data_filename("chemicals/benzene/benzene.mol2")

    with utils.enter_temp_directory(): #Prevents creating lots of tleap/antechamber files everywhere
        #Generate frcmod files, mol2 files
        gaff_mol2_filename1, frcmod_filename1 = amber.run_antechamber( "etoh", etoh_filename, charge_method = None)
        gaff_mol2_filename2, frcmod_filename2 = amber.run_antechamber( "benzene", benzene_filename, charge_method = None)

        #Set file names
        prmtop_filename1 = "./out1.prmtop"
        prmtop_filename2 = "./out2.prmtop"
        crd_filename1 = "./out1.inpcrd"
        crd_filename2 = "./out2.inpcrd"
        top_filename1 = "./out1.top"
        top_filename2 = "./out2.top"
        gro_filename1 = "./out1.gro"
        gro_filename2 = "./out2.gro"

        #Generate AMBER files
        amber.run_tleap( 'etoh', gaff_mol2_filename1, frcmod_filename1, prmtop_filename1, crd_filename1 )
        amber.run_tleap( 'benzene', gaff_mol2_filename2, frcmod_filename2, prmtop_filename2, crd_filename2 )

        #Convert to GROMACS
        utils.amber_to_gromacs( "etoh", prmtop_filename1, crd_filename1, out_top = top_filename1, out_gro = gro_filename1 )
        utils.amber_to_gromacs( "benzene", prmtop_filename2, crd_filename2, out_top = top_filename2, out_gro = gro_filename2 )

        #Merge topologies
        gromacs.merge_topologies( [ top_filename1, top_filename2], './combined.top', 'combined', molecule_numbers = [1, 5], molecule_names = ['etoh', 'benzene'] )

        #Test editing of molecule numbers in topology file
        gromacs.change_molecules_section( './combined.top', './edited.top', ['etoh', 'benzene'], [10, 20] )
def imatinib_timing():
    print("Loading imatinib...")
    # Load the PDB file.
    from simtk.openmm.app import PDBFile
    pdb_filename = utils.get_data_filename("chemicals/imatinib/imatinib.pdb")
    pdb = PDBFile(pdb_filename)
    # Create a ForceField object.
    gaff_xml_filename = utils.get_data_filename("parameters/gaff.xml")
    forcefield = ForceField(gaff_xml_filename)
    # Add the residue template generator.
    from openmoltools.forcefield_generators import gaffTemplateGenerator
    forcefield.registerTemplateGenerator(gaffTemplateGenerator)
    # Parameterize system.
    system = forcefield.createSystem(pdb.topology, nonbondedMethod=NoCutoff)
    integrator = openmm.LangevinIntegrator(300 * unit.kelvin,
                                           5.0 / unit.picoseconds,
                                           1.0 * unit.femtoseconds)
    # Create Context
    context = openmm.Context(system, integrator)
    context.setPositions(pdb.positions)
    integrator.step(100)

    import time
    nsteps = 10000000
    initial_time = time.time()
    integrator.step(nsteps)
    state = context.getState().getPeriodicBoxVectors()  # force dynamics
    final_time = time.time()
    elapsed_time = final_time / initial_time
    time_per_step = elapsed_time / float(nsteps)
    print('time per force evaluation is %.3f us' % (time_per_step * 1e6))
예제 #3
0
def test_amber_binary_mixture():
    sustiva_filename = utils.get_data_filename("chemicals/etoh/etoh.mol2")
    etoh_filename = utils.get_data_filename("chemicals/etoh/etoh_renamed.mol2")

    trj0, trj1 = md.load(sustiva_filename), md.load(etoh_filename)

    # Hack to assign unique residue names that are consistent with contents of mol2 files
    trj0.top.residue(0).name = "LIG"
    trj1.top.residue(0).name = "LI2"

    trj_list = [trj0, trj1]

    with utils.enter_temp_directory(
    ):  # Prevents creating tons of GAFF files everywhere.

        box_filename = "./box.pdb"
        box_trj = packmol.pack_box(trj_list, [25, 50])
        box_trj.save(box_filename)

        gaff_mol2_filename0, frcmod_filename0 = amber.run_antechamber(
            "sustiva", sustiva_filename, charge_method=None)
        gaff_mol2_filename1, frcmod_filename1 = amber.run_antechamber(
            "etoh", etoh_filename, charge_method=None)

        mol2_filenames = [gaff_mol2_filename0, gaff_mol2_filename1]
        frcmod_filenames = [frcmod_filename0, frcmod_filename1]

        prmtop_filename = "./out.prmtop"
        inpcrd_filename = "./out.inpcrd"

        tleap_cmd = amber.build_mixture_prmtop(mol2_filenames,
                                               frcmod_filenames, box_filename,
                                               prmtop_filename,
                                               inpcrd_filename)
        print(tleap_cmd)
예제 #4
0
def test_amber_binary_mixture():
    sustiva_filename = utils.get_data_filename("chemicals/etoh/etoh.mol2")
    etoh_filename = utils.get_data_filename("chemicals/etoh/etoh_renamed.mol2")

    trj0, trj1 = md.load(sustiva_filename), md.load(etoh_filename)
    
    # Hack to assign unique residue names that are consistent with contents of mol2 files
    trj0.top.residue(0).name = "LIG"
    trj1.top.residue(0).name = "LI2"
    
    trj_list = [trj0, trj1]
    
    with utils.enter_temp_directory():  # Prevents creating tons of GAFF files everywhere.
        
        box_filename = "./box.pdb"
        box_trj = packmol.pack_box(trj_list, [25, 50])
        box_trj.save(box_filename)
        
        gaff_mol2_filename0, frcmod_filename0 = amber.run_antechamber("sustiva", sustiva_filename, charge_method=None)
        gaff_mol2_filename1, frcmod_filename1 = amber.run_antechamber("etoh", etoh_filename, charge_method=None)
        
        mol2_filenames = [gaff_mol2_filename0, gaff_mol2_filename1]
        frcmod_filenames = [frcmod_filename0, frcmod_filename1]
        
        
        prmtop_filename = "./out.prmtop"
        inpcrd_filename = "./out.inpcrd"

        tleap_cmd = amber.build_mixture_prmtop(mol2_filenames, frcmod_filenames, box_filename, prmtop_filename, inpcrd_filename)
        print(tleap_cmd)
def imatinib_timing():
    print("Loading imatinib...")
    # Load the PDB file.
    from simtk.openmm.app import PDBFile
    pdb_filename = utils.get_data_filename("chemicals/imatinib/imatinib.pdb")
    pdb = PDBFile(pdb_filename)
    # Create a ForceField object.
    gaff_xml_filename = utils.get_data_filename("parameters/gaff.xml")
    forcefield = ForceField(gaff_xml_filename)
    # Add the residue template generator.
    from openmoltools.forcefield_generators import gaffTemplateGenerator
    forcefield.registerTemplateGenerator(gaffTemplateGenerator)
    # Parameterize system.
    system = forcefield.createSystem(pdb.topology, nonbondedMethod=NoCutoff)
    integrator = openmm.LangevinIntegrator(300 * unit.kelvin, 5.0 / unit.picoseconds, 1.0 * unit.femtoseconds)
    # Create Context
    context = openmm.Context(system, integrator)
    context.setPositions(pdb.positions)
    integrator.step(100)

    import time
    nsteps = 10000000
    initial_time = time.time()
    integrator.step(nsteps)
    state = context.getState().getPeriodicBoxVectors() # force dynamics
    final_time = time.time()
    elapsed_time = final_time / initial_time
    time_per_step = elapsed_time / float(nsteps)
    print('time per force evaluation is %.3f us' % (time_per_step*1e6))
예제 #6
0
def test_gromacs_merge():
    etoh_filename = utils.get_data_filename("chemicals/etoh/etoh.mol2")
    benzene_filename = utils.get_data_filename("chemicals/benzene/benzene.mol2")

    with utils.enter_temp_directory(): #Prevents creating lots of tleap/antechamber files everywhere
        #Generate frcmod files, mol2 files
        gaff_mol2_filename1, frcmod_filename1 = amber.run_antechamber( "etoh", etoh_filename, charge_method = None)
        gaff_mol2_filename2, frcmod_filename2 = amber.run_antechamber( "benzene", benzene_filename, charge_method = None)

        #Set file names
        prmtop_filename1 = "./out1.prmtop"
        prmtop_filename2 = "./out2.prmtop"
        crd_filename1 = "./out1.inpcrd"
        crd_filename2 = "./out2.inpcrd"
        top_filename1 = "./out1.top"
        top_filename2 = "./out2.top"
        gro_filename1 = "./out1.gro"
        gro_filename2 = "./out2.gro"

        #Generate AMBER files
        amber.run_tleap( 'etoh', gaff_mol2_filename1, frcmod_filename1, prmtop_filename1, crd_filename1 )
        amber.run_tleap( 'benzene', gaff_mol2_filename2, frcmod_filename2, prmtop_filename2, crd_filename2 )

        #Convert to GROMACS
        utils.convert_via_acpype( "etoh", prmtop_filename1, crd_filename1, out_top = top_filename1, out_gro = gro_filename1 ) 
        utils.convert_via_acpype( "benzene", prmtop_filename2, crd_filename2, out_top = top_filename2, out_gro = gro_filename2 )

        #Merge topologies
        gromacs.merge_topologies( [ top_filename1, top_filename2], './combined.top', 'combined', molecule_numbers = [1, 5], molecule_names = ['etoh', 'benzene'] )

        #Test editing of molecule numbers in topology file
        gromacs.change_molecules_section( './combined.top', './edited.top', ['etoh', 'benzene'], [10, 20] )
def test_gaffResidueTemplateGenerator():
    """
    Test the GAFF residue template generator.
    """

    #
    # Test where we generate parameters for only a ligand.
    #

    # Load the PDB file.
    from simtk.openmm.app import PDBFile

    pdb_filename = utils.get_data_filename("chemicals/imatinib/imatinib.pdb")
    pdb = PDBFile(pdb_filename)
    # Create a ForceField object.
    forcefield = ForceField("gaff.xml")
    # Add the residue template generator.
    from openmoltools.forcefield_generators import gaffTemplateGenerator

    forcefield.registerTemplateGenerator(gaffTemplateGenerator)
    # Parameterize system.
    system = forcefield.createSystem(pdb.topology, nonbondedMethod=NoCutoff)
    # Check potential is finite.
    check_potential_is_finite(system, pdb.positions)
    # Check energy matches prmtop route.
    check_energy_components_vs_prmtop(
        prmtop=utils.get_data_filename("chemicals/imatinib/imatinib.prmtop"),
        inpcrd=utils.get_data_filename("chemicals/imatinib/imatinib.inpcrd"),
        system=system,
    )

    #
    # Test where we generate parameters for only a ligand in a protein.
    #

    # Load the PDB file.
    from simtk.openmm.app import PDBFile

    pdb_filename = utils.get_data_filename("chemicals/proteins/T4-lysozyme-L99A-p-xylene-implicit.pdb")
    pdb = PDBFile(pdb_filename)
    # Create a ForceField object.
    forcefield = ForceField("amber99sb.xml", "gaff.xml")
    # Add the residue template generator.
    from openmoltools.forcefield_generators import gaffTemplateGenerator

    forcefield.registerTemplateGenerator(gaffTemplateGenerator)
    # Parameterize system.
    system = forcefield.createSystem(pdb.topology, nonbondedMethod=NoCutoff)
    # Check potential is finite.
    check_potential_is_finite(system, pdb.positions)
예제 #8
0
def test_run_antechamber_charges():
    molecule_name = "acetate"
    input_filename = utils.get_data_filename("chemicals/acetate/acetate.mol2")
    with utils.enter_temp_directory():  # Prevents creating tons of GAFF files everywhere.
        gaff_mol2_filename, frcmod_filename = utils.run_antechamber(
            molecule_name, input_filename, charge_method=None, net_charge=-1
        )
예제 #9
0
def test_standardize_water():
    """Test utility function standardize_water.

    The water bonds must be recognized even when residue names do not
    match the standard definition in mdtraj.formats.pdb.data.residues.xml.

    """
    water_filepath = utils.get_data_filename("chemicals/water/water.mol2")
    water_traj = md.load(water_filepath)

    # Store in pdb format and lose CONECT records.
    water_pdb_filepath = tempfile.mktemp(suffix='.pdb')
    water_traj.save_pdb(water_pdb_filepath)
    with open(water_pdb_filepath, 'r') as f:
        pdb_lines = f.readlines()
    with open(water_pdb_filepath, 'w') as f:
        for line in pdb_lines:
            if line[:6] != 'CONECT':
                f.write(line)

    # Test pre-condition: MDTraj cannot detect water bonds automatically.
    water_traj = md.load(water_pdb_filepath)
    assert water_traj.topology.n_bonds == 0

    # The function modifies the Trajectory and bonds are now recognized.
    assert packmol.standardize_water(water_traj) is True
    assert water_traj.topology.n_bonds == 2

    # Remove temporary file.
    os.remove(water_pdb_filepath)
예제 #10
0
def test_standardize_water():
    """Test utility function standardize_water.

    The water bonds must be recognized even when residue names do not
    match the standard definition in mdtraj.formats.pdb.data.residues.xml.

    """
    water_filepath = utils.get_data_filename("chemicals/water/water.mol2")
    water_traj = md.load(water_filepath)

    # Store in pdb format and lose CONECT records.
    water_pdb_filepath = tempfile.mktemp(suffix='.pdb')
    water_traj.save_pdb(water_pdb_filepath)
    with open(water_pdb_filepath, 'r') as f:
        pdb_lines = f.readlines()
    with open(water_pdb_filepath, 'w') as f:
        for line in pdb_lines:
            if line[:6] != 'CONECT':
                f.write(line)

    # Test pre-condition: MDTraj cannot detect water bonds automatically.
    water_traj = md.load(water_pdb_filepath)
    assert water_traj.topology.n_bonds == 0

    # The function modifies the Trajectory and bonds are now recognized.
    assert packmol.standardize_water(water_traj) is True
    assert water_traj.topology.n_bonds == 2

    # Remove temporary file.
    os.remove(water_pdb_filepath)
예제 #11
0
def _drug_tester(n_molecules=3404, charge_method="bcc"):
    """Helper function for running various versions of the drug parameterization benchmark."""
    assert n_molecules <= 3404, "The maximum number of molecules is 3404."
    assert charge_method in ["bcc", None
                             ], "Charge method must be either None or 'bcc'"

    path = tempfile.mkdtemp()
    database_filename = utils.get_data_filename("chemicals/drugs/Zdd.mol2.gz")
    cmd = "gunzip -c %s > %s/Zdd.mol2" % (database_filename, path)
    os.system(cmd)
    cmd = """awk '/MOLECULE/{close(x);x="%s/molecule_"i++".mol2"}{print > x}' %s/Zdd.mol2""" % (
        path, path)
    os.system(cmd)

    for k in range(n_molecules):
        molecule_name = "molecule_%d" % k
        mol2_filename = "%s/%s.mol2" % (path, molecule_name)
        cmd = """sed -i "s/<0>/LIG/" %s""" % mol2_filename
        os.system(
            cmd
        )  # Have to remove the <0> because it leads to invalid XML in the forcefield files.
        with utils.enter_temp_directory():
            yield utils.tag_description(
                lambda: utils.test_molecule(
                    "LIG", mol2_filename, charge_method=CHARGE_METHOD),
                "Testing drugs %s with charge method %s" %
                (molecule_name, CHARGE_METHOD))
예제 #12
0
def test_run_antechamber_charges():
    molecule_name = "acetate"
    input_filename = utils.get_data_filename("chemicals/acetate/acetate.mol2")
    with utils.enter_temp_directory(
    ):  # Prevents creating tons of GAFF files everywhere.
        gaff_mol2_filename, frcmod_filename = amber.run_antechamber(
            molecule_name, input_filename, charge_method=None, net_charge=-1)
예제 #13
0
def test_parse_ligand_filename():
    molecule_name = "sustiva"
    input_filename = utils.get_data_filename("chemicals/sustiva/sustiva.mol2")
    name, ext = utils.parse_ligand_filename(input_filename)

    eq(name, "sustiva")
    eq(ext, ".mol2")
def test_system_generator():
    """
    Test SystemGenerator.
    """
    from functools import partial
    # Vacuum tests.
    ffxmls = ['amber99sbildn.xml']
    forcefield_kwargs = {'nonbondedMethod': NoCutoff, 'implicitSolvent': None, 'constraints': None}
    for testsystem_name in ['AlanineDipeptideVacuum']:
        f = partial(check_system_generator, ffxmls, forcefield_kwargs, testsystem_name)
        f.description = 'Testing SystemGenerator on %s' % testsystem_name
        yield f

    # Implicit solvent tests.
    ffxmls = ['amber99sbildn.xml', 'amber99_obc.xml']
    forcefield_kwargs = {'nonbondedMethod': NoCutoff, 'implicitSolvent': OBC2, 'constraints': None}
    for testsystem_name in ['AlanineDipeptideImplicit']:
        f = partial(check_system_generator, ffxmls, forcefield_kwargs, testsystem_name)
        f.description = 'Testing SystemGenerator on %s' % testsystem_name
        yield f

    # Small molecule tests.
    gaff_xml_filename = utils.get_data_filename("parameters/gaff.xml")
    ffxmls = [gaff_xml_filename]
    forcefield_kwargs = {'nonbondedMethod': NoCutoff, 'implicitSolvent': None, 'constraints': None}
    for name in IUPAC_molecule_names:
        f = partial(check_system_generator, ffxmls, forcefield_kwargs, name, use_gaff=True)
        f.description = 'Testing SystemGenerator on %s' % name
        yield f
예제 #15
0
def test_generate_ffxml_from_molecules():
    """
    Test generation of single ffxml file from a list of molecules
    """
    # Create a test set of molecules.
    molecules = [createOEMolFromIUPAC(name) for name in IUPAC_molecule_names]
    # Create an ffxml file.
    from openmoltools.forcefield_generators import generateForceFieldFromMolecules
    ffxml = generateForceFieldFromMolecules(molecules)
    # Create a ForceField.
    gaff_xml_filename = utils.get_data_filename("parameters/gaff.xml")
    forcefield = ForceField(gaff_xml_filename)
    try:
        forcefield.loadFile(StringIO(ffxml))
    except Exception as e:
        msg = str(e)
        msg += "ffxml contents:\n"
        for (index, line) in enumerate(ffxml.split('\n')):
            msg += 'line %8d : %s\n' % (index, line)
        raise Exception(msg)

    # Parameterize the molecules.
    from openmoltools.forcefield_generators import generateTopologyFromOEMol
    for molecule in molecules:
        # Create topology from molecule.
        topology = generateTopologyFromOEMol(molecule)
        # Create system with forcefield.
        system = forcefield.createSystem(topology)
        # Check potential is finite.
        positions = extractPositionsFromOEMOL(molecule)
        check_potential_is_finite(system, positions)
def test_generate_ffxml_from_molecules():
    """
    Test generation of single ffxml file from a list of molecules
    """
    # Create a test set of molecules.
    molecules = [createOEMolFromIUPAC(name) for name in IUPAC_molecule_names]
    # Create an ffxml file.
    from openmoltools.forcefield_generators import generateForceFieldFromMolecules

    ffxml = generateForceFieldFromMolecules(molecules)
    # Create a ForceField.
    gaff_xml_filename = utils.get_data_filename("parameters/gaff.xml")
    forcefield = ForceField(gaff_xml_filename)
    try:
        forcefield.loadFile(StringIO(ffxml))
    except Exception as e:
        msg = str(e)
        msg += "ffxml contents:\n"
        for (index, line) in enumerate(ffxml.split("\n")):
            msg += "line %8d : %s\n" % (index, line)
        raise Exception(msg)

    # Parameterize the molecules.
    from openmoltools.forcefield_generators import generateTopologyFromOEMol

    for molecule in molecules:
        # Create topology from molecule.
        topology = generateTopologyFromOEMol(molecule)
        # Create system with forcefield.
        system = forcefield.createSystem(topology)
        # Check potential is finite.
        positions = extractPositionsFromOEMOL(molecule)
        check_potential_is_finite(system, positions)
예제 #17
0
def test_acpype_conversion():
    molecule_name = 'sustiva'
    input_filename = utils.get_data_filename("chemicals/sustiva/sustiva.mol2")
    with utils.enter_temp_directory(): # Prevents creating tons of GAFF files everywhere.
        gaff_mol2_filename, frcmod_filename = amber.run_antechamber(molecule_name, input_filename, charge_method=None)
        prmtop, inpcrd = amber.run_tleap(molecule_name, gaff_mol2_filename, frcmod_filename)
        out_top, out_gro = utils.convert_via_acpype( molecule_name, prmtop, inpcrd ) 
예제 #18
0
def test_amber_box():
    etoh_filename = utils.get_data_filename("chemicals/etoh/etoh.mol2")
    trj_list = [md.load(etoh_filename)]

    with utils.enter_temp_directory(
    ):  # Prevents creating tons of GAFF files everywhere.

        box_filename = "./box.pdb"
        box_trj = packmol.pack_box(trj_list, [50])
        box_trj.save(box_filename)

        gaff_mol2_filename1, frcmod_filename1 = amber.run_antechamber(
            "etoh", etoh_filename, charge_method=None)

        mol2_filenames = [gaff_mol2_filename1]
        frcmod_filenames = [frcmod_filename1]

        prmtop_filename = "./out.prmtop"
        inpcrd_filename = "./out.inpcrd"

        tleap_cmd = amber.build_mixture_prmtop(mol2_filenames,
                                               frcmod_filenames, box_filename,
                                               prmtop_filename,
                                               inpcrd_filename)
        print(tleap_cmd)
예제 #19
0
def _tester_load_freesolv_gaffmol2_vs_sybylmol2_vs_obabelpdb(
        charge_method="bcc"):
    with utils.enter_temp_directory():

        tar_filename = utils.get_data_filename(
            "chemicals/freesolv/freesolve_v0.3.tar.bz2")
        tar = tarfile.open(tar_filename, mode="r:bz2")
        tar.extractall()
        tar.close()

        database = pickle.load(open("./v0.3/database.pickle"))
        for key in database:
            for directory in ["mol2files_gaff", "mol2files_sybyl"]:
                gaff_filename = os.path.abspath("./v0.3/%s/%s.mol2" %
                                                (directory, key))

                cmd = """sed -i "s/<0>/LIG/" %s""" % gaff_filename
                os.system(
                    cmd
                )  # Have to remove the <0> because it leads to invalid XML in the forcefield files.

                t_gaff = md.load(gaff_filename)

                with utils.enter_temp_directory():
                    yield utils.tag_description(
                        lambda: utils.test_molecule(
                            "LIG", gaff_filename, charge_method=charge_method),
                        "Testing freesolv %s %s with charge model %s" %
                        (directory, key, charge_method))
예제 #20
0
def test_parse_ligand_filename():
    molecule_name = "sustiva"
    input_filename = utils.get_data_filename("chemicals/sustiva/sustiva.mol2")
    name, ext = utils.parse_ligand_filename(input_filename)

    eq(name, "sustiva")
    eq(ext, ".mol2")
예제 #21
0
def test_run_antechamber_resname():
    molecule_name = "sustiva"
    input_filename = utils.get_data_filename("chemicals/sustiva/sustiva.mol2")
    with utils.enter_temp_directory():  # Prevents creating tons of GAFF files everywhere.
        gaff_mol2_filename, frcmod_filename = amber.run_antechamber(molecule_name, input_filename, charge_method=None, resname=True)
        with open(gaff_mol2_filename, 'r') as fin:
            fin.readline()
            assert fin.readline().strip() == molecule_name
예제 #22
0
def test_drugs():
    import openeye.oechem
    database_filename = utils.get_data_filename("chemicals/drugs/Zdd.mol2.gz")
    ifs = openeye.oechem.oemolistream(database_filename)
    for molecule in ifs.GetOEMols():
        with utils.enter_temp_directory():
            molecule_name, tripos_mol2_filename = utils.molecule_to_mol2(molecule)
            yield utils.tag_description(lambda : utils.test_molecule(molecule_name, tripos_mol2_filename), "Testing drugs %s" % molecule_name)
예제 #23
0
def test_amber_water_mixture():
    water_filename = utils.get_data_filename("chemicals/water/water.mol2")
    etoh_filename = utils.get_data_filename("chemicals/etoh/etoh.mol2")
    sustiva_filename = utils.get_data_filename("chemicals/sustiva/sustiva.mol2")

    with utils.enter_temp_directory():  # Prevents creating tons of GAFF files everywhere.
        shutil.copy( water_filename, 'c1.mol2' )
        shutil.copy( etoh_filename, 'c2.mol2' )
        shutil.copy( sustiva_filename, 'c3.mol2')
        water_filename = 'c1.mol2'
        etoh_filename = 'c2.mol2'
        sustiva_filename = 'c3.mol2'
        #Randomize residue names to avoid clashes
        utils.randomize_mol2_residue_names( [ water_filename, etoh_filename, sustiva_filename] )

        trj0, trj1, trj2 = md.load(water_filename), md.load(etoh_filename), md.load(sustiva_filename)

        trj_list = [trj0, trj1, trj2]
        
        box_filename = "./box.pdb"
        box_trj = packmol.pack_box(trj_list, [300, 25, 3])
        box_trj.save(box_filename)
        
        gaff_mol2_filename0, frcmod_filename0 = amber.run_antechamber("water", water_filename, charge_method=None)
        gaff_mol2_filename1, frcmod_filename1 = amber.run_antechamber("etoh", etoh_filename, charge_method=None)
        gaff_mol2_filename2, frcmod_filename2 = amber.run_antechamber("sustiva", sustiva_filename, charge_method=None)
        
        mol2_filenames = [gaff_mol2_filename0, gaff_mol2_filename1, gaff_mol2_filename2]
        frcmod_filenames = [frcmod_filename0, frcmod_filename1, frcmod_filename2]
        
        
        prmtop_filename = "./out.prmtop"
        inpcrd_filename = "./out.inpcrd"

        shutil.copy(box_filename, 'renamed.pdb')
        tleap_cmd = amber.build_mixture_prmtop(mol2_filenames, frcmod_filenames, 'renamed.pdb', prmtop_filename, inpcrd_filename)
        print(tleap_cmd)

        #Also do here for case of GAFF water
        tleap_cmd = amber.build_mixture_prmtop(mol2_filenames, frcmod_filenames, box_filename, prmtop_filename, inpcrd_filename, water_model = None)
        print(tleap_cmd)

        #Also do here for case of SPC
        tleap_cmd = amber.build_mixture_prmtop(mol2_filenames, frcmod_filenames, 'renamed.pdb', prmtop_filename, inpcrd_filename, water_model = 'SPC')
        print(tleap_cmd)
예제 #24
0
def test_run_tleap():
    molecule_name = "sustiva"
    input_filename = utils.get_data_filename("chemicals/sustiva/sustiva.mol2")
    with utils.enter_temp_directory(
    ):  # Prevents creating tons of GAFF files everywhere.
        gaff_mol2_filename, frcmod_filename = amber.run_antechamber(
            molecule_name, input_filename, charge_method=None)
        prmtop, inpcrd = amber.run_tleap(molecule_name, gaff_mol2_filename,
                                         frcmod_filename)
예제 #25
0
def test_run_antechamber_resname():
    molecule_name = "sustiva"
    input_filename = utils.get_data_filename("chemicals/sustiva/sustiva.mol2")
    with utils.enter_temp_directory(
    ):  # Prevents creating tons of GAFF files everywhere.
        gaff_mol2_filename, frcmod_filename = amber.run_antechamber(
            molecule_name, input_filename, charge_method=None, resname=True)
        with open(gaff_mol2_filename, 'r') as fin:
            fin.readline()
            assert fin.readline().strip() == molecule_name
예제 #26
0
def test_ffxml_simulation():
    """Test converting toluene and benzene smiles to oemol to ffxml to openmm simulation."""
    with utils.enter_temp_directory():
        m0 = openmoltools.openeye.smiles_to_oemol("Cc1ccccc1")
        charged0 = openmoltools.openeye.get_charges(m0)
        m1 = openmoltools.openeye.smiles_to_oemol("c1ccccc1")
        charged1 = openmoltools.openeye.get_charges(m1)
        ligands = [charged0, charged1]
        n_atoms = [15,12]

        trajectories, ffxml = openmoltools.openeye.oemols_to_ffxml(ligands)
        eq(len(trajectories),len(ligands))

        pdb_filename = utils.get_data_filename("chemicals/proteins/1vii.pdb")

        temperature = 300 * u.kelvin
        friction = 0.3 / u.picosecond
        timestep = 0.01 * u.femtosecond

        protein_traj = md.load(pdb_filename)
        protein_traj.center_coordinates()

        protein_top = protein_traj.top.to_openmm()
        protein_xyz = protein_traj.openmm_positions(0)

        for k, ligand in enumerate(ligands):
            ligand_traj = trajectories[k]
            ligand_traj.center_coordinates()

            eq(ligand_traj.n_atoms, n_atoms[k])
            eq(ligand_traj.n_frames, 1)

            #Move the pre-centered ligand sufficiently far away from the protein to avoid a clash.
            min_atom_pair_distance = ((ligand_traj.xyz[0] ** 2.).sum(1) ** 0.5).max() + ((protein_traj.xyz[0] ** 2.).sum(1) ** 0.5).max() + 0.3
            ligand_traj.xyz += np.array([1.0, 0.0, 0.0]) * min_atom_pair_distance

            ligand_xyz = ligand_traj.openmm_positions(0)
            ligand_top = ligand_traj.top.to_openmm()

            ffxml.seek(0)
            forcefield = app.ForceField("amber10.xml", ffxml, "tip3p.xml")

            model = app.modeller.Modeller(protein_top, protein_xyz)
            model.add(ligand_top, ligand_xyz)
            model.addSolvent(forcefield, padding=0.4 * u.nanometer)

            system = forcefield.createSystem(model.topology, nonbondedMethod=app.PME, nonbondedCutoff=1.0 * u.nanometers, constraints=app.HAngles)

            integrator = mm.LangevinIntegrator(temperature, friction, timestep)

            simulation = app.Simulation(model.topology, system, integrator)
            simulation.context.setPositions(model.positions)
            print("running")
            simulation.step(1)
예제 #27
0
def test_acpype_conversion():
    molecule_name = 'sustiva'
    input_filename = utils.get_data_filename("chemicals/sustiva/sustiva.mol2")
    with utils.enter_temp_directory(
    ):  # Prevents creating tons of GAFF files everywhere.
        gaff_mol2_filename, frcmod_filename = amber.run_antechamber(
            molecule_name, input_filename, charge_method=None)
        prmtop, inpcrd = amber.run_tleap(molecule_name, gaff_mol2_filename,
                                         frcmod_filename)
        out_top, out_gro = utils.convert_via_acpype(molecule_name, prmtop,
                                                    inpcrd)
예제 #28
0
def test_ffxml_simulation():
    """Test converting toluene and benzene smiles to oemol to ffxml to openmm simulation."""
    with utils.enter_temp_directory():    
        m0 = openmoltools.openeye.smiles_to_oemol("Cc1ccccc1")
        charged0 = openmoltools.openeye.get_charges(m0)
        m1 = openmoltools.openeye.smiles_to_oemol("c1ccccc1")
        charged1 = openmoltools.openeye.get_charges(m1)
        ligands = [charged0, charged1]
        n_atoms = [15,12]

        trajectories, ffxml = openmoltools.openeye.oemols_to_ffxml(ligands)
        eq(len(trajectories),len(ligands))

        pdb_filename = utils.get_data_filename("chemicals/proteins/1vii.pdb")

        temperature = 300 * u.kelvin
        friction = 0.3 / u.picosecond
        timestep = 0.01 * u.femtosecond

        protein_traj = md.load(pdb_filename)
        protein_traj.center_coordinates()

        protein_top = protein_traj.top.to_openmm()
        protein_xyz = protein_traj.openmm_positions(0)

        for k, ligand in enumerate(ligands):
            ligand_traj = trajectories[k]
            ligand_traj.center_coordinates()
        
            eq(ligand_traj.n_atoms, n_atoms[k])
            eq(ligand_traj.n_frames, 1)

            #Move the pre-centered ligand sufficiently far away from the protein to avoid a clash.  
            min_atom_pair_distance = ((ligand_traj.xyz[0] ** 2.).sum(1) ** 0.5).max() + ((protein_traj.xyz[0] ** 2.).sum(1) ** 0.5).max() + 0.3
            ligand_traj.xyz += np.array([1.0, 0.0, 0.0]) * min_atom_pair_distance

            ligand_xyz = ligand_traj.openmm_positions(0)
            ligand_top = ligand_traj.top.to_openmm()

            ffxml.seek(0)
            forcefield = app.ForceField("amber10.xml", ffxml, "tip3p.xml")

            model = app.modeller.Modeller(protein_top, protein_xyz)
            model.add(ligand_top, ligand_xyz)
            model.addSolvent(forcefield, padding=0.4 * u.nanometer)

            system = forcefield.createSystem(model.topology, nonbondedMethod=app.PME, nonbondedCutoff=1.0 * u.nanometers, constraints=app.HAngles)

            integrator = mm.LangevinIntegrator(temperature, friction, timestep)

            simulation = app.Simulation(model.topology, system, integrator)
            simulation.context.setPositions(model.positions)
            print("running")
            simulation.step(1)
예제 #29
0
def test_gromacs_solvate():
    etoh_filename = utils.get_data_filename("chemicals/etoh/etoh.mol2")
    with utils.enter_temp_directory(): #Prevents creating lots of tleap/antechamber files everywhere
        #Generate frcmod files, mol2 files
        gaff_mol2_filename, frcmod_filename = amber.run_antechamber( "etoh", etoh_filename, charge_method = None)

        #Amber setup
        amber.run_tleap( 'etoh', gaff_mol2_filename, frcmod_filename, 'etoh.prmtop', 'etoh.crd' )
        #GROMACS conversion
        utils.convert_via_acpype( 'etoh', 'etoh.prmtop', 'etoh.crd', 'etoh.top', 'etoh.gro' )
        #Solvate
        gromacs.do_solvate( 'etoh.top', 'etoh.gro', 'etoh_solvated.top', 'etoh_solvated.gro', 1.2, 'dodecahedron', 'spc216', 'tip3p.itp' )
예제 #30
0
def test_drugs():
    import openeye.oechem
    database_filename = utils.get_data_filename("chemicals/drugs/Zdd.mol2.gz")
    ifs = openeye.oechem.oemolistream(database_filename)
    for molecule in ifs.GetOEMols():
        with utils.enter_temp_directory():
            molecule_name, tripos_mol2_filename = utils.molecule_to_mol2(
                molecule)
            yield utils.tag_description(
                lambda: utils.test_molecule(molecule_name, tripos_mol2_filename
                                            ),
                "Testing drugs %s" % molecule_name)
예제 #31
0
def test_system_generator():
    """
    Test SystemGenerator.
    """
    import openmmtools
    from functools import partial
    # Vacuum tests.
    ffxmls = ['amber99sbildn.xml']
    forcefield_kwargs = {
        'nonbondedMethod': NoCutoff,
        'implicitSolvent': None,
        'constraints': None
    }
    for testsystem_name in ['AlanineDipeptideVacuum']:
        constructor = getattr(openmmtools.testsystems, testsystem_name)
        testsystem = constructor()
        f = partial(check_system_generator, ffxmls, forcefield_kwargs,
                    testsystem.topology)
        f.description = 'Testing SystemGenerator on %s' % testsystem_name
        yield f
    # Implicit solvent tests.
    ffxmls = ['amber99sbildn.xml', 'amber99_obc.xml']
    forcefield_kwargs = {
        'nonbondedMethod': NoCutoff,
        'implicitSolvent': OBC2,
        'constraints': None
    }
    for testsystem_name in ['AlanineDipeptideImplicit']:
        constructor = getattr(openmmtools.testsystems, testsystem_name)
        testsystem = constructor()
        f = partial(check_system_generator, ffxmls, forcefield_kwargs,
                    testsystem.topology)
        f.description = 'Testing SystemGenerator on %s' % testsystem_name
        yield f
    # Small molecule tests.
    from openmoltools.forcefield_generators import generateTopologyFromOEMol
    gaff_xml_filename = utils.get_data_filename("parameters/gaff.xml")
    ffxmls = [gaff_xml_filename]
    forcefield_kwargs = {
        'nonbondedMethod': NoCutoff,
        'implicitSolvent': None,
        'constraints': None
    }
    for name in IUPAC_molecule_names:
        molecule = createOEMolFromIUPAC(name)
        topology = generateTopologyFromOEMol(molecule)
        f = partial(check_system_generator,
                    ffxmls,
                    forcefield_kwargs,
                    topology,
                    use_gaff=True)
        f.description = 'Testing SystemGenerator on %s' % name
        yield f
예제 #32
0
def test_gromacs_solvate():
    etoh_filename = utils.get_data_filename("chemicals/etoh/etoh.mol2")
    with utils.enter_temp_directory(): #Prevents creating lots of tleap/antechamber files everywhere
        #Generate frcmod files, mol2 files
        gaff_mol2_filename, frcmod_filename = amber.run_antechamber( "etoh", etoh_filename, charge_method = None)

        #Amber setup
        amber.run_tleap( 'etoh', gaff_mol2_filename, frcmod_filename, 'etoh.prmtop', 'etoh.crd' )
        #GROMACS conversion
        utils.amber_to_gromacs( 'etoh', 'etoh.prmtop', 'etoh.crd', 'etoh.top', 'etoh.gro' )
        #Solvate
        gromacs.do_solvate( 'etoh.top', 'etoh.gro', 'etoh_solvated.top', 'etoh_solvated.gro', 1.2, 'dodecahedron', 'spc216', 'tip3p.itp' )
def test_generateResidueTemplate():
    """
    Test GAFF residue template generation from OEMol molecules.
    """
    from openeye import oechem, oeiupac

    from pkg_resources import resource_filename

    gaff_xml_filename = utils.get_data_filename("parameters/gaff.xml")

    # Test independent ForceField instances.
    for molecule_name in IUPAC_molecule_names:
        mol = createOEMolFromIUPAC(molecule_name)
        # Generate an ffxml residue template.
        from openmoltools.forcefield_generators import generateResidueTemplate

        [template, ffxml] = generateResidueTemplate(mol)
        # Create a ForceField object.
        forcefield = ForceField(gaff_xml_filename)
        # Add the additional parameters and template to the forcefield.
        forcefield.registerResidueTemplate(template)
        forcefield.loadFile(StringIO(ffxml))
        # Create a Topology from the molecule.
        from openmoltools.forcefield_generators import generateTopologyFromOEMol

        topology = generateTopologyFromOEMol(mol)
        # Parameterize system.
        system = forcefield.createSystem(topology, nonbondedMethod=NoCutoff)
        # Check potential is finite.
        positions = extractPositionsFromOEMOL(mol)
        check_potential_is_finite(system, positions)

    # Test adding multiple molecules to a single ForceField instance.
    forcefield = ForceField(gaff_xml_filename)
    for molecule_name in IUPAC_molecule_names:
        mol = createOEMolFromIUPAC(molecule_name)
        # Generate an ffxml residue template.
        from openmoltools.forcefield_generators import generateResidueTemplate

        [template, ffxml] = generateResidueTemplate(mol)
        # Add the additional parameters and template to the forcefield.
        forcefield.registerResidueTemplate(template)
        forcefield.loadFile(StringIO(ffxml))
        # Create a Topology from the molecule.
        from openmoltools.forcefield_generators import generateTopologyFromOEMol

        topology = generateTopologyFromOEMol(mol)
        # Parameterize system.
        system = forcefield.createSystem(topology, nonbondedMethod=NoCutoff)
        # Check potential is finite.
        positions = extractPositionsFromOEMOL(mol)
        check_potential_is_finite(system, positions)
예제 #34
0
def test_parmed_conversion():
    molecule_name = 'sustiva'
    input_filename = utils.get_data_filename("chemicals/sustiva/sustiva.mol2")
    with utils.enter_temp_directory(
    ):  # Prevents creating tons of GAFF files everywhere.
        #Make sure conversion runs
        gaff_mol2_filename, frcmod_filename = amber.run_antechamber(
            molecule_name, input_filename, charge_method=None)
        prmtop, inpcrd = amber.run_tleap(molecule_name, gaff_mol2_filename,
                                         frcmod_filename)
        out_top, out_gro = utils.amber_to_gromacs(molecule_name,
                                                  prmtop,
                                                  inpcrd,
                                                  precision=8)

        #Test energies before and after conversion
        #Set up amber system
        a = parmed.amber.AmberParm(prmtop, inpcrd)
        ambersys = a.createSystem()
        ambercon = mmmm.Context(ambersys, mm.VerletIntegrator(0.001))
        ambercon.setPositions(a.positions)
        #Set up GROMACS system
        g = parmed.load_file(out_top)
        gro = parmed.gromacs.GromacsGroFile.parse(out_gro)
        g.box = gro.box
        g.positions = gro.positions
        gromacssys = g.createSystem()
        gromacscon = mmmm.Context(gromacssys, mm.VerletIntegrator(0.001))
        gromacscon.setPositions(g.positions)

        #Check energies
        a_energies = parmed.openmm.utils.energy_decomposition(a, ambercon)
        g_energies = parmed.openmm.utils.energy_decomposition(g, gromacscon)
        #Check components
        tolerance = 1e-5
        ok = True
        for key in a_energies.keys():
            diff = np.abs(a_energies[key] - g_energies[key])
            if diff / np.abs(a_energies[key]) > tolerance:
                ok = False
                print(
                    "In testing AMBER to GROMACS conversion, %s energy differs by %.5g, which is more than a fraction %.2g of the total, so conversion appears not to be working properly."
                    % (key, diff, tolerance))
        if not ok:
            raise (ValueError(
                "AMBER to GROMACS conversion yields energies which are too different."
            ))
def test_system_generator():
    """
    Test SystemGenerator.
    """
    from functools import partial
    # Vacuum tests.
    ffxmls = ['amber99sbildn.xml']
    forcefield_kwargs = {
        'nonbondedMethod': NoCutoff,
        'implicitSolvent': None,
        'constraints': None
    }
    for testsystem_name in ['AlanineDipeptideVacuum']:
        f = partial(check_system_generator, ffxmls, forcefield_kwargs,
                    testsystem_name)
        f.description = 'Testing SystemGenerator on %s' % testsystem_name
        yield f

    # Implicit solvent tests.
    ffxmls = ['amber99sbildn.xml', 'amber99_obc.xml']
    forcefield_kwargs = {
        'nonbondedMethod': NoCutoff,
        'implicitSolvent': OBC2,
        'constraints': None
    }
    for testsystem_name in ['AlanineDipeptideImplicit']:
        f = partial(check_system_generator, ffxmls, forcefield_kwargs,
                    testsystem_name)
        f.description = 'Testing SystemGenerator on %s' % testsystem_name
        yield f

    # Small molecule tests.
    gaff_xml_filename = utils.get_data_filename("parameters/gaff.xml")
    ffxmls = [gaff_xml_filename]
    forcefield_kwargs = {
        'nonbondedMethod': NoCutoff,
        'implicitSolvent': None,
        'constraints': None
    }
    for name in IUPAC_molecule_names:
        f = partial(check_system_generator,
                    ffxmls,
                    forcefield_kwargs,
                    name,
                    use_gaff=True)
        f.description = 'Testing SystemGenerator on %s' % name
        yield f
예제 #36
0
def test_generateResidueTemplate():
    """
    Test GAFF residue template generation from OEMol molecules.
    """
    from openeye import oechem, oeiupac

    from pkg_resources import resource_filename
    gaff_xml_filename = utils.get_data_filename("parameters/gaff.xml")

    # Test independent ForceField instances.
    for molecule_name in IUPAC_molecule_names:
        mol = createOEMolFromIUPAC(molecule_name)
        # Generate an ffxml residue template.
        from openmoltools.forcefield_generators import generateResidueTemplate
        [template, ffxml] = generateResidueTemplate(mol)
        # Create a ForceField object.
        forcefield = ForceField(gaff_xml_filename)
        # Add the additional parameters and template to the forcefield.
        forcefield.registerResidueTemplate(template)
        forcefield.loadFile(StringIO(ffxml))
        # Create a Topology from the molecule.
        from openmoltools.forcefield_generators import generateTopologyFromOEMol
        topology = generateTopologyFromOEMol(mol)
        # Parameterize system.
        system = forcefield.createSystem(topology, nonbondedMethod=NoCutoff)
        # Check potential is finite.
        positions = extractPositionsFromOEMOL(mol)
        check_potential_is_finite(system, positions)

    # Test adding multiple molecules to a single ForceField instance.
    forcefield = ForceField(gaff_xml_filename)
    for molecule_name in IUPAC_molecule_names:
        mol = createOEMolFromIUPAC(molecule_name)
        # Generate an ffxml residue template.
        from openmoltools.forcefield_generators import generateResidueTemplate
        [template, ffxml] = generateResidueTemplate(mol)
        # Add the additional parameters and template to the forcefield.
        forcefield.registerResidueTemplate(template)
        forcefield.loadFile(StringIO(ffxml))
        # Create a Topology from the molecule.
        from openmoltools.forcefield_generators import generateTopologyFromOEMol
        topology = generateTopologyFromOEMol(mol)
        # Parameterize system.
        system = forcefield.createSystem(topology, nonbondedMethod=NoCutoff)
        # Check potential is finite.
        positions = extractPositionsFromOEMOL(mol)
        check_potential_is_finite(system, positions)
예제 #37
0
def test_smiles_conversion():
    pdb_filename = utils.get_data_filename("chemicals/proteins/1vii.pdb")
    smiles = 'Cc1ccccc1'  # Also known as toluene.

    temperature = 300 * u.kelvin
    friction = 0.3 / u.picosecond
    timestep = 0.01 * u.femtosecond

    protein_traj = md.load(pdb_filename)
    protein_traj.center_coordinates()

    protein_top = protein_traj.top.to_openmm()
    protein_xyz = protein_traj.openmm_positions(0)

    ligand_trajectories, ffxml = utils.smiles_to_mdtraj_ffxml([smiles])
    ligand_traj = ligand_trajectories[0]
    ligand_traj.center_coordinates()

    eq(ligand_traj.n_atoms, 15)
    eq(ligand_traj.n_frames, 1)

    #Move the pre-centered ligand sufficiently far away from the protein to avoid a clash.
    min_atom_pair_distance = ((ligand_traj.xyz[0]**2.).sum(1)**0.5).max() + (
        (protein_traj.xyz[0]**2.).sum(1)**0.5).max() + 0.3
    ligand_traj.xyz += np.array([1.0, 0.0, 0.0]) * min_atom_pair_distance

    ligand_xyz = ligand_traj.openmm_positions(0)
    ligand_top = ligand_traj.top.to_openmm()

    forcefield = app.ForceField("amber10.xml", ffxml, "tip3p.xml")

    model = app.modeller.Modeller(protein_top, protein_xyz)
    model.add(ligand_top, ligand_xyz)
    model.addSolvent(forcefield, padding=0.4 * u.nanometer)

    system = forcefield.createSystem(model.topology,
                                     nonbondedMethod=app.PME,
                                     nonbondedCutoff=1.0 * u.nanometers,
                                     constraints=app.HAngles)

    integrator = mm.LangevinIntegrator(temperature, friction, timestep)

    simulation = app.Simulation(model.topology, system, integrator)
    simulation.context.setPositions(model.positions)
    print("running")
    simulation.step(1)
예제 #38
0
def test_smiles_conversion():
    pdb_filename = utils.get_data_filename("chemicals/proteins/1vii.pdb")
    smiles = "Cc1ccccc1"  # Also known as toluene.

    temperature = 300 * u.kelvin
    friction = 0.3 / u.picosecond
    timestep = 0.01 * u.femtosecond

    protein_traj = md.load(pdb_filename)
    protein_traj.center_coordinates()

    protein_top = protein_traj.top.to_openmm()
    protein_xyz = protein_traj.openmm_positions(0)

    ligand_trajectories, ffxml = utils.smiles_to_mdtraj_ffxml([smiles])
    ligand_traj = ligand_trajectories[0]
    ligand_traj.center_coordinates()

    eq(ligand_traj.n_atoms, 15)
    eq(ligand_traj.n_frames, 1)

    # Move the pre-centered ligand sufficiently far away from the protein to avoid a clash.
    min_atom_pair_distance = (
        ((ligand_traj.xyz[0] ** 2.0).sum(1) ** 0.5).max() + ((protein_traj.xyz[0] ** 2.0).sum(1) ** 0.5).max() + 0.3
    )
    ligand_traj.xyz += np.array([1.0, 0.0, 0.0]) * min_atom_pair_distance

    ligand_xyz = ligand_traj.openmm_positions(0)
    ligand_top = ligand_traj.top.to_openmm()

    forcefield = app.ForceField("amber10.xml", ffxml, "tip3p.xml")

    model = app.modeller.Modeller(protein_top, protein_xyz)
    model.add(ligand_top, ligand_xyz)
    model.addSolvent(forcefield, padding=0.4 * u.nanometer)

    system = forcefield.createSystem(
        model.topology, nonbondedMethod=app.PME, nonbondedCutoff=1.0 * u.nanometers, constraints=app.HAngles
    )

    integrator = mm.LangevinIntegrator(temperature, friction, timestep)

    simulation = app.Simulation(model.topology, system, integrator)
    simulation.context.setPositions(model.positions)
    print("running")
    simulation.step(1)
예제 #39
0
def testWriteXMLParametersGAFF():
    """ Test writing XML parameters loaded from Amber GAFF parameter files """

    # Generate ffxml file contents for parmchk-generated frcmod output.
    gaff_dat_filename = utils.get_data_filename("parameters/gaff.dat")
    leaprc = StringIO("parm = loadamberparams %s" % gaff_dat_filename)
    import parmed
    params = parmed.amber.AmberParameterSet.from_leaprc(leaprc)
    params = parmed.openmm.OpenMMParameterSet.from_parameterset(params)
    citations = """\
Wang, J., Wang, W., Kollman P. A.; Case, D. A. "Automatic atom type and bond type perception in molecular mechanical calculations". Journal of Molecular Graphics and Modelling , 25, 2006, 247260.
Wang, J., Wolf, R. M.; Caldwell, J. W.;Kollman, P. A.; Case, D. A. "Development and testing of a general AMBER force field". Journal of Computational Chemistry, 25, 2004, 1157-1174.
"""
    ffxml = str()
    provenance = dict(OriginalFile='gaff.dat', Reference=citations)
    outfile = open('gaff.xml', 'w')
    params.write(outfile, provenance=provenance)
    outfile.close()
def testWriteXMLParametersGAFF():
    """ Test writing XML parameters loaded from Amber GAFF parameter files """

    # Generate ffxml file contents for parmchk-generated frcmod output.
    gaff_dat_filename = utils.get_data_filename("parameters/gaff.dat")
    leaprc = StringIO("parm = loadamberparams %s" % gaff_dat_filename)
    import parmed
    params = parmed.amber.AmberParameterSet.from_leaprc(leaprc)
    params = parmed.openmm.OpenMMParameterSet.from_parameterset(params)
    citations = """\
Wang, J., Wang, W., Kollman P. A.; Case, D. A. "Automatic atom type and bond type perception in molecular mechanical calculations". Journal of Molecular Graphics and Modelling , 25, 2006, 247260.
Wang, J., Wolf, R. M.; Caldwell, J. W.;Kollman, P. A.; Case, D. A. "Development and testing of a general AMBER force field". Journal of Computational Chemistry, 25, 2004, 1157-1174.
"""
    ffxml = str()
    provenance=dict(OriginalFile='gaff.dat', Reference=citations)
    outfile = open('gaff.xml', 'w')
    params.write(outfile, provenance=provenance)
    outfile.close()
예제 #41
0
def _drug_tester(n_molecules=3404, charge_method="bcc"):
    """Helper function for running various versions of the drug parameterization benchmark."""
    assert n_molecules <= 3404, "The maximum number of molecules is 3404."
    assert charge_method in ["bcc", None], "Charge method must be either None or 'bcc'"

    path = tempfile.mkdtemp()
    database_filename = utils.get_data_filename("chemicals/drugs/Zdd.mol2.gz")
    cmd = "gunzip -c %s > %s/Zdd.mol2" % (database_filename, path)
    os.system(cmd)
    cmd = """awk '/MOLECULE/{close(x);x="%s/molecule_"i++".mol2"}{print > x}' %s/Zdd.mol2""" % (path, path)
    os.system(cmd)

    for k in range(n_molecules):
        molecule_name = "molecule_%d" % k
        mol2_filename = "%s/%s.mol2" % (path, molecule_name)
        cmd = """sed -i "s/<0>/LIG/" %s""" % mol2_filename
        os.system(cmd)  # Have to remove the <0> because it leads to invalid XML in the forcefield files.
        with utils.enter_temp_directory():
            yield utils.tag_description(lambda : utils.test_molecule("LIG", mol2_filename, charge_method=CHARGE_METHOD), "Testing drugs %s with charge method %s" % (molecule_name, CHARGE_METHOD))
예제 #42
0
def test_amber_box():
    etoh_filename = utils.get_data_filename("chemicals/etoh/etoh.mol2")
    trj_list = [md.load(etoh_filename)]
    
    with utils.enter_temp_directory():  # Prevents creating tons of GAFF files everywhere.
        
        box_filename = "./box.pdb"
        box_trj = packmol.pack_box(trj_list, [50])
        box_trj.save(box_filename)
    
        gaff_mol2_filename1, frcmod_filename1 = amber.run_antechamber("etoh", etoh_filename, charge_method=None)
        
        mol2_filenames = [gaff_mol2_filename1]
        frcmod_filenames =  [frcmod_filename1]
        
        prmtop_filename = "./out.prmtop"
        inpcrd_filename = "./out.inpcrd"

        tleap_cmd = amber.build_mixture_prmtop(mol2_filenames, frcmod_filenames, box_filename, prmtop_filename, inpcrd_filename)
        print(tleap_cmd)
예제 #43
0
def test_gaffResidueTemplateGenerator():
    """
    Test the GAFF residue template generator.
    """

    #
    # Test where we generate parameters for only a ligand.
    #

    # Load the PDB file.
    from simtk.openmm.app import PDBFile
    pdb_filename = utils.get_data_filename("chemicals/imatinib/imatinib.pdb")
    pdb = PDBFile(pdb_filename)
    # Create a ForceField object.
    gaff_xml_filename = utils.get_data_filename("parameters/gaff.xml")
    forcefield = ForceField(gaff_xml_filename)
    # Add the residue template generator.
    from openmoltools.forcefield_generators import gaffTemplateGenerator
    forcefield.registerTemplateGenerator(gaffTemplateGenerator)
    # Parameterize system.
    system = forcefield.createSystem(pdb.topology, nonbondedMethod=NoCutoff)
    # Check potential is finite.
    check_potential_is_finite(system, pdb.positions)
    # Check energy matches prmtop route.
    check_energy_components_vs_prmtop(
        prmtop=utils.get_data_filename('chemicals/imatinib/imatinib.prmtop'),
        inpcrd=utils.get_data_filename('chemicals/imatinib/imatinib.inpcrd'),
        system=system)

    #
    # Test where we generate parameters for only a ligand in a protein.
    #

    # Load the PDB file.
    from simtk.openmm.app import PDBFile
    pdb_filename = utils.get_data_filename(
        "chemicals/proteins/T4-lysozyme-L99A-p-xylene-implicit.pdb")
    pdb = PDBFile(pdb_filename)
    # Create a ForceField object.
    gaff_xml_filename = utils.get_data_filename("parameters/gaff.xml")
    forcefield = ForceField('amber99sb.xml', gaff_xml_filename)
    # Add the residue template generator.
    from openmoltools.forcefield_generators import gaffTemplateGenerator
    forcefield.registerTemplateGenerator(gaffTemplateGenerator)
    # Parameterize system.
    system = forcefield.createSystem(pdb.topology, nonbondedMethod=NoCutoff)
    # Check potential is finite.
    check_potential_is_finite(system, pdb.positions)
예제 #44
0
def _tester_load_freesolv_gaffmol2_vs_sybylmol2_vs_obabelpdb(charge_method="bcc"):
    with utils.enter_temp_directory():

        tar_filename = utils.get_data_filename("chemicals/freesolv/freesolve_v0.3.tar.bz2")
        tar = tarfile.open(tar_filename, mode="r:bz2")
        tar.extractall()
        tar.close()

        database = pickle.load(open("./v0.3/database.pickle"))
        for key in database:
            for directory in ["mol2files_gaff", "mol2files_sybyl"]:
                gaff_filename = os.path.abspath("./v0.3/%s/%s.mol2" % (directory, key))

                cmd = """sed -i "s/<0>/LIG/" %s""" % gaff_filename
                os.system(cmd)  # Have to remove the <0> because it leads to invalid XML in the forcefield files.

                t_gaff = md.load(gaff_filename)

                with utils.enter_temp_directory():
                    yield utils.tag_description(
                        lambda: utils.test_molecule("LIG", gaff_filename, charge_method=charge_method),
                        "Testing freesolv %s %s with charge model %s" % (directory, key, charge_method),
                    )
예제 #45
0
def test_parmed_conversion():
    molecule_name = 'sustiva'
    input_filename = utils.get_data_filename("chemicals/sustiva/sustiva.mol2")
    with utils.enter_temp_directory(): # Prevents creating tons of GAFF files everywhere.
        #Make sure conversion runs
        gaff_mol2_filename, frcmod_filename = amber.run_antechamber(molecule_name, input_filename, charge_method=None)
        prmtop, inpcrd = amber.run_tleap(molecule_name, gaff_mol2_filename, frcmod_filename)
        out_top, out_gro = utils.amber_to_gromacs( molecule_name, prmtop, inpcrd, precision = 8 ) 

        #Test energies before and after conversion
        #Set up amber system
        a = parmed.amber.AmberParm( prmtop, inpcrd )
        ambersys = a.createSystem()
        ambercon = mmmm.Context( ambersys, mm.VerletIntegrator(0.001))
        ambercon.setPositions( a.positions )
        #Set up GROMACS system
        g = parmed.load_file( out_top )
        gro = parmed.gromacs.GromacsGroFile.parse( out_gro ) 
        g.box = gro.box
        g.positions = gro.positions
        gromacssys = g.createSystem()
        gromacscon = mmmm.Context( gromacssys, mm.VerletIntegrator(0.001))
        gromacscon.setPositions( g.positions ) 

        #Check energies
        a_energies = parmed.openmm.utils.energy_decomposition( a, ambercon )    
        g_energies = parmed.openmm.utils.energy_decomposition( g, gromacscon )
        #Check components
        tolerance = 1e-5
        ok = True
        for key in a_energies.keys():
            diff = np.abs(a_energies[key] - g_energies[key] )
            if diff/np.abs(a_energies[key]) > tolerance:
                ok = False
                print("In testing AMBER to GROMACS conversion, %s energy differs by %.5g, which is more than a fraction %.2g of the total, so conversion appears not to be working properly." % ( key, diff, tolerance) )
        if not ok:
            raise(ValueError("AMBER to GROMACS conversion yields energies which are too different.")) 
def test_system_generator():
    """
    Test SystemGenerator.
    """
    import openmmtools
    from functools import partial

    # Vacuum tests.
    ffxmls = ["amber99sbildn.xml"]
    forcefield_kwargs = {"nonbondedMethod": NoCutoff, "implicitSolvent": None, "constraints": None}
    for testsystem_name in ["AlanineDipeptideVacuum"]:
        constructor = getattr(openmmtools.testsystems, testsystem_name)
        testsystem = constructor()
        f = partial(check_system_generator, ffxmls, forcefield_kwargs, testsystem.topology)
        f.description = "Testing SystemGenerator on %s" % testsystem_name
        yield f
    # Implicit solvent tests.
    ffxmls = ["amber99sbildn.xml", "amber99_obc.xml"]
    forcefield_kwargs = {"nonbondedMethod": NoCutoff, "implicitSolvent": OBC2, "constraints": None}
    for testsystem_name in ["AlanineDipeptideImplicit"]:
        constructor = getattr(openmmtools.testsystems, testsystem_name)
        testsystem = constructor()
        f = partial(check_system_generator, ffxmls, forcefield_kwargs, testsystem.topology)
        f.description = "Testing SystemGenerator on %s" % testsystem_name
        yield f
    # Small molecule tests.
    from openmoltools.forcefield_generators import generateTopologyFromOEMol

    gaff_xml_filename = utils.get_data_filename("parameters/gaff.xml")
    ffxmls = [gaff_xml_filename]
    forcefield_kwargs = {"nonbondedMethod": NoCutoff, "implicitSolvent": None, "constraints": None}
    for name in IUPAC_molecule_names:
        molecule = createOEMolFromIUPAC(name)
        topology = generateTopologyFromOEMol(molecule)
        f = partial(check_system_generator, ffxmls, forcefield_kwargs, topology, use_gaff=True)
        f.description = "Testing SystemGenerator on %s" % name
        yield f
예제 #47
0
def test_checkmol_descriptors():
    input_filename = utils.get_data_filename("chemicals/sustiva/sustiva.mol2")
    utils.get_checkmol_descriptors(input_filename)
예제 #48
0
def test_run_test_molecule():
    molecule_name = "sustiva"
    input_filename = utils.get_data_filename("chemicals/sustiva/sustiva.mol2")
    with utils.enter_temp_directory(
    ):  # Prevents creating tons of GAFF files everywhere.
        utils.test_molecule(molecule_name, input_filename)
예제 #49
0
def test_checkmol_descriptors():
    input_filename = utils.get_data_filename("chemicals/sustiva/sustiva.mol2")
    utils.get_checkmol_descriptors( input_filename )
예제 #50
0
def test_amber_water_mixture():
    water_filename = utils.get_data_filename("chemicals/water/water.mol2")
    etoh_filename = utils.get_data_filename("chemicals/etoh/etoh.mol2")
    sustiva_filename = utils.get_data_filename(
        "chemicals/sustiva/sustiva.mol2")

    with utils.enter_temp_directory(
    ):  # Prevents creating tons of GAFF files everywhere.
        shutil.copy(water_filename, 'c1.mol2')
        shutil.copy(etoh_filename, 'c2.mol2')
        shutil.copy(sustiva_filename, 'c3.mol2')
        water_filename = 'c1.mol2'
        etoh_filename = 'c2.mol2'
        sustiva_filename = 'c3.mol2'
        #Randomize residue names to avoid clashes
        utils.randomize_mol2_residue_names(
            [water_filename, etoh_filename, sustiva_filename])

        trj0, trj1, trj2 = md.load(water_filename), md.load(
            etoh_filename), md.load(sustiva_filename)

        trj_list = [trj0, trj1, trj2]

        box_filename = "./box.pdb"
        box_trj = packmol.pack_box(trj_list, [300, 25, 3])
        box_trj.save(box_filename)

        gaff_mol2_filename0, frcmod_filename0 = amber.run_antechamber(
            "water", water_filename, charge_method=None)
        gaff_mol2_filename1, frcmod_filename1 = amber.run_antechamber(
            "etoh", etoh_filename, charge_method=None)
        gaff_mol2_filename2, frcmod_filename2 = amber.run_antechamber(
            "sustiva", sustiva_filename, charge_method=None)

        mol2_filenames = [
            gaff_mol2_filename0, gaff_mol2_filename1, gaff_mol2_filename2
        ]
        frcmod_filenames = [
            frcmod_filename0, frcmod_filename1, frcmod_filename2
        ]

        prmtop_filename = "./out.prmtop"
        inpcrd_filename = "./out.inpcrd"

        shutil.copy(box_filename, 'renamed.pdb')
        tleap_cmd = amber.build_mixture_prmtop(mol2_filenames,
                                               frcmod_filenames, 'renamed.pdb',
                                               prmtop_filename,
                                               inpcrd_filename)
        print(tleap_cmd)

        #Also do here for case of GAFF water
        tleap_cmd = amber.build_mixture_prmtop(mol2_filenames,
                                               frcmod_filenames,
                                               box_filename,
                                               prmtop_filename,
                                               inpcrd_filename,
                                               water_model=None)
        print(tleap_cmd)

        #Also do here for case of SPC
        tleap_cmd = amber.build_mixture_prmtop(mol2_filenames,
                                               frcmod_filenames,
                                               'renamed.pdb',
                                               prmtop_filename,
                                               inpcrd_filename,
                                               water_model='SPC')
        print(tleap_cmd)
예제 #51
0
def test_run_tleap():
    molecule_name = "sustiva"
    input_filename = utils.get_data_filename("chemicals/sustiva/sustiva.mol2")
    with utils.enter_temp_directory():  # Prevents creating tons of GAFF files everywhere.
        gaff_mol2_filename, frcmod_filename = utils.run_antechamber(molecule_name, input_filename, charge_method=None)
        prmtop, inpcrd = utils.run_tleap(molecule_name, gaff_mol2_filename, frcmod_filename)
예제 #52
0
def test_run_test_molecule():
    molecule_name = "sustiva"
    input_filename = utils.get_data_filename("chemicals/sustiva/sustiva.mol2")
    with utils.enter_temp_directory():  # Prevents creating tons of GAFF files everywhere.
        utils.test_molecule(molecule_name, input_filename)