"vscode:/vscode.git/clone" did not exist on "59b0b53ff4d602d963a1ae1056ba4a2a35a9bf40"
TestPdbxFile.py 8.03 KB
Newer Older
1
import tempfile
2
import unittest
3
4
5
6
from openmm.app import *
from openmm import *
from openmm.unit import *
import openmm.app.element as elem
Jason Swails's avatar
Jason Swails committed
7
import os
8
from io import StringIO
9
10
11

class TestPdbxFile(unittest.TestCase):
    """Test the PDBx/mmCIF file parser"""
12
13
14
15
16

    def test_FormatConversion(self):
        """Test conversion from PDB to PDBx"""

        mol = PDBFile('systems/ala_ala_ala.pdb')
17
18
19
20
21
22
23
        with tempfile.TemporaryDirectory() as tempdir:
            filename = os.path.join(tempdir, 'temp.pdbx')
            PDBxFile.writeFile(mol.topology, mol.positions, filename, keepIds=True)
            try:
                pdbx = PDBxFile(filename)
            except Exception:
                self.fail('Parser failed to read PDBx/mmCIF file')
24
25


26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
    def test_Triclinic(self):
        """Test parsing a file that describes a triclinic box."""
        pdb = PDBxFile('systems/triclinic.pdbx')
        self.assertEqual(len(pdb.positions), 8)
        expectedPositions = [
            Vec3(1.744, 2.788, 3.162),
            Vec3(1.048, 0.762, 2.340),
            Vec3(2.489, 1.570, 2.817),
            Vec3(1.027, 1.893, 3.271),
            Vec3(0.937, 0.825, 0.009),
            Vec3(2.290, 1.887, 3.352),
            Vec3(1.266, 1.111, 2.894),
            Vec3(0.933, 1.862, 3.490)]*nanometers
        for (p1, p2) in zip(expectedPositions, pdb.positions):
            self.assertVecAlmostEqual(p1, p2)
        expectedVectors = [
            Vec3(2.5, 0, 0),
            Vec3(0.5, 3.0, 0),
            Vec3(0.7, 0.9, 3.5)]*nanometers
        for (v1, v2) in zip(expectedVectors, pdb.topology.getPeriodicBoxVectors()):
            self.assertVecAlmostEqual(v1, v2, 1e-6)
        self.assertVecAlmostEqual(Vec3(2.5, 3.0, 3.5)*nanometers, pdb.topology.getUnitCellDimensions(), 1e-6)
        for atom in pdb.topology.atoms():
            if atom.index < 4:
                self.assertEqual(elem.chlorine, atom.element)
                self.assertEqual('Cl', atom.name)
                self.assertEqual('Cl', atom.residue.name)
            else:
                self.assertEqual(elem.sodium, atom.element)
                self.assertEqual('Na', atom.name)
                self.assertEqual('Na', atom.residue.name)

    def assertVecAlmostEqual(self, p1, p2, tol=1e-7):
        unit = p1.unit
        p1 = p1.value_in_unit(unit)
        p2 = p2.value_in_unit(unit)
        scale = max(1.0, norm(p1),)
        for i in range(3):
            diff = abs(p1[i]-p2[i])/scale
            self.assertTrue(diff < tol)

Jason Swails's avatar
Jason Swails committed
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
    def testReporterImplicit(self):
        """ Tests the PDBxReporter without PBC """
        parm = AmberPrmtopFile('systems/alanine-dipeptide-implicit.prmtop')
        system = parm.createSystem()
        sim = Simulation(parm.topology, system, VerletIntegrator(1*femtoseconds),
                         Platform.getPlatformByName('Reference'))
        sim.context.setPositions(PDBFile('systems/alanine-dipeptide-implicit.pdb').getPositions())
        sim.reporters.append(PDBxReporter('test.cif', 1))
        sim.step(10)
        pdb = PDBxFile('test.cif')
        self.assertEqual(len(list(pdb.topology.atoms())), len(list(parm.topology.atoms())))
        self.assertEqual(len(list(pdb.topology.residues())), len(list(parm.topology.residues())))
        for res1, res2 in zip(pdb.topology.residues(), parm.topology.residues()):
            self.assertEqual(res1.name, res2.name)
            for atom1, atom2 in zip(res1.atoms(), res2.atoms()):
                self.assertEqual(atom1.name, atom2.name)
        positions = pdb.getPositions(frame=9)
        self.assertFalse(all(x1 == x2 for x1, x2 in zip(positions, pdb.getPositions(frame=0))))
        # There should only be 10 frames (0 through 9)
        self.assertRaises(IndexError, lambda: pdb.getPositions(frame=10))
        self.assertIs(pdb.topology.getPeriodicBoxVectors(), None)
88
        del sim
