Beispiel #1
0
def test_topology_precedence():
    """Test to see if topology precedence is properly adhered to.

    This test uses a force field file where bond, angle, and dihedral
    parameters are present with different counts of `type` definitions.
    It checks that:
        1. The parameters with the higher number of `type` definitions
           are assigned (because they are given the highest precedence)
        2. That if multiple definitions exist with the same number of
           `type` definitions, that the convention from OpenMM is followed
           whereby the definitions that occurs earliest in the XML is
           assigned.
    """
    import mbuild as mb
    ethane = mb.load(get_fn('ethane.mol2'))
    ff = Forcefield(forcefield_files=get_fn('ethane-topo-precedence.xml'))
    typed_ethane = ff.apply(ethane)

    assert len([bond for bond in typed_ethane.bonds
                if round(bond.type.req, 2) == 1.15]) == 6
    assert len([bond for bond in typed_ethane.bonds
                if round(bond.type.req, 2) == 1.6]) == 1
    assert len([angle for angle in typed_ethane.angles
                if round(angle.type.theteq, 3) == 120.321]) == 6
    assert len([angle for angle in typed_ethane.angles
                if round(angle.type.theteq, 3) == 97.403]) == 6
    assert len([rb for rb in typed_ethane.rb_torsions
                if round(rb.type.c0, 3) == 0.287]) == 9
Beispiel #2
0
def test_improper_dihedral():
    untyped_benzene = pmd.load_file(get_fn('benzene.mol2'), structure=True)
    ff_improper = Forcefield(forcefield_files=get_fn('improper_dihedral.xml'))
    benzene = ff_improper.apply(untyped_benzene, assert_dihedral_params=False)
    assert len(benzene.dihedrals) == 18
    assert len([dih for dih in benzene.dihedrals if dih.improper]) == 6
    assert len([dih for dih in benzene.dihedrals if not dih.improper]) == 12
Beispiel #3
0
def test_topology_precedence():
    """Test to see if topology precedence is properly adhered to.

    This test uses a force field file where bond, angle, and dihedral
    parameters are present with different counts of `type` definitions.
    It checks that:
        1. The parameters with the higher number of `type` definitions
           are assigned (because they are given the highest precedence)
        2. That if multiple definitions exist with the same number of
           `type` definitions, that the convention from OpenMM is followed
           whereby the definitions that occurs earliest in the XML is
           assigned.
    """
    ethane = mb.load(get_fn('ethane.mol2'))
    ff = Forcefield(forcefield_files=get_fn('ethane-topo-precedence.xml'))
    typed_ethane = ff.apply(ethane)

    assert len([bond for bond in typed_ethane.bonds
                if round(bond.type.req, 2) == 1.15]) == 6
    assert len([bond for bond in typed_ethane.bonds
                if round(bond.type.req, 2) == 1.6]) == 1
    assert len([angle for angle in typed_ethane.angles
                if round(angle.type.theteq, 3) == 120.321]) == 6
    assert len([angle for angle in typed_ethane.angles
                if round(angle.type.theteq, 3) == 97.403]) == 6
    assert len([rb for rb in typed_ethane.rb_torsions
                if round(rb.type.c0, 3) == 0.287]) == 9
Beispiel #4
0
def test_load_files():
    for ff_file in FORCEFIELDS:
        ff1 = Forcefield(forcefield_files=ff_file)
        assert len(ff1._atomTypes) > 0

        ff2 = Forcefield(forcefield_files=ff_file)
        assert len(ff1._atomTypes) == len(ff2._atomTypes)
    def test_allow_empty_def(self):
        import mbuild as mb

        ethane = mb.load(get_fn("ethane.mol2"))
        with pytest.warns(ValidationWarning):
            ff = Forcefield(forcefield_files=get_fn("empty_def.xml"))
        ff.apply(ethane)
    def test_overrides_space(self):
        import mbuild as mb

        ethane = mb.load(get_fn("ethane.mol2"))
        ff = Forcefield(forcefield_files=get_fn("overrides-space.xml"))
        typed_ethane = ff.apply(ethane)
        assert typed_ethane.atoms[0].type == "CT3"
