"vscode:/vscode.git/clone" did not exist on "5a00b39191dd47ca74aac2c11454aa649cc62330"
TestPdbFile.py 7.29 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
7
from io import StringIO
Robert McGibbon's avatar
Robert McGibbon committed
8

9
10
11

class TestPdbFile(unittest.TestCase):
    """Test the PDB file parser"""
Robert McGibbon's avatar
Robert McGibbon committed
12

13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
    def test_Triclinic(self):
        """Test parsing a file that describes a triclinic box."""
        pdb = PDBFile('systems/triclinic.pdb')
        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-4)
        self.assertVecAlmostEqual(Vec3(2.5, 3.0, 3.5)*nanometers, pdb.topology.getUnitCellDimensions(), 1e-4)
        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)

45
46
    def test_WriteFile(self):
        """Write a file, read it back, and make sure it matches the original."""
47
48
49
50
51
52
53
54
55
56
57
58
        def compareFiles(pdb1, pdb2):
            self.assertEqual(len(pdb2.positions), 8)
            for (p1, p2) in zip(pdb1.positions, pdb2.positions):
                self.assertVecAlmostEqual(p1, p2)
            for (v1, v2) in zip(pdb1.topology.getPeriodicBoxVectors(), pdb2.topology.getPeriodicBoxVectors()):
                self.assertVecAlmostEqual(v1, v2, 1e-4)
            self.assertVecAlmostEqual(pdb1.topology.getUnitCellDimensions(), pdb2.topology.getUnitCellDimensions(), 1e-4)
            for atom1, atom2 in zip(pdb1.topology.atoms(), pdb2.topology.atoms()):
                self.assertEqual(atom1.element, atom2.element)
                self.assertEqual(atom1.name, atom2.name)
                self.assertEqual(atom1.residue.name, atom2.residue.name)

59
        pdb1 = PDBFile('systems/triclinic.pdb')
60
61
62

        # First try writing to an open file object.

Robert McGibbon's avatar
Robert McGibbon committed
63
        output = StringIO()
64
        PDBFile.writeFile(pdb1.topology, pdb1.positions, output)
Robert McGibbon's avatar
Robert McGibbon committed
65
        input = StringIO(output.getvalue())
66
        pdb2 = PDBFile(input)
67
68
69
70
71
72
73
74
75
76
77
        output.close()
        input.close()
        compareFiles(pdb1, pdb2)

        # Now try a filename.

        with tempfile.TemporaryDirectory() as tempdir:
            filename = os.path.join(tempdir, 'temp.pdb')
            PDBFile.writeFile(pdb1.topology, pdb1.positions, filename)
            pdb2 = PDBFile(filename)
            compareFiles(pdb1, pdb2)
78

peastman's avatar
peastman committed
79
80
    def test_BinaryStream(self):
        """Test reading a stream that was opened in binary mode."""
81
82
        with open('systems/triclinic.pdb', 'rb') as infile:
            pdb = PDBFile(infile)
peastman's avatar
peastman committed
83
84
        self.assertEqual(len(pdb.positions), 8)

Rafal P. Wiewiora's avatar
tests  
Rafal P. Wiewiora committed
85
86
    def test_ExtraParticles(self):
        """Test reading, and writing and re-reading of a file containing extra particle atoms."""
87
        pdb = PDBFile('systems/tip5p.pdb')
Rafal P. Wiewiora's avatar
tests  
Rafal P. Wiewiora committed
88
89
90
91
92
93
        for atom in pdb.topology.atoms():
            if atom.index > 2:
                self.assertEqual(None, atom.element)
        output = StringIO()
        PDBFile.writeFile(pdb.topology, pdb.positions, output)
        input = StringIO(output.getvalue())
peastman's avatar
peastman committed
94
        pdb = PDBFile(input)
Rafal P. Wiewiora's avatar
tests  
Rafal P. Wiewiora committed
95
96
        for atom in pdb.topology.atoms():
            if atom.index > 2:
Rafal P. Wiewiora's avatar
Rafal P. Wiewiora committed
97
98
                self.assertEqual(None, atom.element)

99
100
    def test_AltLocs(self):
        """Test reading a file that includes AltLocs"""
101
102
103
104
105
106
        for filename in ['altlocs.pdb', 'altlocs2.pdb']:
            pdb = PDBFile(f'systems/{filename}')
            self.assertEqual(1, pdb.topology.getNumResidues())
            self.assertEqual(19, pdb.topology.getNumAtoms())
            self.assertEqual(19, len(pdb.positions))
            self.assertEqual('ILE', list(pdb.topology.residues())[0].name)
Rafal P. Wiewiora's avatar
Rafal P. Wiewiora committed
107

108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
    def test_FormalCharges(self):
        """Test reading, and writing and re-reading of a file containing formal charges."""
        pdb = PDBFile('systems/formal-charges.pdb')
        for atom in pdb.topology.atoms():
            if atom.index == 8:
                self.assertEqual(+1, atom.formalCharge)
            elif atom.index == 29:
                self.assertEqual(-1, atom.formalCharge)
            else:
                self.assertEqual(None, atom.formalCharge)
        output = StringIO()
        PDBFile.writeFile(pdb.topology, pdb.positions, output)
        input = StringIO(output.getvalue())
        pdb = PDBFile(input)
        for atom in pdb.topology.atoms():
            if atom.index == 8:
                self.assertEqual(+1, atom.formalCharge)
            elif atom.index == 29:
                self.assertEqual(-1, atom.formalCharge)
            else:
                self.assertEqual(None, atom.formalCharge)

130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
    def test_LargeFile(self):
        """Write and read a file with more than 100,000 atoms"""
        topology = Topology()
        chain = topology.addChain('A')
        for i in range(20000):
            res = topology.addResidue('MOL', chain)
            atoms = []
            for j in range(6):
                atoms.append(topology.addAtom(f'AT{j}', elem.carbon, res))
            for j in range(5):
                topology.addBond(atoms[j], atoms[j+1])
        positions = [Vec3(0, 0, 0)]*topology.getNumAtoms()

        # The model has 20,000 residues and 120,000 atoms.

        output = StringIO()
        PDBFile.writeFile(topology, positions, output)
        input = StringIO(output.getvalue())
        pdb = PDBFile(input)
        output.close()
        input.close()
        self.assertEqual(len(positions), len(pdb.positions))
        self.assertEqual(topology.getNumAtoms(), pdb.topology.getNumAtoms())
        self.assertEqual(topology.getNumResidues(), pdb.topology.getNumResidues())
        self.assertEqual(topology.getNumChains(), pdb.topology.getNumChains())
        self.assertEqual(topology.getNumBonds(), pdb.topology.getNumBonds())
        for atom in pdb.topology.atoms():
            self.assertEqual(str(atom.index+1), atom.id)
        for res in pdb.topology.residues():
            self.assertEqual(str(res.index+1), res.id)

        # Make sure the CONECT records were interpreted correctly.

        bonds = set()
        for atom1, atom2 in topology.bonds():
            bonds.add(tuple(sorted((atom1.index, atom2.index))))
        for atom1, atom2 in pdb.topology.bonds():
            assert tuple(sorted((atom1.index, atom2.index))) in bonds

Rafal P. Wiewiora's avatar
Rafal P. Wiewiora committed
169
170
171
172
173
174
175
176
177
    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)

178
179
180

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