Jason Swails's avatar
Jason Swails committed
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
        os.unlink('test.cif')

    def assertAlmostEqualVec(self, vec1, vec2, *args, **kwargs):
        if is_quantity(vec1):
            vec1 = vec1.value_in_unit_system(md_unit_system)
        if is_quantity(vec2):
            vec2 = vec2.value_in_unit_system(md_unit_system)
        for x, y in zip(vec1, vec2):
            self.assertAlmostEqual(x, y, *args, **kwargs)

    def testReporterExplicit(self):
        """ Tests the PDBxReporter with PBC """
        parm = AmberPrmtopFile('systems/alanine-dipeptide-explicit.prmtop')
        system = parm.createSystem(nonbondedCutoff=1.0, nonbondedMethod=PME)
        sim = Simulation(parm.topology, system, VerletIntegrator(1*femtoseconds),
                         Platform.getPlatformByName('Reference'))
        orig_pdb = PDBFile('systems/alanine-dipeptide-explicit.pdb')
        sim.context.setPositions(orig_pdb.getPositions())
        sim.context.setPeriodicBoxVectors(*parm.topology.getPeriodicBoxVectors())
        sim.reporters.append(PDBxReporter('test.cif', 1))
        sim.step(10)
        pdb = PDBxFile('test.cif')
        self.assertEqual(len(list(pdb.topology.atoms())), len(list(parm.topology.atoms())))
        self.assertEqual(len(list(pdb.topology.residues())), len(list(parm.topology.residues())))
        for res1, res2 in zip(pdb.topology.residues(), parm.topology.residues()):
            self.assertEqual(res1.name, res2.name)
            for atom1, atom2 in zip(res1.atoms(), res2.atoms()):
                self.assertEqual(atom1.name, atom2.name)
        positions = pdb.getPositions(frame=9)
        self.assertFalse(all(x1 == x2 for x1, x2 in zip(positions, pdb.getPositions(frame=0))))
        # There should only be 10 frames (0 through 9)
        self.assertRaises(IndexError, lambda: pdb.getPositions(frame=10))
        self.assertAlmostEqualVec(parm.topology.getPeriodicBoxVectors()[0],
                                  pdb.topology.getPeriodicBoxVectors()[0],
                                  places=5)
        self.assertAlmostEqualVec(parm.topology.getPeriodicBoxVectors()[1],
                                  pdb.topology.getPeriodicBoxVectors()[1],
                                  places=5)
        self.assertAlmostEqualVec(parm.topology.getPeriodicBoxVectors()[2],
                                  pdb.topology.getPeriodicBoxVectors()[2],
                                  places=5)
130
        del sim
Jason Swails's avatar
Jason Swails committed
131
        os.unlink('test.cif')
132

peastman's avatar
peastman committed
133
134
135
136
137
138
139
140
141
142
143
144
145
146
    def testBonds(self):
        """Test reading and writing a file that includes bonds."""
        pdb = PDBFile('systems/methanol_ions.pdb')
        output = StringIO()
        PDBxFile.writeFile(pdb.topology, pdb.positions, output)
        input = StringIO(output.getvalue())
        pdbx = PDBxFile(input)
        output.close()
        input.close()
        self.assertEqual(pdb.topology.getNumBonds(), pdbx.topology.getNumBonds())
        for bond1, bond2 in zip(pdb.topology.bonds(), pdbx.topology.bonds()):
            self.assertEqual(bond1[0].name, bond2[0].name)
            self.assertEqual(bond1[1].name, bond2[1].name)

147
148
    def testMultiChain(self):
        """Test reading and writing a file that includes multiple chains"""
149
        cif_ori = PDBxFile('systems/multichain.pdbx')
150
151
152
153
154
155
156
157
158
159
160
161
162

        output = StringIO()
        PDBxFile.writeFile(cif_ori.topology, cif_ori.positions, output, keepIds=True)
        input = StringIO(output.getvalue())
        cif_new = PDBxFile(input)
        output.close()
        input.close()

        self.assertEqual(cif_ori.topology.getNumChains(), cif_new.topology.getNumChains())

        for chain1, chain2 in zip(cif_ori.topology.chains(), cif_new.topology.chains()):
            self.assertEqual(chain1.id, chain2.id)

163
164
165
166
167
168
169
170
171
172
173
174
175
    def testInsertionCodes(self):
        """Test reading a file that uses insertion codes."""
        pdbx = PDBxFile('systems/insertions.pdbx')
        residues = list(pdbx.topology.residues())
        self.assertEqual(7, len(residues))
        names = ['PHE', 'ASP', 'LYS', 'ILE', 'LYS', 'ASN', 'TRP']
        ids = ['59', '60', '60', '60', '60', '60', '61']
        codes = ['', '', 'A', 'B', 'C', 'D', '']
        for res, name, id, code in zip(residues, names, ids, codes):
            self.assertEqual(name, res.name)
            self.assertEqual(id, res.id)
            self.assertEqual(code, res.insertionCode)

176
177
if __name__ == '__main__':
    unittest.main()