Beispiel #7
0
    def test_nbfix(self, ethane):
        from foyer import Forcefield

        OPLSAA = Forcefield(name="oplsaa")
        structure = OPLSAA.apply(ethane)
        # Add nbfixes
        types = list(set([a.atom_type for a in structure.atoms]))
        types[0].add_nbfix(types[1].name, 1.2, 2.1)
        types[1].add_nbfix(types[0].name, 1.2, 2.1)
        write_lammpsdata(filename="nbfix.lammps", structure=structure)

        checked_section = False
        with open("nbfix.lammps", "r") as fi:
            while not checked_section:
                line = fi.readline()
                if "PairIJ Coeffs" in line:
                    fi.readline()
                    line = fi.readline().partition("#")[0]
                    assert np.allclose(
                        np.asarray(line.split(), dtype=float),
                        [1, 1, 0.066, 3.5],
                    )
                    line = fi.readline().partition("#")[0]
                    assert np.allclose(
                        np.asarray(line.split(), dtype=float),
                        [1, 2, 2.1, 1.06907846],
                    )
                    line = fi.readline().partition("#")[0]
                    assert np.allclose(np.asarray(line.split(), dtype=float),
                                       [2, 2, 0.03, 2.5])
                    line = fi.readline()
                    checked_section = True
                # Break if PairIJ Coeffs is not found
                if "Atoms" in line:
                    break
    def test_write_refs_multiple(self, requests_mock):
        import mbuild as mb

        register_mock_request(
            mocker=requests_mock,
            url="http://api.crossref.org/",
            path="works/10.1021/ja9621760/transform/application/x-bibtex",
            headers={"accept": "application/x-bibtex"},
            text=RESPONSE_BIB_ETHANE_JA962170,
        )
        register_mock_request(
            mocker=requests_mock,
            url="http://api.crossref.org/",
            path="works/10.1021/jp0484579/transform/application/x-bibtex",
            headers={"accept": "application/x-bibtex"},
            text=RESPONSE_BIB_ETHANE_JP0484579,
        )
        mol2 = mb.load(get_fn("ethane.mol2"))
        oplsaa = Forcefield(forcefield_files=get_fn("refs-multi.xml"))
        ethane = oplsaa.apply(mol2, references_file="ethane-multi.bib")
        assert os.path.isfile("ethane-multi.bib")
        with open(get_fn("ethane-multi.bib")) as file1:
            with open("ethane-multi.bib") as file2:
                diff = list(
                    difflib.unified_diff(file1.readlines(),
                                         file2.readlines(),
                                         n=0))
        assert not diff
    def test_save_forcefield_with_same_struct(self):
        from foyer import Forcefield

        from mbuild.formats.lammpsdata import write_lammpsdata

        system = mb.load("C1(=CC=CC=C1)F", smiles=True)

        ff = Forcefield(forcefield_files=[get_fn("gaff_test.xml")])
        struc = ff.apply(
            system,
            assert_angle_params=False,
            assert_dihedral_params=False,
            assert_improper_params=False,
        )
        write_lammpsdata(struc,
                         "charmm_improper.lammps",
                         zero_dihedral_weighting_factor=True)
        for i in range(3):
            xyz = struc.coordinates
            xyz = xyz + np.array([1, 1, 1])
            struc.coordinates = xyz
            write_lammpsdata(
                struc,
                f"charmm_improper{i}.lammps",
                zero_dihedral_weighting_factor=True,
            )
    def test_singleterm_charmm(self):
        from foyer import Forcefield

        from mbuild.formats.lammpsdata import write_lammpsdata

        cmpd = mb.load(get_fn("charmm_dihedral.mol2"))
        for i in cmpd.particles():
            i.name = "_{}".format(i.name)
        structure = cmpd.to_parmed(
            box=cmpd.get_boundingbox(),
            residues=set([p.parent.name for p in cmpd.particles()]),
        )
        ff = Forcefield(
            forcefield_files=[get_fn("charmm_truncated_singleterm.xml")])
        structure = ff.apply(structure, assert_dihedral_params=False)
        write_lammpsdata(structure, "charmm_dihedral_singleterm.lammps")
        out_lammps = open("charmm_dihedral_singleterm.lammps", "r").readlines()
        found_dihedrals = False
        for i, line in enumerate(out_lammps):
            if "Dihedral Coeffs" in line:
                assert "# charmm" in line
                assert "#k, n, phi, weight" in out_lammps[i + 1]
                assert len(out_lammps[i + 2].split("#")[0].split()) == 5
                assert float(
                    out_lammps[i + 2].split("#")[0].split()[4]) == float("1.0")
                found_dihedrals = True
            else:
                pass
        assert found_dihedrals
    def test_save_charmm(self):
        from foyer import Forcefield

        cmpd = mb.load(get_fn("charmm_dihedral.mol2"))
        for i in cmpd.particles():
            i.name = "_{}".format(i.name)
        structure = cmpd.to_parmed(
            box=cmpd.get_boundingbox(),
            residues=set([p.parent.name for p in cmpd.particles()]),
        )
        ff = Forcefield(forcefield_files=[get_fn("charmm_truncated.xml")])
        structure = ff.apply(structure, assert_dihedral_params=False)
        write_lammpsdata(structure, "charmm_dihedral.lammps")
        out_lammps = open("charmm_dihedral.lammps", "r").readlines()
        found_angles = False
        found_dihedrals = False
        for i, line in enumerate(out_lammps):
            if "Angle Coeffs" in line:
                assert "# charmm" in line
                assert (
                    "#\tk(kcal/mol/rad^2)\t\ttheteq(deg)\tk(kcal/mol/angstrom^2)\treq(angstrom)\n"
                    in out_lammps[i + 1])
                assert len(out_lammps[i + 2].split("#")[0].split()) == 5
                found_angles = True
            elif "Dihedral Coeffs" in line:
                assert "# charmm" in line
                assert "#k, n, phi, weight" in out_lammps[i + 1]
                assert len(out_lammps[i + 2].split("#")[0].split()) == 5
                found_dihedrals = True
            else:
                pass
        assert found_angles
        assert found_dihedrals
