示例#1
0
def test_label_molecules(verbose=False):
    """Test labeling/getting stats on labeling molecules"""
    molecules = read_molecules(
        get_data_filename('molecules/AlkEthOH-tripos.mol2.gz'),
        verbose=verbose)
    ffxml = get_data_filename('forcefield/Frosst_AlkEthOH.ffxml')
    get_molecule_parameterIDs(molecules, ffxml)
    def test_atomtyper(self):
        typetag = 'atomtype'
        atomtypes = AtomTyper.read_typelist(get_data_filename('atomtypes/basetypes.smarts'))
        replacements = AtomTyper.read_typelist(get_data_filename('atomtypes/replacements.smarts'))
        molecules = read_molecules('zinc-subset-tripos.mol2.gz', verbose=False)

        atomtyper = AtomTyper(atomtypes, typetag, replacements=replacements)
        for molecule in molecules:
            atomtyper.assignTypes(molecule)
示例#3
0
    def test_atomtyper(self):
        typetag = 'atomtype'
        atomtypes = AtomTyper.read_typelist(
            get_data_filename('atomtypes/basetypes.smarts'))
        replacements = AtomTyper.read_typelist(
            get_data_filename('atomtypes/replacements.smarts'))
        molecules = read_molecules('zinc-subset-tripos.mol2.gz', verbose=False)

        atomtyper = AtomTyper(atomtypes, typetag, replacements=replacements)
        for molecule in molecules:
            atomtyper.assignTypes(molecule)
示例#4
0
    def __init__(self, *args, **kwargs):
        """
        Initialize TestCase including files used in all smarty tests
        """
        unittest.TestCase.__init__(self, *args, **kwargs)

        self.basetypes = get_data_filename('atomtypes/basetypes.smarts')
        self.alkethoh_answers = get_data_filename(
            'atomtypes/initial_AlkEthOH.smarts')
        self.simple_decs = get_data_filename('atomtypes/decorators.smarts')
        self.combine_decs = get_data_filename(
            'atomtypes/new-decorators.smarts')
        self.replacements = get_data_filename('atomtypes/replacements.smarts')

        # import molecules
        self.mols_zinc = read_molecules('zinc-subset-tripos.mol2.gz',
                                        verbose=False)
        self.mols_zinc_ref = read_molecules('*****@*****.**',
                                            verbose=False)

        self.mols_alkethoh = read_molecules('AlkEthOH_test_filt1_tripos.mol2',
                                            verbose=False)
        self.mols_alkethoh_ref = read_molecules('AlkEthOH_test_filt1_ff.mol2',
                                                verbose=False)
示例#5
0
def test_tip3p_constraints():
    """Test that TIP3P distance costraints are correctly applied."""
    # TIP3P constrained distances.
    tip3p_oh_distance = 0.9572  # angstrom
    tip3p_hoh_angle = 104.52  # angle
    tip3p_hh_distance = tip3p_oh_distance * np.sin(
        np.radians(tip3p_hoh_angle / 2)) * 2
    expected_distances = [
        tip3p_oh_distance, tip3p_oh_distance, tip3p_hh_distance
    ]

    # Load tip3p molecule as OEMol.
    tip3p_mol2_filepath = get_data_filename(
        os.path.join('systems', 'monomers', 'tip3p_water.mol2'))
    tip3p_oemol = read_molecules(tip3p_mol2_filepath, verbose=False)[0]

    # Extract topology and positions.
    tip3p_topology = generateTopologyFromOEMol(tip3p_oemol)
    tip3p_positions = positions_from_oemol(tip3p_oemol)

    # Create tip3p water system.
    ff = ForceField('forcefield/tip3p.ffxml')
    system = ff.createSystem(tip3p_topology, [tip3p_oemol])

    # Run dynamics.
    integrator = openmm.VerletIntegrator(2.0 * unit.femtoseconds)
    context = openmm.Context(system, integrator)
    context.setPositions(tip3p_positions)
    integrator.step(50)

    # Constrained distances are correct.
    state = context.getState(getPositions=True)
    new_positions = state.getPositions(asNumpy=True) / unit.angstroms
    distances = []
    for atom_1, atom_2 in [(0, 1), (0, 2),
                           (1, 2)]:  # pair of atoms O-H1, O-H2, H1-H2
        distances.append(
            np.linalg.norm(new_positions[atom_1] - new_positions[atom_2]))
    err_msg = 'expected distances [O-H1, O-H2, H1-H2]: {} A, new distances: {} A'
    assert np.allclose(expected_distances,
                       distances), err_msg.format(expected_distances,
                                                  distances)
