示例#1
0
 def _check_written_restarts(self, box):
     # Now try to read them and verify the information (keep in mind that the
     # restart velocities are scaled down then back up, so you'll need to use
     # assertAlmostEqual in this case).
     rst = readparm.Rst7.open(get_fn('testc.rst7', written=True))
     self.assertFalse(rst.hasbox)
     self.assertFalse(rst.hasvels)
     np.testing.assert_equal(rst.coordinates.flatten(), list(range(27)))
     rst = readparm.Rst7.open(get_fn('testcb.rst7', written=True))
     self.assertTrue(rst.hasbox)
     self.assertFalse(rst.hasvels)
     np.testing.assert_equal(rst.coordinates.flatten(), list(range(21)))
     np.testing.assert_equal(rst.box.flatten(), box)
     rst = readparm.Rst7.open(get_fn('testcv.rst7', written=True))
     self.assertTrue(rst.hasvels)
     self.assertFalse(rst.hasbox)
     np.testing.assert_equal(rst.coordinates,
             np.arange(60).reshape(rst.coordinates.shape))
     np.testing.assert_allclose(rst.velocities,
             np.array(list(reversed(range(60)))).reshape(rst.velocities.shape))
     rst = readparm.Rst7.open(get_fn('testcvb.rst7', written=True))
     self.assertTrue(rst.hasvels)
     self.assertTrue(rst.hasbox)
     np.testing.assert_equal(rst.coordinates,
             np.arange(45).reshape(rst.coordinates.shape))
     np.testing.assert_allclose(rst.velocities,
             np.array(list(reversed(range(45)))).reshape(rst.velocities.shape))
     np.testing.assert_equal(rst.box, box)
 def testWriteCharmm27Top(self):
     """ Tests writing a Gromacs topology file with CHARMM 27 FF """
     top = load_file(get_fn('1aki.charmm27.top'))
     GromacsTopologyFile.write(top,
             get_fn('1aki.charmm27.top', written=True))
     top2 = load_file(get_fn('1aki.charmm27.top', written=True))
     self._charmm27_checks(top)
示例#3
0
 def testParmSetParsing(self):
     """ Tests parsing a set of Amber parameter files """
     params = parameters.AmberParameterSet(
             os.path.join(get_fn('parm'), 'parm99.dat'),
             os.path.join(get_fn('parm'), 'frcmod.ff99SB'),
             os.path.join(get_fn('parm'), 'frcmod.parmbsc0'),
     )
     self.assertGreater(_num_unique_types(params.atom_types), 0)
     self.assertGreater(_num_unique_types(params.bond_types), 0)
     self.assertGreater(_num_unique_types(params.angle_types), 0)
     self.assertGreater(_num_unique_types(params.dihedral_types), 0)
     self.assertGreater(_num_unique_types(params.improper_periodic_types), 0)
     # Check that parameters were properly overridden. parm99.dat defines
     # C-N-CT-C torsion as follows:
     #
     # C -N -CT-C    1    0.850       180.000          -2.
     # C -N -CT-C    1    0.800         0.000           1.
     #
     # whereas ff99SB defines that torsion as:
     #
     # C -N -CT-C    1    0.00          0.0            -4.
     # C -N -CT-C    1    0.42          0.0            -3.
     # C -N -CT-C    1    0.27          0.0            -2.
     # C -N -CT-C    1    0.00          0.0             1.
     #
     # Since ff99SB is loaded last, this should be the one that is stored
     self.assertEqual(len(params.dihedral_types[('C','N','CT','C')]), 4)
     self.assertEqual(params.dihedral_types[('C','N','CT','C')][0],
                      topologyobjects.DihedralType(0, 4, 0, 1.2, 2.0))
     self.assertEqual(params.dihedral_types[('C','N','CT','C')][1],
                      topologyobjects.DihedralType(0.42, 3, 0, 1.2, 2.0))
     self.assertEqual(params.dihedral_types[('C','N','CT','C')][2],
                      topologyobjects.DihedralType(0.27, 2, 0, 1.2, 2.0))
     self.assertEqual(params.dihedral_types[('C','N','CT','C')][3],
                      topologyobjects.DihedralType(0, 1, 0, 1.2, 2.0))
    def test_dppc(self):
        """ Tests non-standard Gromacs force fields and nonbonded exceptions """
        # We know what we're doing
        warnings.filterwarnings('ignore', category=GromacsWarning)
        top = load_file(os.path.join(get_fn('12.DPPC'), 'topol.top'),
                        xyz=os.path.join(get_fn('12.DPPC'), 'conf.gro'))
        self.assertEqual(top.combining_rule, 'lorentz')

        # Create the system and context, then calculate the energy decomposition
        system = top.createSystem()
        context = mm.Context(system, mm.VerletIntegrator(0.001), CPU)
        context.setPositions(top.positions)
        energies = energy_decomposition(top, context, nrg=u.kilojoules_per_mole)

        # Compare with Lee-Ping's answers.
        self.assertAlmostEqual(energies['bond'], 0)
        self.assertAlmostEqual(energies['angle'], 1405.7354199, places=4)
        self.assertAlmostEqual(energies['dihedral'], 236.932663255, places=4)
        self.assertAlmostEqual(energies['improper'], 33.201541811, places=4)
        self.assertAlmostEqual(energies['rb_torsion'], 428.0550599, places=4)
        self.assertRelativeEqual(energies['nonbonded'], -16432.8092955, places=4)
        gmxfrc = get_forces_from_xvg(os.path.join(get_fn('12.DPPC'), 'force.xvg'))
        ommfrc = context.getState(getForces=True).getForces().value_in_unit(
                    u.kilojoules_per_mole/u.nanometer)
        zero_ep_frc(ommfrc, top)
        max_diff = get_max_diff(gmxfrc, ommfrc)
        self.assertLess(max_diff, 5)
    def test_round_trip(self):
        """ Test ParmEd -> OpenMM round trip with Gromacs system """
        # Use DPPC to get RB-torsions tested. Also check that it initially fails
        # with the CustomNonbondedForce
        warnings.filterwarnings('ignore', category=GromacsWarning)
        top = load_file(os.path.join(get_fn('12.DPPC'), 'topol.top'),
                        xyz=os.path.join(get_fn('12.DPPC'), 'conf.gro'))
        self.assertEqual(top.combining_rule, 'lorentz')

        system = top.createSystem()
        def bad_system():
            return openmm.load_topology(top.topology, system).createSystem()
        warnings.filterwarnings('ignore', category=OpenMMWarning)
        self.assertTrue(
                openmm.load_topology(top.topology, system).unknown_functional
        )
        self.assertRaises(ParmedError, bad_system)
        for i in range(len(system.getForces())):
            if isinstance(system.getForce(i), mm.CustomNonbondedForce):
                system.removeForce(i)
                break
        system2 = openmm.load_topology(top.topology, system).createSystem()
        con1 = mm.Context(system, mm.VerletIntegrator(0.001), CPU)
        con2 = mm.Context(system2, mm.VerletIntegrator(0.001), CPU)
        con1.setPositions(top.positions)
        con2.setPositions(top.positions)
        ene1 = energy_decomposition(top, con1)
        ene2 = energy_decomposition(top, con2)
        self.assertAlmostEqual(ene1['bond'], ene2['bond'])
        self.assertAlmostEqual(ene1['angle'], ene2['angle'])
        self.assertAlmostEqual(ene1['dihedral'], ene2['dihedral'])
        self.assertAlmostEqual(ene1['improper'], ene2['improper'])
        self.assertAlmostEqual(ene1['rb_torsion'], ene2['rb_torsion'])
        self.assertAlmostEqual(ene1['nonbonded'], ene2['nonbonded'])
    def test_jac(self):
        """ Tests the JAC benchmark Gromacs system nrg and force (no PBC) """
        # Load the top and gro files
        top = load_file(os.path.join(get_fn('07.DHFR-Liquid-NoPBC'), 'topol.top'),
                        xyz=os.path.join(get_fn('07.DHFR-Liquid-NoPBC'), 'conf.gro'))
        self.assertEqual(top.combining_rule, 'lorentz')

        # Create the system and context, then calculate the energy decomposition
        system = top.createSystem()
        context = mm.Context(system, mm.VerletIntegrator(0.001), CPU)
        context.setPositions(top.positions)
        energies = energy_decomposition(top, context, nrg=u.kilojoules_per_mole)

        # Compare with Lee-Ping's answers. Make sure we zero-out forces for
        # virtual sites, since OMM doesn't do this and Gromacs does.
        self.assertAlmostEqual(energies['bond'], 35.142565, places=3)
        self.assertAlmostEqual(energies['angle'], 3735.514669, places=3)
        self.assertAlmostEqual(energies['dihedral'], 7277.741635, delta=0.002)
        self.assertRelativeEqual(energies['nonbonded'], -288718.981405, places=4)
        gmxfrc = get_forces_from_xvg(
                os.path.join(get_fn('07.DHFR-Liquid-NoPBC'), 'force.xvg'))
        ommfrc = context.getState(getForces=True).getForces().value_in_unit(
                    u.kilojoules_per_mole/u.nanometer)
        zero_ep_frc(ommfrc, top)
        max_diff = get_max_diff(gmxfrc, ommfrc)
        self.assertLess(max_diff, 0.5)
    def test_jac_pme(self):
        """ Tests the JAC benchmark Gromacs system nrg and force (PME) """
        # Load the top and gro files
        top = load_file(os.path.join(get_fn('09.DHFR-PME'), 'topol.top'),
                        xyz=os.path.join(get_fn('09.DHFR-PME'), 'conf.gro'))
        self.assertEqual(top.combining_rule, 'lorentz')

        # Create the system and context, then calculate the energy decomposition
        system = top.createSystem(nonbondedMethod=app.PME,
                                  constraints=app.HBonds,
                                  nonbondedCutoff=0.9*u.nanometers,
                                  ewaldErrorTolerance=1.0e-5)
        context = mm.Context(system, mm.VerletIntegrator(0.001), Reference)
        context.setPositions(top.positions)
        energies = energy_decomposition(top, context, nrg=u.kilojoules_per_mole)

        # Compare with Lee-Ping's answers. Make sure we zero-out forces for
        # virtual sites, since OMM doesn't do this and Gromacs does.
        self.assertAlmostEqual(energies['bond'], 1628.54739, places=3)
        self.assertAlmostEqual(energies['angle'], 3604.58751, places=3)
        self.assertAlmostEqual(energies['dihedral'], 6490.00844, delta=0.002)
        self.assertRelativeEqual(energies['nonbonded'], 23616.457584, delta=0.002)
        gmxfrc = get_forces_from_xvg(
                os.path.join(get_fn('09.DHFR-PME'), 'force.xvg'))
        ommfrc = context.getState(getForces=True).getForces().value_in_unit(
                    u.kilojoules_per_mole/u.nanometer)
        zero_ep_frc(ommfrc, top)
        max_diff = get_max_diff(gmxfrc, ommfrc)
        self.assertLess(max_diff, 5)