Beispiel #12
0
    def test_save_charmm(self):
        cmpd = mb.load(get_fn('charmm_dihedral.mol2'))
        for i in cmpd.particles():
            i.name = "_{}".format(i.name)
        structure = cmpd.to_parmed(box=cmpd.boundingbox,
                                    residues=set([p.parent.name for \
                                                 p in cmpd.particles()]))

        from foyer import Forcefield
        ff = Forcefield(forcefield_files=[get_fn('charmm_truncated.xml')])
        structure = ff.apply(structure, assert_dihedral_params=False)

        from mbuild.formats.lammpsdata import write_lammpsdata
        write_lammpsdata(structure, 'charmm_dihedral.lammps')
        out_lammps = open('charmm_dihedral.lammps', 'r').readlines()
        for i, line in enumerate(out_lammps):
            if 'Angle Coeffs' in line:
                assert '# charmm' in line
                assert '#\tk(kcal/mol/rad^2)\t\ttheteq(deg)\tk(kcal/mol/angstrom^2)\treq(angstrom)\n' in out_lammps[
                    i + 1]
                assert len(out_lammps[i + 2].split('#')[0].split()) == 5
            elif 'Dihedral Coeffs' in line:
                assert '# charmm' in line
                assert '#k, n, phi, weight' in out_lammps[i + 1]
                assert len(out_lammps[i + 2].split('#')[0].split()) == 5
            else:
                pass
Beispiel #13
0
    def test_comb_rule(self, mixing_rule):
        import mbuild as mb

        mol2 = mb.load(get_fn("ethane.mol2"))
        oplsaa = Forcefield(name="oplsaa")
        ethane = oplsaa.apply(mol2, combining_rule=mixing_rule)
        assert ethane.combining_rule == mixing_rule
Beispiel #14
0
def test_preserve_resname():
    untyped_ethane = pmd.load_file(get_fn('ethane.mol2'), structure=True)
    untyped_resname = untyped_ethane.residues[0].name
    oplsaa = Forcefield(name='oplsaa')
    typed_ethane = oplsaa.apply(untyped_ethane)
    typed_resname = typed_ethane.residues[0].name
    assert typed_resname == untyped_resname
Beispiel #15
0
    def test_non_zero_charge(self):
        import mbuild as mb

        compound = mb.load("C1=CC=C2C(=C1)C(C3=CC=CC=C3O2)C(=O)O", smiles=True)
        oplsaa = Forcefield(name="oplsaa")
        with pytest.warns(UserWarning):
            oplsaa.apply(compound, assert_dihedral_params=False)
Beispiel #16
0
def test_apply_residues():
    import mbuild as mb
    from mbuild.examples import Ethane
    ethane = Ethane()
    opls = Forcefield(name='oplsaa')
    typed = opls.apply(ethane, residues='CH3')
    assert len([res for res in typed.residues if res.name == 'CH3']) == 2
Beispiel #17
0
def test_preserve_resname():
    untyped_ethane = pmd.load_file(get_fn('ethane.mol2'), structure=True)
    untyped_resname = untyped_ethane.residues[0].name
    oplsaa = Forcefield(name='oplsaa')
    typed_ethane = oplsaa.apply(untyped_ethane)
    typed_resname = typed_ethane.residues[0].name
    assert typed_resname == untyped_resname
Beispiel #18
0
def test_apply_residues():
    import mbuild.recipes
    propane = mbuild.recipes.Alkane(n=3)

    opls = Forcefield(name='oplsaa')
    typed = opls.apply(propane, residues='CH3')
    assert len([res for res in typed.residues if res.name == 'CH3']) == 2
Beispiel #19
0
def test_improper_dihedral():
    untyped_benzene = pmd.load_file(get_fn('benzene.mol2'), structure=True)
    ff_improper = Forcefield(forcefield_files=get_fn('improper_dihedral.xml'))
    benzene = ff_improper.apply(untyped_benzene, assert_dihedral_params=False)
    assert len(benzene.dihedrals) == 18
    assert len([dih for dih in benzene.dihedrals if dih.improper]) == 6
    assert len([dih for dih in benzene.dihedrals if not dih.improper]) == 12