示例#6
0
class TestMiniDrugBank(TestCase):
    basepath = os.path.dirname(__file__)
    tri_file = os.path.abspath(
        os.path.join(basepath, '..', 'MiniDrugBank_tripos.mol2'))
    if not os.path.exists(tri_file):
        raise Exception("%s tripos file not found" % tri_file)
    ff_file = os.path.abspath(
        os.path.join(basepath, '..', 'MiniDrugBank_ff.mol2'))
    if not os.path.exists(ff_file):
        raise Exception("%s parm@frosst file not found" % ff_file)
    tripos_mols = read_molecules(tri_file)
    ff_mols = read_molecules(ff_file)

    def test_repeating_molecules(self):
        """
        Test methods used to create minidrugbank
        """
        smiles = set()
        # check for repeating SMILES
        for idx, ff_mol in enumerate(TestMiniDrugBank.ff_mols):
            # get SMILES information
            ff_smile = oechem.OECreateIsoSmiString(ff_mol)
            tri_mol = TestMiniDrugBank.tripos_mols[idx]
            tri_smile = oechem.OECreateIsoSmiString(tri_mol)

            # SMILES should be the same for the two force fields
            self.assertEqual(
                ff_smile,
                tri_smile,
                msg=
                "SMILES for tripos molecule %s and parm@frosst molecule % should agree and don't"
                % (tri_mol.GetTitle(), ff_mol.GetTitle))

            # there should also be no repeating smiles
            self.assertFalse(
                (ff_smile in smiles),
                msg="Found repeating SMILES string for %s" % ff_mol.GetTitle())

            # add smiles to the list
            smiles.add(ff_smile)

    def test_atom_types(self):
        """
        Check the number of atom types represented hasn't changed
        """
        atom_types = {
            1: [12, set()],
            6: [12, set()],
            7: [8, set()],
            8: [5, set()],
            9: [1, set()],
            15: [1, set()],
            16: [5, set()],
            17: [1, set()],
            35: [1, set()],
            53: [1, set()]
        }

        for mol in TestMiniDrugBank.ff_mols:
            for atom in mol.GetAtoms():
                # get atomic number
                n = atom.GetAtomicNum()
                t = atom.GetType()
                self.assertTrue(n in atom_types,
                                msg="Atomic number %i not in original set" % n)
                atom_types[n][1].add(t)

        # Check that the number of types here match original
        for n, [count, s] in atom_types.items():
            self.assertTrue(
                len(s) == count,
                msg=
                "Current set has %i atom types for atomic number %i, there were %i in the original set"
                % (len(s), n, count))

    def test_pid_types(self):
        """
        Check that the number of smirnoff parameter types hasn't changed
        """
        pids = {
            'HarmonicBondGenerator': [73, set()],
            'HarmonicAngleGenerator': [34, set()],
            'PeriodicTorsionGenerator': [136, set()],
            'NonbondedGenerator': [26, set()]
        }

        ff = ForceField("forcefield/smirnoff99Frosst.ffxml")
        labels = ff.labelMolecules(TestMiniDrugBank.ff_mols, verbose=False)
        # loop through labels from smirnoff
        for force_dict in labels:
            for force, label_list in force_dict.items():
                for (indics, pid, smirks) in label_list:
                    # we don't have current counts on impropers
                    if pid[0] == 'i':
                        continue
                    pids[force][1].add(pid)

        # Check that the number of types here match original
        for force, [count, s] in pids.items():
            self.assertTrue(
                len(s) == count,
                msg=
                "Current set has %i types for the force %s, there were %i in the original set"
                % (len(s), force, count))

    def test_3Dcoordinates(self):
        """
        Check for three dimensional coordinates for every molecule
        """
        for idx, ff_mol in enumerate(TestMiniDrugBank.ff_mols):
            tri_mol = TestMiniDrugBank.tripos_mols[idx]
            self.assertTrue(
                ff_mol.GetDimension() == 3,
                msg="Molecule %s in parm@frosst set doesn't have 3D coordinates"
                % ff_mol.GetTitle())
            self.assertTrue(
                tri_mol.GetDimension() == 3,
                msg="Molecule %s in tripos set doesn't have 3D coordinates" %
                tri_mol.GetTitle())

    def test_check_hydrogens(self):
        """
        Test that explicit hydrogens are already included on all molecules
        In other words the implicit hydrogen count on all atoms is zero
        """
        for mol in TestMiniDrugBank.tripos_mols:
            for a in mol.GetAtoms():
                self.assertTrue(a.GetImplicitHCount() == 0,
                                msg="Found a %i atom with implicit hydrogens" %
                                a.GetAtomicNum())