示例#8
0
def test_component_for_duck_typing():
    view = NGLWidget()
    traj = pt.load(nv.datafiles.PDB)
    view.add_component(get_fn('tz2.pdb'))
    view.add_component(get_fn('tz2_2.pdb.gz'))
    view.add_trajectory(nv.PyTrajTrajectory(traj))
    view.component_0.add_representation('cartoon')
    
    c0 = view[0]
    c1 = view[1]
    assert hasattr(view, 'component_0')
    assert hasattr(view, 'component_1')
    assert hasattr(view, 'trajectory_0')
    assert hasattr(view.trajectory_0, 'n_frames')
    assert hasattr(view.trajectory_0, 'get_coordinates')
    assert hasattr(view.trajectory_0, 'get_structure_string')

    c0.show()
    c0.hide()

    view.remove_component(c0.id)
    assert not hasattr(view, 'component_2')

    # negative indexing
    assert view[-1]._index == c1._index
    def test_small_double_peptide(self):
        """ Test interacting peptides Gromacs system nrg and frc (no PBC) """
        # Load the top and gro files
        top = load_file(os.path.join(get_fn('03.AlaGlu'), 'topol.top'),
                        xyz=os.path.join(get_fn('03.AlaGlu'), 'conf.gro'))
        self.assertEqual(top.combining_rule, 'lorentz')

        # create the system and context, then calculate the energy decomposition
        system = top.createSystem()
        context = mm.Context(system, mm.VerletIntegrator(0.001), CPU)
        context.setPositions(top.positions)
        energies = energy_decomposition(top, context, nrg=u.kilojoules_per_mole)

        # Compare with Lee-Ping's answers. Make sure we zero-out forces for
        # virtual sites, since OMM doesn't do this and Gromacs does.
        self.assertAlmostEqual(energies['bond'], 1.5307999, places=4)
        self.assertAlmostEqual(energies['angle'], 6.5804488, places=4)
        self.assertAlmostEqual(energies['dihedral'], 80.379714, places=4)
        self.assertAlmostEqual(energies['nonbonded'], -275.142487, places=3)
        gmxfrc = get_forces_from_xvg(os.path.join(get_fn('03.AlaGlu'), 'force.xvg'))
        ommfrc = context.getState(getForces=True).getForces().value_in_unit(
                    u.kilojoules_per_mole/u.nanometer)
        zero_ep_frc(ommfrc, top)
        max_diff = get_max_diff(gmxfrc, ommfrc)
        self.assertLess(max_diff, 0.05)
示例#10
0
 def testMol3SingleWriteStruct(self):
     """ Tests writing mol3 file of single-residue Structure """
     mol2 = formats.Mol2File.parse(get_fn('tripos9.mol2'), structure=True)
     formats.Mol2File.write(mol2, get_fn('tripos9struct.mol3', written=True),
                            mol3=True)
     self.assertTrue(diff_files(get_fn('tripos9struct.mol3', written=True),
                                get_saved_fn('tripos9struct.mol3')))
示例#11
0
 def testMol3SingleWrite(self):
     """ Tests writing mol3 file of single ResidueTemplate """
     mol2 = formats.Mol2File.parse(get_fn('tripos9.mol2'))
     formats.Mol2File.write(mol2, get_fn('tripos9.mol3', written=True),
                            mol3=True)
     self.assertTrue(diff_files(get_fn('tripos9.mol3', written=True),
                                get_saved_fn('tripos9.mol3')))
示例#12
0
 def testMol3MultiWriteFromStructure(self):
     """ Tests writing mol3 file of multi residues from Structure """
     mol2 = formats.Mol2File.parse(get_fn('test_multi.mol2'), structure=True)
     formats.Mol2File.write(mol2, get_fn('test_multistruct.mol3', written=True),
                            mol3=True)
     self.assertTrue(diff_files(get_fn('test_multistruct.mol3', written=True),
                                get_saved_fn('test_multistruct.mol3')))
示例#13
0
    def _check_written_mdcrds(self, box):
        # Now try to read them and verify the information
        crd = asciicrd.AmberMdcrd(get_fn('testc.mdcrd', written=True),
                                  15, False, 'r')
        self.assertEqual(crd.title, 'Test file')
        self.assertFalse(crd.hasbox)
        for i in range(crd.frame):
            shape = crd.coordinates[i].shape
            refcrd = np.arange(45) + i
            np.testing.assert_equal(crd.coordinates[i], refcrd.reshape(shape))
        for i, array in enumerate(crd.coordinates):
            refcrd = (np.arange(45) + i).reshape(array.shape)
            np.testing.assert_equal(array, refcrd)
        crd.close()

        crd = asciicrd.AmberMdcrd(get_fn('testcb.mdcrd', written=True),
                                  18, True, 'r')
        self.assertEqual(crd.title, 'Test file')
        self.assertTrue(crd.hasbox)
        for i in range(crd.frame):
            refcrd = (np.arange(54) + i).reshape(crd.coordinates[i].shape)
            np.testing.assert_equal(crd.coordinates[i], refcrd)
            np.testing.assert_equal(crd.box[i], box)
        for i, (coords, mybox) in enumerate(zip(crd.coordinates, crd.box)):
            np.testing.assert_equal(coords, (np.arange(54)+i).reshape(coords.shape))
            np.testing.assert_equal(mybox, box)
示例#14
0
    def testAmberGasParm(self):
        """ Test the AmberParm class with a non-periodic (gas-phase) prmtop """
        parm = readparm.AmberParm(get_fn('trx.prmtop'), get_fn('trx.inpcrd'))
        gasparm = readparm.AmberParm(get_fn('trx.prmtop'))
        gasparm.load_rst7(get_fn('trx.inpcrd'))

        self.assertEqual([a.xx for a in gasparm.atoms],
                         [a.xx for a in parm.atoms])
        self.assertEqual([a.xy for a in gasparm.atoms],
                         [a.xy for a in parm.atoms])
        self.assertEqual([a.xz for a in gasparm.atoms],
                         [a.xz for a in parm.atoms])
        
        # Now run the tests for the prmtop
        self._standard_parm_tests(parm)
        self._extensive_checks(parm)
        self.assertFalse(parm.chamber)
        self.assertFalse(parm.amoeba)
        self.assertRaises(KeyError, lambda: parm.parm_data['BOX_DIMENSIONS'])
        self.assertEqual(parm.ptr('ifbox'), 0)

        # Now check the restart file
        rst = readparm.Rst7.open(get_fn('trx.inpcrd'))
        coords = rst.coordinates
        vels = rst.vels
        for i, atom in enumerate(gasparm.atoms):
            i3 = i * 3
            self.assertEqual(coords[i3  ], atom.xx)
            self.assertEqual(coords[i3+1], atom.xy)
            self.assertEqual(coords[i3+2], atom.xz)
            self.assertEqual(vels[i3  ], atom.vx)
            self.assertEqual(vels[i3+1], atom.vy)
            self.assertEqual(vels[i3+2], atom.vz)
示例#15
0
 def test_box_from_system(self):
     """ Tests loading box from System """
     parm = load_file(get_fn('solv2.parm7'), get_fn('solv2.rst7'))
     system = parm.createSystem(nonbondedMethod=app.PME,
                                nonbondedCutoff=8*u.angstroms)
     top = openmm.load_topology(parm.topology, system)
     np.testing.assert_allclose(parm.box, top.box)