Beispiel #20
0
def test_missing_overrides():
    top = os.path.join(OPLS_TESTFILES_DIR, 'benzene/benzene.top')
    gro = os.path.join(OPLS_TESTFILES_DIR, 'benzene/benzene.gro')
    structure = pmd.load_file(top, xyz=gro)

    forcefield = Forcefield(get_fn('missing_overrides.xml'))
    with pytest.raises(FoyerError):
        forcefield.apply(structure)
Beispiel #21
0
def test_missing_topo_params(ff_filename, kwargs):
    """Test that the user is notified if not all topology parameters are found."""
    ethane = mb.load(get_fn('ethane.mol2'))
    oplsaa_with_typo = Forcefield(forcefield_files=get_fn(ff_filename))
    with pytest.raises(Exception):
        ethane = oplsaa_with_typo.apply(ethane)
    with pytest.warns(UserWarning):
        ethane = oplsaa_with_typo.apply(ethane, **kwargs)
Beispiel #22
0
def test_load_metadata():
    lj_ff = Forcefield(get_fn('lj.xml'))
    assert lj_ff.version == '0.4.1'
    assert lj_ff.name == 'LJ'

    lj_ff = Forcefield(forcefield_files=[get_fn('lj.xml'), get_fn('lj2.xml')])
    assert lj_ff.version == ['0.4.1', '4.8.2']
    assert lj_ff.name == ['LJ', 'JL']
Beispiel #23
0
    def test_apply_residues(self):
        import mbuild.recipes

        propane = mbuild.recipes.Alkane(n=3)

        opls = Forcefield(name="oplsaa")
        typed = opls.apply(propane, residues="CH3")
        assert len([res for res in typed.residues if res.name == "CH3"]) == 2
Beispiel #24
0
def test_missing_overrides():
    top = os.path.join(OPLS_TESTFILES_DIR, 'benzene/benzene.top')
    gro = os.path.join(OPLS_TESTFILES_DIR, 'benzene/benzene.gro')
    structure = pmd.load_file(top, xyz=gro)

    forcefield = Forcefield(get_fn('bad_ff.xml'))
    with pytest.raises(FoyerError):
        forcefield.apply(structure)
Beispiel #25
0
def test_missing_topo_params(ff_filename, kwargs):
    """Test that the user is notified if not all topology parameters are found."""
    ethane = mb.load(get_fn('ethane.mol2'))
    oplsaa_with_typo = Forcefield(forcefield_files=get_fn(ff_filename))
    with pytest.raises(Exception):
        ethane = oplsaa_with_typo.apply(ethane)
    with pytest.warns(UserWarning):
        ethane = oplsaa_with_typo.apply(ethane, **kwargs)
Beispiel #26
0
    def write_lammps(self, filename):

        cgff = Forcefield(forcefield_files='mbuild_ONA/ONA.xml')
        #apply it to the mbuild structure
        test_box_typed = cgff.apply(self, assert_dihedral_params=False)
        #Output a LAMMPS data file
        mb.formats.lammpsdata.write_lammpsdata(test_box_typed,
                                               filename,
                                               atom_style='full')
Beispiel #27
0
def test_load_files():
    ff1 = Forcefield(forcefield_files=FORCEFIELDS)
    assert len(ff1._atomTypes) > 0

    ff2 = Forcefield(forcefield_files=FORCEFIELDS[0])
    assert len(ff1._atomTypes) == len(ff2._atomTypes)

    ff3 = Forcefield(name='oplsaa')
    assert len(ff1._atomTypes) == len(ff3._atomTypes)
Beispiel #28
0
def test_load_files():
    for ff_file in FORCEFIELDS:
        ff1 = Forcefield(forcefield_files=ff_file)
        assert len(ff1._atomTypes) > 0

        ff2 = Forcefield(forcefield_files=ff_file)
        assert len(ff1._atomTypes) == len(ff2._atomTypes)

        ff3 = Forcefield(name=os.path.splitext(os.path.basename(ff_file))[0])
        assert len(ff1._atomTypes) == len(ff3._atomTypes)
    def test_load_xml(self, filename, oplsaa):
        mol = pmd.load_file(get_fn(filename), structure=True)
        if filename == "ethane.mol2":
            ff = Forcefield(get_fn("ethane-multiple.xml"))
        else:
            ff = oplsaa
        typed = ff.apply(mol)
        typed.write_foyer(filename="snippet.xml", forcefield=ff, unique=True)

        generated_ff = Forcefield("snippet.xml")
    def test_load_metadata(self):
        lj_ff = Forcefield(get_fn("lj.xml"))
        assert lj_ff.version == "0.4.1"
        assert lj_ff.name == "LJ"

        lj_ff = Forcefield(
            forcefield_files=[get_fn("lj.xml"),
                              get_fn("lj2.xml")])
        assert lj_ff.version == ["0.4.1", "4.8.2"]
        assert lj_ff.name == ["LJ", "JL"]
        def _create_lammps(ethane, tmp):
            from foyer import Forcefield

            OPLSAA = Forcefield(name="oplsaa")
            structure = OPLSAA.apply(ethane)
            fn = tmpdir_factory.mktemp("data").join("lj.lammps")
            write_lammpsdata(filename=str(fn),
                             structure=structure,
                             unit_style="real")
            return str(fn)