示例#7
0
def test_tip3p_solvated_molecule_energy():
    """Check the energy of a TIP3P solvated molecule is the same with SMIRNOFF and OpenMM.

    This test makes also use of defining the force field with multiple FFXML files,
    and test the energy of mixture systems (i.e. molecule plus water).

    """

    # TODO remove this function when ParmEd#868 is fixed
    def add_water_bonds(system):
        """Hack to make tip3p waters work with ParmEd Structure.createSystem.

        Bond parameters need to be specified even when constrained.
        """
        k_tip3p = 462750.4 * unit.kilojoule_per_mole / unit.nanometers**2
        length_tip3p = 0.09572 * unit.nanometers
        for force in system.getForces():
            if isinstance(force, openmm.HarmonicBondForce):
                force.addBond(particle1=0,
                              particle2=1,
                              length=length_tip3p,
                              k=k_tip3p)
                force.addBond(particle1=0,
                              particle2=2,
                              length=length_tip3p,
                              k=k_tip3p)

    monomers_dir = get_data_filename(os.path.join('systems', 'monomers'))

    # Load tip3p molecule as OEMol.
    tip3p_mol2_filepath = os.path.join(monomers_dir, 'tip3p_water.mol2')
    tip3p_oemol = read_molecules(tip3p_mol2_filepath, verbose=False)[0]

    # Create OpenMM-parametrized water ParmEd Structure.
    tip3p_openmm_ff = openmm.app.ForceField('tip3p.xml')
    tip3p_topology = generateTopologyFromOEMol(tip3p_oemol)
    tip3p_positions = positions_from_oemol(tip3p_oemol)
    tip3p_openmm_system = tip3p_openmm_ff.createSystem(tip3p_topology)

    # TODO remove this line when ParmEd#868 is fixed
    # Hack to make tip3p waters work with ParmEd Structure.createSystem.
    add_water_bonds(tip3p_openmm_system)

    tip3p_openmm_structure = parmed.openmm.topsystem.load_topology(
        tip3p_topology, tip3p_openmm_system, tip3p_positions)

    # Test case: monomer_filename
    test_cases = [('smirnoff99Frosst.ffxml', 'ethanol.mol2'),
                  ('smirnoff99Frosst.ffxml', 'methane.mol2')]

    for ff_name, molecule_filename in test_cases:
        # Load molecule as OEMol.
        molecule_filepath = os.path.join(monomers_dir, molecule_filename)
        molecule_oemol = read_molecules(molecule_filepath, verbose=False)[0]

        # Create molecule parametrized ParmEd args.
        molecule_ff = ForceField('forcefield/' + ff_name)
        molecule_args = forcefield_utils.create_system_from_molecule(
            molecule_ff, molecule_oemol)
        molecule_structure = parmed.openmm.topsystem.load_topology(
            *molecule_args)
        _, _, molecule_positions = molecule_args

        # Merge molecule and OpenMM TIP3P water.
        structure = tip3p_openmm_structure + molecule_structure
        structure.positions = np.append(tip3p_positions,
                                        molecule_positions,
                                        axis=0)
        system = structure.createSystem()
        energy_openmm = get_energy(system, structure.positions)

        # Test the creation of system with multiple force field files.
        ff = ForceField('forcefield/' + ff_name, 'forcefield/tip3p.ffxml')
        system = ff.createSystem(structure.topology,
                                 [tip3p_oemol, molecule_oemol])

        # TODO remove this line when ParmEd#868 is fixed
        # Add bonds to match ParmEd hack above.
        add_water_bonds(system)

        energy_smirnoff = get_energy(system, structure.positions)

        # The energies of the systems must be the same.
        assert np.isclose(energy_openmm,
                          energy_smirnoff), 'OpenMM: {}, SMIRNOFF: {}'.format(
                              energy_openmm, energy_smirnoff)
示例#8
0
 def test_read_molecules(self):
     molecules = utils.read_molecules('zinc-subset-tripos.mol2.gz',
                                      verbose=False)
示例#9
0
 def test_smirnoff_structure(self):
     """Test function that generates the SMIRNOFF parmed.Structure."""
     molecule = utils.read_molecules('toluene.pdb', verbose=False)[0]
     molecule_structure = utils.generateSMIRNOFFStructure(molecule)
     self.assertIsInstance(molecule_structure, parmed.structure.Structure)
示例#10
0
 def test_positions(self):
     """Test ability to extract and set positions."""
     molecules = utils.read_molecules('zinc-subset-tripos.mol2.gz',
                                      verbose=False)
     positions = utils.extractPositionsFromOEMol(molecules[0])
     utils.setPositionsInOEMol(molecules[0], positions)