示例#16
0
 def testAdd(self):
     """ Tests combining AmberParm instances """
     parm1 = readparm.AmberParm(get_fn('phenol.prmtop'))
     parm2 = readparm.AmberParm(get_fn('biphenyl.prmtop'))
     comb = parm1 + parm2
     self.assertEqual(len(comb.atoms), len(parm1.atoms) + len(parm2.atoms))
     for a1, a2 in zip(comb.atoms, parm1.atoms + parm2.atoms):
         self.assertEqual(a1.name, a2.name)
         self.assertEqual(a1.mass, a2.mass)
         self.assertEqual(a1.charge, a2.charge)
         self.assertEqual(a1.radii, a2.radii)
     self.assertEqual(len(comb.residues), len(parm1.residues) + len(parm2.residues))
     for r1, r2 in zip(comb.residues, parm1.residues + parm2.residues):
         self.assertEqual(len(r1), len(r2))
         self.assertEqual(r1.name, r2.name)
         self.assertEqual(r1.chain, r2.chain)
     # In-place now
     parm1 += parm2
     self.assertEqual(len(parm1.atoms), len(comb.atoms))
     for a1, a2 in zip(comb.atoms, parm1.atoms):
         self.assertEqual(a1.name, a2.name)
         self.assertEqual(a1.mass, a2.mass)
         self.assertEqual(a1.charge, a2.charge)
         self.assertEqual(a1.radii, a2.radii)
     self.assertEqual(len(parm1.residues), len(comb.residues))
     for r1, r2 in zip(comb.residues, parm1.residues):
         self.assertEqual(len(r1), len(r2))
         self.assertEqual(r1.name, r2.name)
         self.assertEqual(r1.chain, r2.chain)
示例#17
0
    def test_write_xml_parameters_amber_write_unused(self):
        """Test the write_unused argument in writing XML files"""
        params = openmm.OpenMMParameterSet.from_parameterset(
                pmd.amber.AmberParameterSet(get_fn('amino12.lib'),
                os.path.join(get_fn('parm'), 'parm10.dat'),
                os.path.join(get_fn('parm'), 'frcmod.ff14SB'))
        )
        ffxml = StringIO()
        params.write(ffxml)
        ffxml.seek(0)
        self.assertEqual(len(ffxml.readlines()), 2178)
        ffxml = StringIO()
        params.write(ffxml, write_unused=False)
        ffxml.seek(0)
        self.assertEqual(len(ffxml.readlines()), 1646)
        ffxml.seek(0)
        forcefield = app.ForceField(ffxml)

        params = openmm.OpenMMParameterSet.from_parameterset(
                  pmd.amber.AmberParameterSet(get_fn('atomic_ions.lib'),
                  os.path.join(get_fn('parm'), 'frcmod.ionsjc_tip3p'))
        )
        ffxml = StringIO()
        warnings.filterwarnings('ignore', category=exceptions.ParameterWarning)
        params.write(ffxml)
        ffxml.seek(0)
        self.assertEqual(len(ffxml.readlines()), 222)
        ffxml = StringIO()
        params.write(ffxml, write_unused=False)
        ffxml.seek(0)
        self.assertEqual(len(ffxml.readlines()), 57)
        ffxml.seek(0)
        forcefield = app.ForceField(ffxml)
示例#18
0
    def test_write_xml_parameters_charmm_multisite_waters(self):
        """ Test writing XML parameter files from Charmm multisite water parameter files and reading them back into OpenMM ForceField """

        params = openmm.OpenMMParameterSet.from_parameterset(
                pmd.charmm.CharmmParameterSet(get_fn('toppar_water_ions_tip5p.str'))
        )
        ffxml_filename = get_fn('charmm_conv.xml', written=True)
        params.write(ffxml_filename,
                     provenance=dict(
                         OriginalFile='toppar_water_ions_tip5p.str',
                         Reference='MacKerrell'
                     )
        )
        forcefield = app.ForceField(ffxml_filename)

        # Check that water has the right number of bonds
        assert len(params.residues['TIP5'].bonds) == 2, "TIP5P should only have two bonds, but instead has {}".format(params.residues['TIP5'].bonds)

        # Parameterize water box
        pdbfile = app.PDBFile(get_fn('waterbox.pdb'))
        modeller = app.Modeller(pdbfile.topology, pdbfile.positions)
        modeller.addExtraParticles(forcefield)
        system = forcefield.createSystem(modeller.topology, nonbondedMethod=app.NoCutoff)

        # Parameterize water box
        pdbfile = app.PDBFile(get_fn('waterbox-tip3p.pdb'))
        modeller = app.Modeller(pdbfile.topology, pdbfile.positions)
        modeller.addExtraParticles(forcefield)
        system = forcefield.createSystem(modeller.topology, nonbondedMethod=app.PME)
    def test_geometric_combining_rule_energy(self):
        """ Tests converting geom. comb. rule energy from Gromacs to Amber """
        top = load_file(os.path.join(get_fn('05.OPLS'), 'topol.top'),
                        xyz=os.path.join(get_fn('05.OPLS'), 'conf.gro'))
        self.assertEqual(top.combining_rule, 'geometric')
        del top.rb_torsions[:]
        parm = load_file(get_saved_fn('opls.parm7'),
                         xyz=os.path.join(get_fn('05.OPLS'), 'conf.gro'))
        self.assertEqual(parm.combining_rule, 'geometric')
        self.assertFalse(parm.has_NBFIX())

        sysg = top.createSystem()
        sysa = parm.createSystem()

        cong = mm.Context(sysg, mm.VerletIntegrator(0.001), CPU)
        cona = mm.Context(sysa, mm.VerletIntegrator(0.001), CPU)

        cong.setPositions(top.positions)
        cona.setPositions(top.positions)

        self._check_energies(top, cong, parm, cona)

        # Make an NBFIX
        self.assertFalse(parm.has_NBFIX())
        parm.parm_data['LENNARD_JONES_ACOEF'][-4] = 10.0
        self.assertTrue(parm.has_NBFIX())
        parm.createSystem()
示例#20
0
 def testMoleculeCombine(self):
     """ Tests selective molecule combination in Gromacs topology files """
     warnings.filterwarnings('ignore', category=GromacsWarning)
     parm = load_file(os.path.join(get_fn('12.DPPC'), 'topol3.top'))
     fname = get_fn('combined.top', written=True)
     # Make sure that combining non-adjacent molecules fails
     self.assertRaises(ValueError, lambda:
             parm.write(fname, combine=[[1, 3]]))
     self.assertRaises(ValueError, lambda:
             parm.write(fname, combine='joey'))
     self.assertRaises(ValueError, lambda:
             parm.write(fname, combine=[1, 2, 3]))
     self.assertRaises(TypeError, lambda:
             parm.write(fname, combine=1))
     parm.write(fname, combine=[[3, 4], [126, 127, 128, 129, 130]])
     with open(fname, 'r') as f:
         for line in f:
             if line.startswith('[ molecules ]'):
                 break
         molecule_list = []
         for line in f:
             if line[0] == ';': continue
             words = line.split()
             molecule_list.append((words[0], int(words[1])))
     parm2 = load_file(fname)
     self.assertEqual(molecule_list, [('DPPC', 3), ('system1', 1),
                      ('SOL', 121), ('system2', 1), ('SOL', 121)])
     self.assertEqual(len(parm2.atoms), len(parm.atoms))
     self.assertEqual(len(parm2.residues), len(parm2.residues))
     for a1, a2 in zip(parm.atoms, parm2.atoms):
         self._equal_atoms(a1, a2)
     for r1, r2 in zip(parm.residues, parm2.residues):
         self.assertEqual(len(r1), len(r2))
         for a1, a2 in zip(r1, r2):
             self._equal_atoms(a1, a2)