Beispiel #32
0
def convert(correct_structure,
            forcefield_files=['foyer_charmm.xml', 'foyer_water.xml']):
    """ Convert gmx to lmp structure via foyer

    Parameters
    ---------
    correct_structure : str
        filename of the correct structure we are pulling xyz from
    forcefield_files :
        To be passed to foyer

    Notes
    -----
    We are making a 'fake' mbuild compound and then updating the coordinates. 
    This is done to preserve compound hierarchies and residue names
    Note the generation of an extra box according to the correct_structure's
    periodicity. This is because update_coordinates doesn't carry over
    box/periodicity information.
    The fake mbuild compound is then converted to parmed structure and then atomtyped
    It is *necessary* to update how we are making this fakae mbuild compound
    It will help to look at the gmx top file to see the order of the molecules
    Remember to specify `use_atom_name` to false in order for the ffxml to succesfully
    ientify atoms in the mb Compound and pmd Structure
        """
    system = mb.Compound()
    for i in range(64):
        system.add(DSPC.DSPC(use_atom_name=False))
    for i in range(1280):
        system.add(SOL.SOL(use_atom_name=False))
    for i in range(64):
        system.add(DSPC.DSPC(use_atom_name=False))
    for i in range(1280):
        system.add(SOL.SOL(use_atom_name=False))

    system.update_coordinates(correct_structure)
    system_box = mb.Box(lengths=mb.load(correct_structure).periodicity)

    # In order to avoid using smarts, define custom elements in parmed
    # by adding underscores to mb particle names
    for num, i in enumerate(system.particles()):
        i.name = "_{}".format(i.name)

    structure = system.to_parmed(
        box=system_box,
        residues=set([p.parent.name for p in system.particles()]))

    ff = Forcefield(forcefield_files=forcefield_files)
    structure = ff.apply(structure, assert_dihedral_params=False)

    # Because mbuild compounds don't pass charges to parmed structures, need to
    # manuallly set the charges AFTER the force field has been applied
    for i, j in zip(system.particles(), structure.atoms):
        j.charge = i.charge

    write_lammpsdata(structure, correct_structure[:-4] + '.lammpsdata')
Beispiel #33
0
def test_write_refs_multiple():
    mol2 = mb.load(get_fn('ethane.mol2'))
    oplsaa = Forcefield(forcefield_files=get_fn('refs-multi.xml'))
    ethane = oplsaa.apply(mol2, references_file='ethane-multi.bib')
    assert os.path.isfile('ethane-multi.bib')
    with open(get_fn('ethane-multi.bib')) as file1:
        with open('ethane-multi.bib') as file2:
            diff = list(difflib.unified_diff(file1.readlines(),
                                             file2.readlines(),
                                             n=0))
    assert not diff
Beispiel #34
0
def test_write_refs_multiple():
    mol2 = mb.load(get_fn('ethane.mol2'))
    oplsaa = Forcefield(forcefield_files=get_fn('refs-multi.xml'))
    ethane = oplsaa.apply(mol2, references_file='ethane-multi.bib')
    assert os.path.isfile('ethane-multi.bib')
    with open(get_fn('ethane-multi.bib')) as file1:
        with open('ethane-multi.bib') as file2:
            diff = list(
                difflib.unified_diff(file1.readlines(), file2.readlines(),
                                     n=0))
    assert not diff
Beispiel #35
0
def test_write_bad_ref(requests_mock):
    import mbuild as mb
    register_mock_request(mocker=requests_mock,
                          url='http://api.crossref.org/',
                          path='works/10.1021/garbage_bad_44444444jjjj/transform/application/x-bibtex',
                          headers={'accept': 'application/x-bibtex'},
                          status_code=404)
    mol2 = mb.load(get_fn('ethane.mol2'))
    oplsaa = Forcefield(forcefield_files=get_fn('refs-bad.xml'))
    with pytest.warns(UserWarning):
        ethane = oplsaa.apply(mol2, references_file='ethane.bib')