示例#21
0
    def testDistanceBasedMask(self):
        """ Test distance-based mask selections """
        parm = readparm.AmberParm(get_fn('trx.prmtop'), get_fn('trx.inpcrd'))
        # All atoms within 5 A of residue 8
        mask1 = mask.AmberMask(parm, ':8<@5')
        # All atoms more than 10 A away from residue 1
        mask2 = mask.AmberMask(parm, ':1>:10')

        sel = mask1.Selection()
        for i, atom in enumerate(parm.atoms):
            within = 0
            for atom2 in parm.residues[7].atoms:
                dx = atom2.xx - atom.xx
                dy = atom2.xy - atom.xy
                dz = atom2.xz - atom.xz
                if (dx*dx + dy*dy + dz*dz) < 25:
                    within = 1
                    break
            self.assertEqual(sel[i], within)

        sel = mask2.Selection()
        self.assertEqual(sum(sel), 1588)
        for i, res in enumerate(parm.residues):
            within = 0
            for atom in res.atoms:
                for atom2 in parm.residues[0].atoms:
                    dx = atom2.xx - atom.xx
                    dy = atom2.xy - atom.xy
                    dz = atom2.xz - atom.xz
                    if (dx*dx + dy*dy + dz*dz) > 100:
                        within = 1
                        break
                if within: break
            for atom in res.atoms:
                self.assertEqual(sel[atom.idx], within)
 def test_chamber_expanded_exclusions(self):
     """ Tests converting Gromacs to Chamber parm w/ modified exceptions """
     # Now let's modify an exception parameter so that it needs type
     # expansion, and ensure that it is handled correctly
     top = load_file(get_fn('1aki.charmm27.solv.top'),
                     xyz=get_fn('1aki.charmm27.solv.gro'))
     gsystem1 = top.createSystem(nonbondedCutoff=8*u.angstroms,
                                 nonbondedMethod=app.PME)
     gcon1 = mm.Context(gsystem1, mm.VerletIntegrator(1*u.femtosecond),
                        Reference)
     gcon1.setPositions(top.positions)
     top.adjust_types.append(to.NonbondedExceptionType(0, 0, 1))
     top.adjust_types.claim()
     top.adjusts[10].type = top.adjust_types[-1]
     gsystem2 = top.createSystem(nonbondedCutoff=8*u.angstroms,
                                 nonbondedMethod=app.PME)
     gcon2 = mm.Context(gsystem2, mm.VerletIntegrator(1*u.femtosecond),
                        Reference)
     gcon2.setPositions(top.positions)
     e1 = gcon1.getState(getEnergy=True).getPotentialEnergy()
     e1 = e1.value_in_unit(u.kilocalories_per_mole)
     e2 = gcon2.getState(getEnergy=True).getPotentialEnergy()
     e2 = e2.value_in_unit(u.kilocalories_per_mole)
     self.assertGreater(abs(e2 - e1), 1e-2)
     # Convert to chamber now
     parm = amber.ChamberParm.from_structure(top)
     asystem = parm.createSystem(nonbondedCutoff=8*u.angstroms,
                                 nonbondedMethod=app.PME)
     acon = mm.Context(asystem, mm.VerletIntegrator(1*u.femtosecond),
                       Reference)
     acon.setPositions(top.positions)
     e3 = acon.getState(getEnergy=True).getPotentialEnergy()
     e3 = e3.value_in_unit(u.kilocalories_per_mole)
     self.assertLess(abs(e2 - e3), 1e-2)
示例#23
0
    def _check_written_mdcrds(self, box):
        # Now try to read them and verify the information
        crd = asciicrd.AmberMdcrd(get_fn('testc.mdcrd', written=True),
                                  15, False, 'r')
        self.assertEqual(crd.title, 'Test file')
        self.assertFalse(crd.hasbox)
        for i in range(crd.frame):
            for x1, x2 in zip(crd.coordinates(i), [x+i for x in range(45)]):
                self.assertEqual(x1, x2)
        for i, array in enumerate(crd.coordinates()):
            for x1, x2 in zip(array, [x+i for x in range(45)]):
                self.assertEqual(x1, x2)
        crd.close()

        crd = asciicrd.AmberMdcrd(get_fn('testcb.mdcrd', written=True),
                                  18, True, 'r')
        self.assertEqual(crd.title, 'Test file')
        self.assertTrue(crd.hasbox)
        for i in range(crd.frame):
            for x1, x2 in zip(crd.coordinates(i), [x+i for x in range(54)]):
                self.assertEqual(x1, x2)
            for x1, x2 in zip(crd.box(i), box):
                self.assertEqual(x1, x2)
        for i, (coords, mybox) in enumerate(zip(crd.coordinates(), crd.box())):
            for x1, x2 in zip(coords, [x+i for x in range(45)]):
                self.assertEqual(x1, x2)
            for x1, x2 in zip(mybox, box):
                self.assertEqual(x1, x2)
示例#24
0
    def testMdcrd(self):
        """ Test the ASCII trajectory file parsing """
        mdcrd = asciicrd.AmberMdcrd(get_fn('tz2.truncoct.crd'),
                                    natom=5827, hasbox=True, mode='r')
        self.assertEqual(mdcrd.frame, 10)
        if has_numpy():
            import numpy as np
            self.assertIsInstance(mdcrd.coordinates(0), np.ndarray)
            # Hack numpy off so we test that code path, too
            asciicrd.np = None
            asciicrd.array = array
            mdcrdarray = asciicrd.AmberMdcrd(get_fn('tz2.truncoct.crd'),
                                             natom=5827, hasbox=True, mode='r')
            asciicrd.np = np
        else:
            mdcrdarray = mdcrd
        self.assertIsInstance(mdcrdarray.coordinates(0), array)

        if has_numpy():
            runsum = 0
            for i in range(10):
                arr1 = mdcrd.coordinates(i)
                arr2 = mdcrdarray.coordinates(i)
                runsum += arr1.sum()
                self.assertAlmostEqual(arr1.sum(), sum(arr2), places=3)
        else:
            runsum = 0
            for i in range(10):
                runsum += sum(mdcrdarray.coordinates(i))
        self.assertAlmostEqual(runsum, 7049.817, places=3)
示例#25
0
 def testBadFileUsage(self):
     """ Check that illegal file usage results in desired exceptions """
     Restart = asciicrd.AmberAsciiRestart
     Mdcrd = asciicrd.AmberMdcrd
     box = [10, 10, 10, 90, 90, 90]
     rst = Restart(get_fn('testc.rst7', written=True), 'w', natom=9,
                   hasbox=True)
     def assign(obj, stmnt):
         rst = crd = obj
         exec(stmnt)
     try:
         self.assertRaises(ValueError,
                           lambda: assign(rst, 'rst.coordinates=range(20)'))
         self.assertRaises(RuntimeError,
                           lambda: assign(rst, 'rst.box=[10]*3+[90]*3'))
         rst.coordinates = list(range(27))
         rst.box = box
         self.assertRaises(RuntimeError, lambda:
                           assign(rst, 'rst.velocities=list(range(27))'))
     finally:
         rst.close()
     crd = Mdcrd(get_fn('testc.mdcrd', written=True), natom=15, hasbox=True,
                 mode='w', title='Test file')
     s = 'list(range(45))'
     s2 = 'list(range(42))'
     try:
         crd.add_coordinates(eval(s))
         self.assertRaises(RuntimeError,
                           lambda: assign(crd, 'crd.add_coordinates(%s)'%s))
         crd.add_box([10, 10, 10])
         self.assertRaises(ValueError,
                           lambda: assign(crd, 'crd.add_coordinates(%s)'%s2))
     finally:
         crd.close()
示例#26
0
 def _check_written_restarts(self, box):
     # Now try to read them and verify the information (keep in mind that the
     # restart velocities are scaled down then back up, so you'll need to use
     # assertAlmostEqual in this case).
     rst = readparm.Rst7.open(get_fn('testc.rst7', written=True))
     self.assertFalse(rst.hasbox)
     self.assertFalse(rst.hasvels)
     for x1, x2 in zip(rst.coordinates, range(27)):
         self.assertEqual(x1, x2)
     rst = readparm.Rst7.open(get_fn('testcb.rst7', written=True))
     self.assertTrue(rst.hasbox)
     self.assertFalse(rst.hasvels)
     for x1, x2 in zip(rst.coordinates, range(21)):
         self.assertEqual(x1, x2)
     for x1, x2 in zip(rst.box, box):
         self.assertEqual(x1, x2)
     rst = readparm.Rst7.open(get_fn('testcv.rst7', written=True))
     self.assertTrue(rst.hasvels)
     self.assertFalse(rst.hasbox)
     for x1, x2 in zip(rst.coordinates, range(60)):
         self.assertEqual(x1, x2)
     for x1, x2 in zip(rst.vels, reversed(range(60))):
         self.assertAlmostEqual(x1, x2, places=5)
     rst = readparm.Rst7.open(get_fn('testcvb.rst7', written=True))
     self.assertTrue(rst.hasvels)
     self.assertTrue(rst.hasbox)
     for x1, x2 in zip(rst.coordinates, range(45)):
         self.assertEqual(x1, x2)
     for x1, x2 in zip(rst.vels, reversed(range(45))):
         self.assertAlmostEqual(x1, x2, places=5)
     for x1, x2 in zip(rst.box, box):
         self.assertEqual(x1, x2)
示例#27
0
 def testAmberMdcrdNumpy(self):
     """ Test writing ASCII trajectory file passing numpy arrays """
     import numpy as np
     box = np.asarray([15, 15, 15])
     Mdcrd = asciicrd.AmberMdcrd
     crd = Mdcrd(get_fn('testc.mdcrd', written=True), natom=15, hasbox=False,
                 mode='w', title='Test file')
     coorddata = np.arange(45).reshape((15,3))
     crd.add_coordinates(coorddata)
     crd.add_coordinates(coorddata+1)
     crd.add_coordinates(coorddata+2)
     crd.add_coordinates(coorddata+3)
     crd.add_coordinates(coorddata+4)
     crd.close()
     crd = Mdcrd(get_fn('testcb.mdcrd', written=True), natom=18, hasbox=True,
                 mode='w', title='Test file')
     coorddata = np.arange(54).reshape((18,3))
     crd.add_coordinates(coorddata)
     crd.add_box(box)
     crd.add_coordinates(coorddata+1)
     crd.add_box(box)
     crd.add_coordinates(coorddata+2)
     crd.add_box(box)
     crd.add_coordinates(coorddata+3)
     crd.add_box(box)
     crd.add_coordinates(coorddata+4)
     crd.add_box(box)
     crd.close()
     self._check_written_mdcrds(box)
示例#28
0
 def testAmberMdcrd(self):
     """ Test writing ASCII trajectory file """
     box = [15, 15, 15]
     Mdcrd = asciicrd.AmberMdcrd
     crd = Mdcrd(get_fn('testc.mdcrd', written=True), natom=15, hasbox=False,
                 mode='w', title='Test file')
     crd.add_coordinates(list(range(45)))
     crd.add_coordinates([x+1 for x in range(45)])
     crd.add_coordinates([x+2 for x in range(45)])
     crd.add_coordinates([x+3 for x in range(45)])
     crd.add_coordinates([x+4 for x in range(45)])
     crd.close()
     crd = Mdcrd(get_fn('testcb.mdcrd', written=True), natom=18, hasbox=True,
                 mode='w', title='Test file')
     crd.add_coordinates(list(range(54)))
     crd.add_box(box)
     crd.add_coordinates([x+1 for x in range(54)])
     crd.add_box(box)                          
     crd.add_coordinates([x+2 for x in range(54)])
     crd.add_box(box)                          
     crd.add_coordinates([x+3 for x in range(54)])
     crd.add_box(box)                          
     crd.add_coordinates([x+4 for x in range(54)])
     crd.add_box(box)
     crd.close()
     self._check_written_mdcrds(box)
示例#29
0
 def tearDown(self):
     try:
         for f in os.listdir(get_fn('writes')):
             os.unlink(get_fn(f, written=True))
         os.rmdir(get_fn('writes'))
     except OSError:
         pass
示例#30
0
 def setUp(self):
     self.lfh=sys.stderr
     self.verbose=False
     self.pathPdbxDataFile = get_fn("1kip.cif")
     self.pathOutputFile = get_fn("testOutputDataFile.cif", written=True)
     if not os.path.exists(get_fn('writes')):
         os.makedirs(get_fn('writes'))
示例#31
0
def test_load_data():
    view = nv.show_pytraj(pt.datafiles.load_tz2())

    # load blob with ext
    blob = open(nv.datafiles.PDB).read()
    view._load_data(blob, ext='pdb')

    # raise if passing blob but does not provide ext
    with pytest.raises(ValueError):
        view._load_data(blob)

    # raise if passing dummy name
    with pytest.raises(NameError):
        view._load_data(hahahaha)

    # load PyTrajectory
    t0 = nv.PyTrajTrajectory(pt.datafiles.load_ala3())
    view._load_data(t0)

    # load current folder
    view._load_data(get_fn('tz2.pdb'))
示例#32
0
    def testCharmmPSFPandas(self):
        """ Tests creating a pandas DataFrame from a CharmmPsfFile """
        parm = load_file(get_fn('ala_ala_ala.psf'))
        df = parm.to_dataframe()
        self.assertEqual(df.shape[0], len(parm.atoms))
        for i, r1 in df.iterrows():
            self.assertEqual(r1.charge, parm.atoms[i].charge)
            self.assertEqual(r1['name'], parm.atoms[i].name)
            self.assertEqual(r1.radii, parm.atoms[i].radii)
            self.assertEqual(r1.screen, parm.atoms[i].screen)
            self.assertEqual(r1.type, parm.atoms[i].type)
            self.assertEqual(r1.occupancy, parm.atoms[i].occupancy)
            self.assertEqual(r1.bfactor, parm.atoms[i].bfactor)
            self.assertEqual(r1.altloc, parm.atoms[i].altloc)
            self.assertEqual(r1.rmin, parm.atoms[i].rmin)
            self.assertEqual(r1.epsilon, parm.atoms[i].epsilon)
            self.assertEqual(r1.rmin_14, parm.atoms[i].rmin_14)
            self.assertEqual(r1.epsilon_14, parm.atoms[i].epsilon_14)
            self.assertEqual(r1.resname, parm.atoms[i].residue.name)
            self.assertEqual(r1.resid, parm.atoms[i].residue.idx)
            self.assertEqual(r1.resnum, parm.atoms[i].residue.number)
            self.assertEqual(r1.chain, parm.atoms[i].residue.chain)
            self.assertEqual(r1.join, parm.atoms[i].join)
            self.assertEqual(r1.nb_idx, parm.atoms[i].nb_idx)
            self.assertEqual(r1.segid, parm.atoms[i].segid)

        self.assertNotIn('xx', df)
        self.assertNotIn('xy', df)
        self.assertNotIn('xz', df)
        self.assertNotIn('vx', df)
        self.assertNotIn('vy', df)
        self.assertNotIn('vz', df)
        self.assertNotIn('type_idx', df)
        self.assertNotIn('class_idx', df)
        for key in df.keys():
            self.assertFalse(key.startswith('multipole'))
        self.assertNotIn('polarizability', df)
        self.assertNotIn('vdw_parent', df)
示例#33
0
 def testBadNetCDFFiles(self):
     """ Tests error checking for bad usage of NetCDF files """
     self.assertRaises(
         ValueError,
         lambda: NetCDFRestart.open_new(get_fn('test.ncrst', written=True),
                                        natom=10,
                                        box=True,
                                        vels=True,
                                        remd='Temperature'))
     self.assertRaises(
         ValueError,
         lambda: NetCDFRestart.open_new(get_fn('test.ncrst', written=True),
                                        natom=10,
                                        box=True,
                                        vels=True,
                                        remd='Multi'))
     self.assertRaises(
         ValueError,
         lambda: NetCDFRestart.open_new(get_fn('test.ncrst', written=True),
                                        natom=10,
                                        box=True,
                                        vels=True,
                                        remd='Multi',
                                        remd_dimtypes=[1, 3, 2]))
     self.assertRaises(
         ValueError,
         lambda: NetCDFRestart.open_new(get_fn('test.ncrst', written=True),
                                        natom=10,
                                        box=True,
                                        vels=True,
                                        remd='Illegal'))
     self.assertRaises(
         ValueError,
         lambda: NetCDFTraj.open_new(get_fn('test.nc', written=True),
                                     natom=10,
                                     box=True,
                                     vels=False,
                                     remd='Multidim'))
     self.assertRaises(
         ValueError,
         lambda: NetCDFTraj.open_new(get_fn('test.nc', written=True),
                                     natom=10,
                                     box=True,
                                     vels=False,
                                     remd='Illegal'))
示例#34
0
def test_coordinates_meta():
    from mdtraj.testing import get_fn
    fn, tn = [
        get_fn('frame0.pdb'),
    ] * 2
    trajs = [pt.load(fn, tn), md.load(fn, top=tn), pmd.load_file(tn, fn)]

    N_FRAMES = trajs[0].n_frames

    from MDAnalysis import Universe
    u = Universe(tn, fn)
    trajs.append(Universe(tn, fn))

    views = [
        nv.show_pytraj(trajs[0]), nv.show_mdtraj(trajs[1]),
        nv.show_parmed(trajs[2])
    ]
    views.append(nv.show_mdanalysis(trajs[3]))

    for index, (view, traj) in enumerate(zip(views, trajs)):
        view.frame = 3

        assert view._trajlist[0].n_frames == N_FRAMES
示例#35
0
def test_mutation():
    # mol2
    pdb_fn = get_fn('2igd/2igd.pdb')
    pdb_out = 'out.pdb'

    # no whitespace
    command = [
        'pdb4amber', '-i', pdb_fn, '-o', pdb_out, '-m', '1-ALA,2-ALA,3-ALA'
    ]

    with tempfolder():
        subprocess.check_call(command)
        parm = pmd.load_file(pdb_out)
        assert set(res.name for res in parm.residues[:3]) == {"ALA"}

    # with whitespace
    command = [
        'pdb4amber', '-i', pdb_fn, '-o', pdb_out, '-m', '1-ALA, 2-ALA, 3-ALA'
    ]

    with tempfolder():
        subprocess.check_call(command)
        parm = pmd.load_file(pdb_out)
        assert set(res.name for res in parm.residues[:3]) == {"ALA"}
    def test_write_xml_parameters_charmm(self):
        """ Test writing XML parameter files from Charmm parameter files and reading them back into OpenMM ForceField """

        params = openmm.OpenMMParameterSet.from_parameterset(
            pmd.charmm.CharmmParameterSet(get_fn('par_all36_prot.prm'),
                                          get_fn('top_all36_prot.rtf'),
                                          get_fn('toppar_water_ions.str')))
        ffxml_filename = get_fn('charmm_conv.xml', written=True)
        params.write(ffxml_filename,
                     provenance=dict(
                         OriginalFile='par_all36_prot.prm, top_all36_prot.rtf',
                         Reference='MacKerrell'))
        forcefield = app.ForceField(ffxml_filename)
        # Parameterize alanine tripeptide in vacuum
        pdbfile = app.PDBFile(get_fn('ala_ala_ala.pdb'))
        system = forcefield.createSystem(pdbfile.topology,
                                         nonbondedMethod=app.NoCutoff)
        # Parameterize ACE-NME in water
        pdbfile = app.PDBFile(get_fn('2igd_924wat.pdb'))
        system = forcefield.createSystem(pdbfile.topology,
                                         nonbondedMethod=app.PME)