Beispiel #36
0
def test_write_refs():
    import mbuild as mb
    mol2 = mb.load(get_fn('ethane.mol2'))
    oplsaa = Forcefield(name='oplsaa')
    ethane = oplsaa.apply(mol2, references_file='ethane.bib')
    assert os.path.isfile('ethane.bib')
    with open(get_fn('ethane.bib')) as file1:
        with open('ethane.bib') as file2:
            diff = list(
                difflib.unified_diff(file1.readlines(), file2.readlines(),
                                     n=0))
    assert not diff
Beispiel #37
0
def test_from_mbuild():
    mol2 = mb.load(get_fn('ethane.mol2'))
    oplsaa = Forcefield(name='oplsaa')
    ethane = oplsaa.apply(mol2)

    assert sum((1 for at in ethane.atoms if at.type == 'opls_135')) == 2
    assert sum((1 for at in ethane.atoms if at.type == 'opls_140')) == 6
    assert len(ethane.bonds) == 7
    assert all(x.type for x in ethane.bonds)
    assert len(ethane.angles) == 12
    assert all(x.type for x in ethane.angles)
    assert len(ethane.rb_torsions) == 9
    assert all(x.type for x in ethane.dihedrals)
Beispiel #38
0
def test_from_mbuild_customtype():
    mol2 = mb.load(get_fn('ethane_customtype.pdb'))
    customtype_ff = Forcefield(forcefield_files=get_fn('validate_customtypes.xml'))
    ethane = customtype_ff.apply(mol2)

    assert sum((1 for at in ethane.atoms if at.type == 'C3')) == 2
    assert sum((1 for at in ethane.atoms if at.type == 'Hb')) == 6
    assert len(ethane.bonds) == 7
    assert all(x.type for x in ethane.bonds)
    assert len(ethane.angles) == 12
    assert all(x.type for x in ethane.angles)
    assert len(ethane.rb_torsions) == 9
    assert all(x.type for x in ethane.dihedrals)
Beispiel #39
0
    def test_pairs(self, benzene):
        from foyer import Forcefield
        import gsd, gsd.pygsd

        benzene.save(filename='benzene.gsd', forcefield_name='oplsaa')
        gsd_file = gsd.pygsd.GSDFile(open('benzene.gsd', 'rb'))
        frame = gsd.hoomd.HOOMDTrajectory(gsd_file).read_frame(0)

        structure = benzene.to_parmed()
        forcefield = Forcefield(name='oplsaa')
        structure = forcefield.apply(structure)

        # Pairs
        assert len(frame.pairs.types) == 3
        assert frame.pairs.N == 21
Beispiel #40
0
def test_assert_bonds():
    ff = Forcefield(name='trappe-ua')

    derponium = mb.Compound()
    at1 = mb.Particle(name='H')
    at2 = mb.Particle(name='O')
    at3 = mb.Particle(name='_CH4')

    derponium.add([at1, at2, at3])
    derponium.add_bond((at1, at2))
    derponium.add_bond((at2, at3))

    with pytest.raises(Exception):
        ff.apply(derponium)
    thing = ff.apply(derponium, assert_bond_params=False, assert_angle_params=False)
    assert any(b.type is None for b in thing.bonds)
Beispiel #41
0
def test_residue_map():
    ethane = pmd.load_file(get_fn('ethane.mol2'), structure=True)
    ethane *= 2
    oplsaa = Forcefield(name='oplsaa')
    topo, NULL = generate_topology(ethane)
    topo_with = oplsaa.run_atomtyping(topo, use_residue_map=True)
    topo_without = oplsaa.run_atomtyping(topo, use_residue_map=False)
    assert all([a.id for a in topo_with.atoms()][0])
    assert all([a.id for a in topo_without.atoms()][0])
    struct_with = pmd.openmm.load_topology(topo_with, oplsaa.createSystem(topo_with))
    struct_without = pmd.openmm.load_topology(topo_without, oplsaa.createSystem(topo_without))
    for atom_with, atom_without in zip(struct_with.atoms, struct_without.atoms):
        assert atom_with.type == atom_without.type
        b_with = atom_with.bond_partners
        b_without = atom_without.bond_partners
        assert [a0.type for a0 in b_with] == [a1.type for a1 in b_without]
        assert [a0.idx for a0 in b_with] == [a1.idx for a1 in b_without]