示例#37
0
    def test_write_xml_parameters_methanol_ions_energy(self):
        """ Test writing XML parameter files from Charmm parameter files, reading them back into OpenMM ForceField, and computing energy of methanol and NaCl """

        params = openmm.OpenMMParameterSet.from_parameterset(
            pmd.charmm.CharmmParameterSet(
                get_fn('par_all36_cgenff.prm'), get_fn('top_all36_cgenff.rtf'),
                get_fn('toppar_water_ions.str'
                       ))  # WARNING: contains duplicate water templates
        )
        del params.residues[
            'TP3M']  # Delete to avoid duplicate water template topologies
        ffxml_filename = get_fn('charmm_conv.xml', written=True)
        params.write(
            ffxml_filename,
            provenance=dict(
                OriginalFile=
                'par_all36_cgenff.prm, top_all36_cgenff.rtf, toppar_water_ions.str',
                Reference='MacKerrell'))
        forcefield = app.ForceField(ffxml_filename)
        # Parameterize methanol and ions in vacuum
        pdbfile = app.PDBFile(get_fn('methanol_ions.pdb'))
        system = forcefield.createSystem(pdbfile.topology,
                                         nonbondedMethod=app.NoCutoff)
        integrator = mm.VerletIntegrator(1.0 * u.femtoseconds)
        context = mm.Context(system, integrator, CPU)
        context.setPositions(pdbfile.positions)
        ffxml_potential = context.getState(
            getEnergy=True).getPotentialEnergy() / u.kilocalories_per_mole
        del context, integrator
        # Compute energy via ParmEd reader
        psf = CharmmPsfFile(get_fn('methanol_ions.psf'))
        system = psf.createSystem(params)
        integrator = mm.VerletIntegrator(1.0 * u.femtoseconds)
        context = mm.Context(system, integrator, CPU)
        context.setPositions(pdbfile.positions)
        parmed_potential = context.getState(
            getEnergy=True).getPotentialEnergy() / u.kilocalories_per_mole
        del context, integrator
        # Ensure potentials are almost equal
        self.assertAlmostEqual(ffxml_potential, parmed_potential)
示例#38
0
    def test_write_xml_parameters_amber_write_unused(self):
        """Test the write_unused argument in writing XML files"""
        params = openmm.OpenMMParameterSet.from_parameterset(
            pmd.amber.AmberParameterSet(
                get_fn('amino12.lib'),
                os.path.join(get_fn('parm'), 'parm10.dat'),
                os.path.join(get_fn('parm'), 'frcmod.ff14SB')))
        ffxml = StringIO()
        params.write(ffxml)
        ffxml.seek(0)
        self.assertEqual(len(ffxml.readlines()), 2179)
        ffxml = StringIO()
        params.write(ffxml, write_unused=False)
        ffxml.seek(0)
        self.assertEqual(len(ffxml.readlines()), 1647)
        ffxml.seek(0)
        forcefield = app.ForceField(ffxml)

        params = openmm.OpenMMParameterSet.from_parameterset(
            pmd.amber.AmberParameterSet(
                get_fn('atomic_ions.lib'),
                os.path.join(get_fn('parm'), 'frcmod.ionsjc_tip3p')))
        ffxml = StringIO()
        warnings.filterwarnings('ignore', category=exceptions.ParameterWarning)
        params.write(ffxml, write_unused=True)
        ffxml.seek(0)
        self.assertEqual(len(ffxml.readlines()), 222)
        ffxml = StringIO()
        params.write(ffxml, write_unused=False)
        ffxml.seek(0)
        self.assertEqual(len(ffxml.readlines()), 57)
        ffxml.seek(0)

        forcefield = app.ForceField(ffxml)

        # Load TIP3P water box to ensure there are no duplicate ion parameters
        pdbfile = app.PDBFile(get_fn('ionsjc.pdb'))
        system = forcefield.createSystem(pdbfile.topology)
示例#39
0
    def test_write_xml_parameters_charmm(self):
        """ Test writing XML parameter files from Charmm parameter files and reading them back into OpenMM ForceField """

        params = openmm.OpenMMParameterSet.from_parameterset(
            pmd.charmm.CharmmParameterSet(
                get_fn('par_all36_prot.prm'), get_fn('top_all36_prot.rtf'),
                get_fn('toppar_water_ions.str'
                       ))  # WARNING: contains duplicate water templates
        )

        # Check that patch ACE remains but duplicate patches ACED, ACP, ACPD
        assert 'ACE' in params.patches, "Patch ACE was expected to be retained, but is missing"
        for name in ['ACED', 'ACP', 'ACPD']:
            assert name not in params.patches, "Duplicate patch {} was expected to be pruned, but is present".format(
                name)

        del params.residues[
            'TP3M']  # Delete to avoid duplicate water template topologies
        ffxml_filename = get_fn('charmm_conv.xml', written=True)
        params.write(ffxml_filename,
                     provenance=dict(
                         OriginalFile='par_all36_prot.prm, top_all36_prot.rtf',
                         Reference='MacKerrell'))
        forcefield = app.ForceField(ffxml_filename)

        # Check that water has the right number of bonds
        assert len(params.residues['TIP3'].bonds
                   ) == 2, "TIP3P should only have two bonds"

        # Parameterize alanine tripeptide in vacuum
        pdbfile = app.PDBFile(get_fn('ala_ala_ala.pdb'))
        system = forcefield.createSystem(pdbfile.topology,
                                         nonbondedMethod=app.NoCutoff)
        # Parameterize ACE-NME in water
        pdbfile = app.PDBFile(get_fn('2igd_924wat.pdb'))
        system = forcefield.createSystem(pdbfile.topology,
                                         nonbondedMethod=app.PME)
示例#40
0
    def testMask(self):
        """ Test the Amber mask parser """
        parm = readparm.AmberParm(get_fn('trx.prmtop'))
        mask_res1 = mask.AmberMask(parm, ':1')
        mask_resala = mask.AmberMask(parm, ':ALA')
        mask_atname = mask.AmberMask(parm, '@CA')
        mask_resat = mask.AmberMask(parm, ':ALA@CA')
        mask_attyp = mask.AmberMask(parm, '@%CT')

        # Check all of the masks
        self.assertEqual(sum(mask_res1.Selection()), 13)
        for idx in mask_res1.Selected():
            self.assertEqual(parm.atoms[idx].residue.idx, 0)
        self.assertEqual(list(range(13)), list(mask_res1.Selected()))
        sel = mask_res1.Selection()
        for atom in parm.atoms:
            if atom.residue.idx == 0:
                self.assertEqual(sel[atom.idx], 1)
            else:
                self.assertEqual(sel[atom.idx], 0)

        self.assertEqual(sum(mask_resala.Selection()), 121)
        for idx in mask_resala.Selected():
            self.assertEqual(parm.atoms[idx].residue.name, 'ALA')
        sel = mask_resala.Selection()
        for atom in parm.atoms:
            if atom.residue.name == 'ALA':
                self.assertEqual(sel[atom.idx], 1)
            else:
                self.assertEqual(sel[atom.idx], 0)

        self.assertEqual(sum(mask_atname.Selection()), 108)
        for idx in mask_atname.Selected():
            self.assertEqual(parm.atoms[idx].name, 'CA')
        sel = mask_atname.Selection()
        for atom in parm.atoms:
            if atom.name == 'CA':
                self.assertEqual(sel[atom.idx], 1)
            else:
                self.assertEqual(sel[atom.idx], 0)

        self.assertEqual(sum(mask_resat.Selection()), 12)
        for idx in mask_resat.Selected():
            self.assertEqual(parm.atoms[idx].name, 'CA')
            self.assertEqual(parm.atoms[idx].residue.name, 'ALA')
        sel = mask_resat.Selection()
        for atom in parm.atoms:
            if atom.residue.name == 'ALA' and atom.name == 'CA':
                self.assertEqual(sel[atom.idx], 1)
            else:
                self.assertEqual(sel[atom.idx], 0)

        self.assertEqual(sum(mask_attyp.Selection()), 341)
        for idx in mask_attyp.Selected():
            self.assertEqual(parm.atoms[idx].type, 'CT')
        sel = mask_attyp.Selection()
        for atom in parm.atoms:
            if atom.type == 'CT':
                self.assertEqual(sel[atom.idx], 1)
            else:
                self.assertEqual(sel[atom.idx], 0)
示例#41
0
 def test_deserialize_system(self):
     """ Tests automatic deserialization of a System XML file """
     system = openmm.XmlFile.parse(get_fn('system_974wat.xml'))
     self.assertIsInstance(system, mm.System)
     self.assertEqual(system.getNumParticles(), 6638)
示例#42
0
    def test_write_xml_parameters(self):
        """ Test writing XML parameters loaded from Amber files """
        leaprc = StringIO("""\
logFile leap.log
#
# ----- leaprc for loading the ff14SB force field
# ----- NOTE: this is designed for PDB format 3!
#    Uses frcmod.ff14SB for proteins; ff99bsc0 for DNA; ff99bsc0_chiOL3 for RNA
#
#	load atom type hybridizations
#
addAtomTypes {
	{ "H"   "H" "sp3" }
	{ "HO"  "H" "sp3" }
	{ "HS"  "H" "sp3" }
	{ "H1"  "H" "sp3" }
	{ "H2"  "H" "sp3" }
	{ "H3"  "H" "sp3" }
	{ "H4"  "H" "sp3" }
	{ "H5"  "H" "sp3" }
	{ "HW"  "H" "sp3" }
	{ "HC"  "H" "sp3" }
	{ "HA"  "H" "sp3" }
	{ "HP"  "H" "sp3" }
	{ "HZ"  "H" "sp3" }
	{ "OH"  "O" "sp3" }
	{ "OS"  "O" "sp3" }
	{ "O"   "O" "sp2" }
	{ "O2"  "O" "sp2" }
	{ "OP"  "O" "sp2" }
	{ "OW"  "O" "sp3" }
	{ "CT"  "C" "sp3" }
	{ "CX"  "C" "sp3" }
	{ "C8"  "C" "sp3" }
	{ "2C"  "C" "sp3" }
	{ "3C"  "C" "sp3" }
	{ "CH"  "C" "sp3" }
	{ "CS"  "C" "sp2" }
	{ "C"   "C" "sp2" }
	{ "CO"   "C" "sp2" }
	{ "C*"  "C" "sp2" }
	{ "CA"  "C" "sp2" }
	{ "CB"  "C" "sp2" }
	{ "CC"  "C" "sp2" }
	{ "CN"  "C" "sp2" }
	{ "CM"  "C" "sp2" }
	{ "CK"  "C" "sp2" }
	{ "CQ"  "C" "sp2" }
	{ "CD"  "C" "sp2" }
	{ "C5"  "C" "sp2" }
	{ "C4"  "C" "sp2" }
	{ "CP"  "C" "sp2" }
	{ "CI"  "C" "sp3" }
	{ "CJ"  "C" "sp2" }
	{ "CW"  "C" "sp2" }
	{ "CV"  "C" "sp2" }
	{ "CR"  "C" "sp2" }
	{ "CA"  "C" "sp2" }
	{ "CY"  "C" "sp2" }
	{ "C0"  "Ca" "sp3" }
	{ "MG"  "Mg" "sp3" }
	{ "N"   "N" "sp2" }
	{ "NA"  "N" "sp2" }
	{ "N2"  "N" "sp2" }
	{ "N*"  "N" "sp2" }
	{ "NP"  "N" "sp2" }
	{ "NQ"  "N" "sp2" }
	{ "NB"  "N" "sp2" }
	{ "NC"  "N" "sp2" }
	{ "NT"  "N" "sp3" }
	{ "NY"  "N" "sp2" }
	{ "N3"  "N" "sp3" }
	{ "S"   "S" "sp3" }
	{ "SH"  "S" "sp3" }
	{ "P"   "P" "sp3" }
	{ "LP"  ""  "sp3" }
	{ "EP"  ""  "sp3" }
	{ "F"   "F" "sp3" }
	{ "Cl"  "Cl" "sp3" }
	{ "Br"  "Br" "sp3" }
	{ "I"   "I"  "sp3" }
	{ "F-"   "F" "sp3" }
	{ "Cl-"  "Cl" "sp3" }
	{ "Br-"  "Br" "sp3" }
	{ "I-"   "I"  "sp3" }
	{ "Li+"  "Li"  "sp3" }
	{ "Na+"  "Na"  "sp3" }
	{ "K+"  "K"  "sp3" }
	{ "Rb+"  "Rb"  "sp3" }
	{ "Cs+"  "Cs"  "sp3" }
	{ "Mg+"  "Mg"  "sp3" }
# glycam
	{ "OG"  "O" "sp3" }
	{ "OL"  "O" "sp3" }
	{ "AC"  "C" "sp3" }
	{ "EC"  "C" "sp3" }
}
#
#	Load the main parameter set.
#
parm10 = loadamberparams parm10.dat
frcmod14SB = loadamberparams frcmod.ff14SB
#
#	Load main chain and terminating amino acid libraries, nucleic acids
#
loadOff amino12.lib
loadOff aminoct12.lib
loadOff aminont12.lib
loadOff nucleic12.lib
#
#       Load water and ions
#
#loadOff atomic_ions.lib
#loadOff solvents.lib
#HOH = TP3
#WAT = TP3

#
#	Define the PDB name map for the amino acids and nucleic acids
#
addPdbResMap {
  { 0 "HYP" "NHYP" } { 1 "HYP" "CHYP" }
  { 0 "ALA" "NALA" } { 1 "ALA" "CALA" }
  { 0 "ARG" "NARG" } { 1 "ARG" "CARG" }
  { 0 "ASN" "NASN" } { 1 "ASN" "CASN" }
  { 0 "ASP" "NASP" } { 1 "ASP" "CASP" }
  { 0 "CYS" "NCYS" } { 1 "CYS" "CCYS" }
  { 0 "CYX" "NCYX" } { 1 "CYX" "CCYX" }
  { 0 "GLN" "NGLN" } { 1 "GLN" "CGLN" }
  { 0 "GLU" "NGLU" } { 1 "GLU" "CGLU" }
  { 0 "GLY" "NGLY" } { 1 "GLY" "CGLY" }
  { 0 "HID" "NHID" } { 1 "HID" "CHID" }
  { 0 "HIE" "NHIE" } { 1 "HIE" "CHIE" }
  { 0 "HIP" "NHIP" } { 1 "HIP" "CHIP" }
  { 0 "ILE" "NILE" } { 1 "ILE" "CILE" }
  { 0 "LEU" "NLEU" } { 1 "LEU" "CLEU" }
  { 0 "LYS" "NLYS" } { 1 "LYS" "CLYS" }
  { 0 "MET" "NMET" } { 1 "MET" "CMET" }
  { 0 "PHE" "NPHE" } { 1 "PHE" "CPHE" }
  { 0 "PRO" "NPRO" } { 1 "PRO" "CPRO" }
  { 0 "SER" "NSER" } { 1 "SER" "CSER" }
  { 0 "THR" "NTHR" } { 1 "THR" "CTHR" }
  { 0 "TRP" "NTRP" } { 1 "TRP" "CTRP" }
  { 0 "TYR" "NTYR" } { 1 "TYR" "CTYR" }
  { 0 "VAL" "NVAL" } { 1 "VAL" "CVAL" }
  { 0 "HIS" "NHIS" } { 1 "HIS" "CHIS" }
  { 0 "G" "G5"  } { 1 "G" "G3"  }
  { 0 "A" "A5"  } { 1 "A" "A3"  }
  { 0 "C" "C5"  } { 1 "C" "C3"  }
  { 0 "U" "U5"  } { 1 "U" "U3"  }
  { 0 "DG" "DG5"  } { 1 "DG" "DG3"  }
  { 0 "DA" "DA5"  } { 1 "DA" "DA3"  }
  { 0 "DC" "DC5"  } { 1 "DC" "DC3"  }
  { 0 "DT" "DT5"  } { 1 "DT" "DT3"  }
#  some old Amber residue names for RNA:
  { 0  "RA5" "A5" } { 1 "RA3" "A3"} {"RA" "A" }
  { 0  "RC5" "C5" } { 1 "RC3" "C3"} {"RC" "C" }
  { 0  "RG5" "G5" } { 1 "RG3" "G3"} {"RG" "G" }
  { 0  "RU5" "U5" } { 1 "RU3" "U3"} {"RU" "U" }
#  some really old Amber residue names, assuming DNA:
  { 0 "GUA" "DG5"  } { 1 "GUA" "DG3"  } { "GUA" "DG" }
  { 0 "ADE" "DA5"  } { 1 "ADE" "DA3"  } { "ADE" "DA" }
  { 0 "CYT" "DC5"  } { 1 "CYT" "DC3"  } { "CYT" "DC" }
  { 0 "THY" "DT5"  } { 1 "THY" "DT3"  } { "THY" "DT" }
#  uncomment out the following if you have this old style RNA files:
# { 0 "GUA" "G5"  } { 1 "GUA" "G3"  } { "GUA" "G" }
# { 0 "ADE" "A5"  } { 1 "ADE" "A3"  } { "ADE" "A" }
# { 0 "CYT" "C5"  } { 1 "CYT" "C3"  } { "CYT" "C" }
# { 0 "URA" "R5"  } { 1 "URA" "R3"  } { "URA" "R" }

}

#  try to be good about reading in really old atom names as well:
addPdbAtomMap {
  { "O5*" "O5'" }
  { "C5*" "C5'" }
  { "C4*" "C4'" }
  { "O4*" "O4'" }
  { "C3*" "C3'" }
  { "O3*" "O3'" }
  { "C2*" "C2'" }
  { "O2*" "O2'" }
  { "C1*" "C1'" }
  { "C5M" "C7"  }
  { "H1*" "H1'" }
  { "H2*1" "H2'" }
  { "H2*2" "H2''" }
  { "H2'1" "H2'" }
  { "H2'2" "H2''" }
  { "H3*" "H3'" }
  { "H4*" "H4'" }
  { "H5*1" "H5'" }
  { "H5*2" "H5''" }
  { "H5'1" "H5'" }
  { "H5'2" "H5''" }
  { "HO'2" "HO2'" }
  { "H5T"  "HO5'" }
  { "H3T"  "HO3'" }
  { "O1'" "O4'" }
  { "OA"  "OP1" }
  { "OB"  "OP2" }
  { "O1P" "OP1" }
  { "O2P" "OP2" }
}

#
# assume that most often proteins use HIE
#
NHIS = NHIE
HIS = HIE
CHIS = CHIE
""")
        params = openmm.OpenMMParameterSet.from_parameterset(
            pmd.amber.AmberParameterSet.from_leaprc(leaprc))
        ffxml_filename = get_fn('amber_conv.xml', written=True)
        params.write(ffxml_filename,
                     provenance=dict(OriginalFile='leaprc.ff14SB',
                                     Reference=[
                                         'Maier and Simmerling',
                                         'Simmerling and Maier'
                                     ],
                                     Source=dict(Source='leaprc.ff14SB',
                                                 sourcePackage='AmberTools',
                                                 sourcePackageVersion='15')))
        forcefield = app.ForceField(ffxml_filename)
        # Make sure the forcefield can handle proteins with disulfide bonds
        pdbfile = app.PDBFile(get_fn('3qyt_fix.pdb'))
        forcefield.createSystem(pdbfile.topology, nonbondedMethod=app.NoCutoff)