Beispiel #42
0
def test_from_parmed():
    mol2 = pmd.load_file(get_fn('ethane.mol2'), structure=True)
    oplsaa = Forcefield(name='oplsaa')
    ethane = oplsaa.apply(mol2)

    assert sum((1 for at in ethane.atoms if at.type == 'opls_135')) == 2
    assert sum((1 for at in ethane.atoms if at.type == 'opls_140')) == 6
    assert len(ethane.bonds) == 7
    assert all(x.type for x in ethane.bonds)
    assert len(ethane.angles) == 12
    assert all(x.type for x in ethane.angles)
    assert len(ethane.rb_torsions) == 9
    assert all(x.type for x in ethane.dihedrals)

    mol2 = pmd.load_file(get_fn('ethane.mol2'), structure=True)
    mol2.box_vectors = [[2, 0, 0], [0, 2, 0], [0, 0, 2]]
    oplsaa = Forcefield(name='oplsaa')
    ethane = oplsaa.apply(mol2)

    assert ethane.box_vectors == mol2.box_vectors
Beispiel #43
0
    def test_nbfix(self, ethane):
        from foyer import Forcefield

        OPLSAA = Forcefield(name='oplsaa')
        structure = OPLSAA.apply(ethane)
        # Add nbfixes
        types = list(set([a.atom_type for a in structure.atoms]))
        types[0].add_nbfix(types[1].name, 1.2, 2.1)
        types[1].add_nbfix(types[0].name, 1.2, 2.1)
        write_lammpsdata(filename='nbfix.lammps', structure=structure)

        checked_section = False
        with open('nbfix.lammps', 'r') as fi:
            while not checked_section:
                line = fi.readline()
                if 'PairIJ Coeffs' in line:
                    fi.readline()
                    fi.readline()
                    fi.readline()
                    line = fi.readline().partition('#')[0]
                    assert np.allclose(
                        np.asarray(line.split(), dtype=float),
                        [1, 1, 0.066, 3.5])
                    line = fi.readline().partition('#')[0]
                    assert np.allclose(
                        np.asarray(line.split(), dtype=float),
                        [1, 2, 2.1, 1.06907846])
                    line = fi.readline().partition('#')[0]
                    assert np.allclose(
                        np.asarray(line.split(), dtype=float),
                        [2, 2, 0.03, 2.5])
                    line = fi.readline()
                    checked_section = True
                # Break if PairIJ Coeffs is not found
                if 'Atoms' in line:
                    break
Beispiel #44
0
def test_overrides_space():
    ethane = mb.load(get_fn('ethane.mol2'))
    ff = Forcefield(forcefield_files=get_fn('overrides-space.xml'))
    typed_ethane = ff.apply(ethane)
    assert typed_ethane.atoms[0].type == 'CT3'
Beispiel #45
0
def test_missing_type_definitions():
    with pytest.raises(FoyerError):
        FF = Forcefield()
        ethane = pmd.load_file(get_fn('ethane.mol2'), structure=True)
        FF.apply(ethane)
Beispiel #46
0
import parmed as pmd
from foyer import Forcefield
from foyer.tests.utils import get_fn


mol2_path = get_fn('ethane.mol2')
untyped_ethane = pmd.load_file(mol2_path, structure=True)
oplsaa = Forcefield(name='oplsaa')
ethane = oplsaa.apply(untyped_ethane)

print("Atoms:")
for atom in ethane.atoms:
    print('Atom {} is typed as {}'.format(atom, atom.type))

print("Bonds:")
for bond in ethane.bonds:
    print('{} '.format(bond))

print("Angles:")
for angle in ethane.angles:
    print('{} '.format(angle))

print("Dihedrals:")
for dihedral in ethane.dihedrals:
    print('{} '.format(dihedral))

# Save to GROMACS
ethane.save('ethane.gro')
ethane.save('ethane.top')

Beispiel #47
0
import parmed as pmd
from foyer import Forcefield
from foyer.tests.utils import get_fn

if __name__ == '__main__':
    mol2_path = get_fn('ethane.mol2')
    untyped_ethane = pmd.load_file(mol2_path, structure=True)
    oplsaa = Forcefield(name='oplsaa')
    ethane = oplsaa.apply(untyped_ethane, references_file='ethane.bib')

    print("Atoms:")
    for atom in ethane.atoms:
        print('Atom {} is typed as {}'.format(atom, atom.type))

    print("Bonds:")
    for bond in ethane.bonds:
        print('{} '.format(bond))

    print("Angles:")
    for angle in ethane.angles:
        print('{} '.format(angle))

    print("Dihedrals:")
    for dihedral in ethane.dihedrals:
        print('{} '.format(dihedral))

    # Save to GROMACS
    ethane.save('ethane.gro')
    ethane.save('ethane.top')

    # Within the `Forcefield.apply` method, an intermediate OpenMM system is
Beispiel #48
0
def test_write_refs():
    mol2 = mb.load(get_fn('ethane.mol2'))
    oplsaa = Forcefield(name='oplsaa')
    ethane = oplsaa.apply(mol2, references_file='ethane.bib')
    assert os.path.isfile('ethane.bib')