示例#43
0
 def tearDown(self):
     if os.path.exists(get_fn('writes')):
         for f in os.listdir(get_fn('writes')):
             os.unlink(get_fn(f, written=True))
示例#44
0
 def test_read_normal(self):
     """ Tests genopen reading a normal text file """
     with closing(genopen(get_fn('4lzt.pdb'))) as f:
         self.assertEqual(f.read(), open(get_fn('4lzt.pdb')).read())
     with closing(genopen(get_fn('4lzt.pdb'), 'r')) as f:
         self.assertEqual(f.read(), open(get_fn('4lzt.pdb')).read())
示例#45
0
 def test_read_gzipped_URL(self):
     """ Tests genopen reading a gzipped remote file """
     url = 'https://github.com/ParmEd/ParmEd/raw/master/test/files/4lzt.pdb.gz'
     with closing(genopen(url, 'r')) as f:
         self.assertEqual(f.read(), genopen(get_fn('4lzt.pdb.gz')).read())
示例#46
0
 def test_space_group(self):
     parm_from_cif = pmd.load_file(get_fn('2igd.cif'))
     parm_from_pdb = pmd.load_file(get_fn('2igd.pdb'))
     self.assertEqual(parm_from_cif.space_group, 'P 21 21 21')
     self.assertEqual(parm_from_pdb.space_group, 'P 21 21 21')
示例#47
0
 def test_deserialize_integrator(self):
     """ Tests automatic deserialization of an Integrator XML file """
     integrator = openmm.XmlFile.parse(get_fn('integrator.xml'))
     self.assertIsInstance(integrator, mm.Integrator)
     self.assertIsInstance(integrator, mm.LangevinIntegrator)
示例#48
0
 def test1012(self):
     """ Test that 10-12 prmtop files are recognized properly """
     parm = readparm.AmberParm(get_fn('ff91.parm7'))
     self._standard_parm_tests(parm, has1012=True)
示例#49
0
 def testLoadParm(self):
     """ Test the arbitrary parm loader """
     parm = readparm.LoadParm(get_fn('trx.prmtop'))
     parm2 = readparm.AmberParm(get_fn('trx.prmtop'))
     for key in parm.parm_data:
         self.assertEqual(parm.parm_data[key], parm2.parm_data[key])
示例#50
0
 def test_read_gzipped(self):
     """ Tests genopen reading a gzipped file """
     with closing(genopen(get_fn('4lzt.pdb.gz'))) as f:
         text = gzip.open(get_fn('4lzt.pdb.gz'), 'r').read()
         self.assertEqual(f.read(), text.decode('ascii'))
示例#51
0
 def test_read_bzipped(self):
     """ Tests genopen reading a bzipped file """
     with closing(genopen(get_fn('4lzt.pdb.bz2'), 'r')) as f:
         text = bz2.BZ2File(get_fn('4lzt.pdb.bz2'), 'r').read()
         self.assertEqual(text.decode('ascii'), f.read())
 def test_add_amber_parm(self):
     """ Test adding AmberParm-derived instances to ParmList """
     parms = ParmList()
     amber = AmberParm(get_fn('tip4p.parm7'))
     chamber = ChamberParm(get_fn('ala_ala_ala.parm7'))
     amoeba = AmoebaParm(get_fn('nma.parm7'))
     parms.add_parm(amber)
     parms.add_parm(chamber)
     parms.add_parm(amoeba)
     self.assertEqual(len(parms), 3)
     # Test int indexing
     self.assertIs(parms[0], amber)
     self.assertIs(parms[1], chamber)
     self.assertIs(parms[2], amoeba)
     self.assertRaises(IndexError, lambda: parms[3])
     # Test name indexing
     self.assertIs(parms[get_fn('tip4p.parm7')], amber)
     self.assertIs(parms[get_fn('ala_ala_ala.parm7')], chamber)
     self.assertIs(parms[get_fn('nma.parm7')], amoeba)
     self.assertRaises(IndexError, lambda: parms['noparm'])
     # Check that the last added parm is active
     self.assertIs(parms.parm, amoeba)
     # Set a new active topology
     parms.set_new_active(0)
     self.assertIs(parms.parm, amber)
     parms.set_new_active(get_fn('ala_ala_ala.parm7'))
     self.assertIs(parms.parm, chamber)
     self.assertRaises(IndexError, lambda: parms.set_new_active(3))
     self.assertIs(parms.parm, chamber)
     self.assertRaises(exc.DuplicateParm,
                       lambda: parms.add_parm(get_fn('ala_ala_ala.parm7')))
     self.assertRaises(
         exc.DuplicateParm,
         lambda: parms.add_parm(load_file(get_fn('ala_ala_ala.parm7'))))
     self.assertRaises(
         exc.ParmError, lambda: parms.add_parm(
             os.path.join(get_fn('pptest1'), 'pptest1.h')))
     self.assertRaises(exc.ParmError,
                       lambda: parms.add_parm(get_fn('amino12.lib')))
     self.assertRaises(exc.ParmError, lambda: parms.add_parm(object()))
示例#53
0
 def test_write_bzipped(self):
     """ Tests genopen writing a bzipped file """
     with closing(genopen(get_fn('test.bz2', written=True), 'w')) as f:
         f.write(ALPHABET)
     text = bz2.BZ2File(get_fn('test.bz2', written=True), 'r').read()
     self.assertEqual(text.decode('ascii'), ALPHABET)
示例#54
0
 def test_read_ftp_URL(self):
     """ Tests genopen reading a ftp remote file """
     url = 'ftp://ftp.wwpdb.org/pub/pdb/data/structures/divided/mmCIF/05/205l.cif.gz'
     with closing(genopen(url, 'r')) as f:
         self.assertEqual(f.read(), genopen(get_fn('205l.cif.gz')).read())
示例#55
0
 def setUp(self):
     try:
         os.makedirs(get_fn('writes'))
     except OSError:
         pass
示例#56
0
import subprocess
import unittest
import parmed as pmd
import numpy as np
from parmed.residue import WATER_NAMES
import pytest
try:
    from io import StringIO
except ImportError:
    from cStringIO import StringIO

from pdb4amber import pdb4amber
# local
from utils import tempfolder, get_fn, _has_program

pdb_fn = get_fn('4lzt/4lzt_h.pdb')

try:
    # check internet
    pmd.download_PDB('1l2y')
    internet_ok = True
except IOError:
    internet_ok = False


@unittest.skipUnless(internet_ok, 'must have internet connection to rcsb')
def test_write_model():
    orig_parm = pmd.download_PDB('1l2y')
    pdb_out = 'out.pdb'

    # default
示例#57
0
 def test_write_xml_small_amber(self):
     """ Test writing small XML modifications """
     params = openmm.OpenMMParameterSet.from_parameterset(
         load_file(os.path.join(get_fn('parm'), 'frcmod.constph')))
     params.write(get_fn('test.xml', written=True))
示例#58
0
 def test_write_normal(self):
     """ Tests genopen writing a normal text file """
     with closing(genopen(get_fn('tmp.txt', written=True), 'w')) as f:
         f.write(ALPHABET)
     self.assertEqual(
         open(get_fn('tmp.txt', written=True), 'r').read(), ALPHABET)
示例#59
0
 def setUp(self):
     self.verbose = False
     self.pathPdbxDataFile = get_fn("1kip.cif")
     self.pathBigPdbxDataFile = get_fn("1ffk.cif")
     self.pathSFDataFile = get_fn("1kip-sf.cif")
示例#60
0
 def test_read_normal_URL(self):
     """ Tests genopen reading a remote file """
     url = 'https://github.com/ParmEd/ParmEd/raw/master/test/files/tripos1.mol2'
     with closing(genopen(url, 'r')) as f:
         self.assertEqual(f.read(), open(get_fn('tripos1.mol2')).read())