Beispiel #49
0
def test_fullerene():
    fullerene = pmd.load_file(get_fn('fullerene.pdb'), structure=True)
    forcefield = Forcefield(get_fn('fullerene.xml'))
    forcefield.apply(fullerene, assert_dihedral_params=False)
Beispiel #50
0
def test_apply_residues():
    from mbuild.examples import Ethane
    ethane = Ethane()
    opls = Forcefield(name='oplsaa')
    typed = opls.apply(ethane, residues='CH3')
    assert len([res for res in typed.residues if res.name == 'CH3']) == 2
Beispiel #51
0
def test_polymer():
    peg100 = mb.load(get_fn('peg100.mol2'))
    forcefield = Forcefield(name='oplsaa')
    forcefield.apply(peg100)
Beispiel #52
0
def test_missing_definition():
    structure = pmd.load_file(get_fn('silly_chemistry.mol2'), structure=True)

    forcefield = Forcefield(get_fn('missing_overrides.xml'))
    with pytest.raises(FoyerError):
        forcefield.apply(structure)
Beispiel #53
0
def test_surface():
    surface = mb.load(get_fn('silica.mol2'))
    forcefield = Forcefield(get_fn('opls-silica.xml'))
    forcefield.apply(surface, assert_bond_params=False)
Beispiel #54
0
    def test_bonded(self, ethane):
        from foyer import Forcefield
        import gsd, gsd.pygsd

        ethane.save(filename='ethane.gsd', forcefield_name='oplsaa')
        gsd_file = gsd.pygsd.GSDFile(open('ethane.gsd', 'rb'))
        frame = gsd.hoomd.HOOMDTrajectory(gsd_file).read_frame(0)

        structure = ethane.to_parmed()
        forcefield = Forcefield(name='oplsaa')
        structure = forcefield.apply(structure)

        # Bonds
        n_bonds = frame.bonds.N
        assert n_bonds == len(structure.bonds)

        expected_unique_bond_types = ['opls_135-opls_135', 'opls_135-opls_140']
        bond_types = frame.bonds.types
        assert np.array_equal(bond_types, expected_unique_bond_types)

        bond_typeids = frame.bonds.typeid
        bond_atoms = frame.bonds.group
        expected_bond_atoms = [[bond.atom1.idx, bond.atom2.idx] 
                               for bond in structure.bonds]
        assert np.array_equal(bond_atoms, expected_bond_atoms)

        bond_type_dict = {('C', 'C') : 0, ('C', 'H') : 1, ('H', 'C') : 1}
        expected_bond_typeids = []
        for bond in structure.bonds:
            expected_bond_typeids.append(bond_type_dict[(bond.atom1.name,
                                                         bond.atom2.name)])
        assert np.array_equal(bond_typeids, expected_bond_typeids)

        # Angles
        n_angles = frame.angles.N
        assert n_angles == len(structure.angles)

        expected_unique_angle_types = ['opls_135-opls_135-opls_140', 
                                       'opls_140-opls_135-opls_140']
        angle_types = frame.angles.types
        assert np.array_equal(angle_types, expected_unique_angle_types)

        angle_typeids = frame.angles.typeid
        angle_atoms = frame.angles.group
        expected_angle_atoms = [[angle.atom1.idx, angle.atom2.idx, angle.atom3.idx] 
                                for angle in structure.angles]
        assert np.array_equal(angle_atoms, expected_angle_atoms)

        angle_type_dict = {('C', 'C', 'H') : 0, ('H', 'C', 'C') : 0, 
                           ('H', 'C', 'H') : 1}
        expected_angle_typeids = []
        for angle in structure.angles:
            expected_angle_typeids.append(angle_type_dict[(angle.atom1.name,
                                                           angle.atom2.name,
                                                           angle.atom3.name)])
        assert np.array_equal(angle_typeids, expected_angle_typeids)

        # Dihedrals
        n_dihedrals = frame.dihedrals.N
        assert n_dihedrals == len(structure.rb_torsions)

        expected_unique_dihedral_types = ['opls_140-opls_135-opls_135-opls_140']
        dihedral_types = frame.dihedrals.types
        assert np.array_equal(dihedral_types, expected_unique_dihedral_types)

        dihedral_typeids = frame.dihedrals.typeid
        dihedral_atoms = frame.dihedrals.group
        expected_dihedral_atoms = []
        for dihedral in structure.rb_torsions:
            expected_dihedral_atoms.append([dihedral.atom1.idx, dihedral.atom2.idx,
                                            dihedral.atom3.idx, dihedral.atom4.idx])
        assert np.array_equal(dihedral_atoms, expected_dihedral_atoms)
        assert np.array_equal(dihedral_typeids, np.zeros(n_dihedrals))