File: ParmEdParser.py

package info (click to toggle)
mdanalysis 2.10.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 116,696 kB
  • sloc: python: 92,135; ansic: 8,156; makefile: 215; sh: 138
file content (359 lines) | stat: -rw-r--r-- 10,796 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
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
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
#
# MDAnalysis --- https://www.mdanalysis.org
# Copyright (c) 2006-2017 The MDAnalysis Development Team and contributors
# (see the file AUTHORS for the full list of names)
#
# Released under the Lesser GNU Public Licence, v2.1 or any higher version
#
# Please cite your use of MDAnalysis in published work:
#
# R. J. Gowers, M. Linke, J. Barnoud, T. J. E. Reddy, M. N. Melo, S. L. Seyler,
# D. L. Dotson, J. Domanski, S. Buchoux, I. M. Kenney, and O. Beckstein.
# MDAnalysis: A Python package for the rapid analysis of molecular dynamics
# simulations. In S. Benthall and S. Rostrup editors, Proceedings of the 15th
# Python in Science Conference, pages 102-109, Austin, TX, 2016. SciPy.
# doi: 10.25080/majora-629e541a-00e
#
# N. Michaud-Agrawal, E. J. Denning, T. B. Woolf, and O. Beckstein.
# MDAnalysis: A Toolkit for the Analysis of Molecular Dynamics Simulations.
# J. Comput. Chem. 32 (2011), 2319--2327, doi:10.1002/jcc.21787
#

"""
ParmEd topology parser --- :mod:`MDAnalysis.converters.ParmEdParser`
====================================================================

Converts a `ParmEd <https://parmed.github.io/ParmEd/html>`_
:class:`parmed.structure.Structure` into a :class:`MDAnalysis.core.Topology`.


Example
-------

If you want to use an MDAnalysis-written ParmEd structure for simulation
in ParmEd, you need to first read your files with ParmEd to include the
necessary topology parameters. ::

    >>> import parmed as pmd
    >>> import MDAnalysis as mda
    >>> from MDAnalysis.tests.datafiles import PRM7_ala2, RST7_ala2
    >>> prm = pmd.load_file(PRM7_ala2, RST7_ala2)
    >>> prm
    <AmberParm 3026 atoms; 1003 residues; 3025 bonds; PBC (orthogonal); parametrized>

We can then convert this to an MDAnalysis structure, select only the
protein atoms, and then convert it back to ParmEd. ::

    >>> u = mda.Universe(prm)
    >>> u
    <Universe with 3026 atoms>
    >>> prot = u.select_atoms('protein')
    >>> prm_prot = prot.convert_to('PARMED')
    >>> prm_prot
    <Structure 23 atoms; 2 residues; 22 bonds; PBC (orthogonal); parametrized>

From here you can create an OpenMM simulation system and minimize the
energy. ::

    >>> import openmm as mm
    >>> import openmm.app as app
    >>> from parmed import unit as u
    >>> system = prm_prot.createSystem(nonbondedMethod=app.NoCutoff,
    ...                                constraints=app.HBonds,
    ...                                implicitSolvent=app.GBn2)
    >>> integrator = mm.LangevinIntegrator(
    ...                         300*u.kelvin,       # Temperature of heat bath
    ...                         1.0/u.picoseconds,  # Friction coefficient
    ...                         2.0*u.femtoseconds, # Time step
    ... )
    >>> sim = app.Simulation(prm_prot.topology, system, integrator)
    >>> sim.context.setPositions(prm_prot.positions)
    >>> sim.minimizeEnergy(maxIterations=500)

Now you can continue on and run a simulation, if you wish.

Classes
-------

.. autoclass:: ParmEdParser
   :members:
   :inherited-members:

.. versionchanged:: 2.0.0
   The ParmEdParser class was moved from :mod:`~MDAnalysis.topology` to
   :mod:`~MDAnalysis.converters`

"""
import logging
import numpy as np

from ..topology.base import TopologyReaderBase, change_squash
from ..guesser.tables import Z2SYMB
from ..core.topologyattrs import (
    Atomids,
    Atomnames,
    AltLocs,
    ChainIDs,
    Atomtypes,
    Occupancies,
    Tempfactors,
    Elements,
    Masses,
    Charges,
    Resids,
    Resnums,
    Resnames,
    Segids,
    GBScreens,
    SolventRadii,
    NonbondedIndices,
    RMins,
    Epsilons,
    RMin14s,
    Epsilon14s,
    Bonds,
    UreyBradleys,
    Angles,
    Dihedrals,
    Impropers,
    CMaps,
)
from ..core.topology import Topology

logger = logging.getLogger("MDAnalysis.converters.ParmEdParser")


def squash_identical(values):
    if len(values) == 1:
        return values[0]
    else:
        return tuple(values)


class ParmEdParser(TopologyReaderBase):
    """
    For ParmEd structures
    """

    format = "PARMED"

    @staticmethod
    def _format_hint(thing):
        """Can this Parser read object *thing*?

        .. versionadded:: 1.0.0
        """
        try:
            import parmed as pmd
        except ImportError:  # if no parmed, probably not parmed
            return False
        else:
            return isinstance(thing, pmd.Structure)

    def parse(self, **kwargs):
        """Parse PARMED into Topology

        Returns
        -------
        MDAnalysis *Topology* object


        .. versionchanged:: 2.0.0
           Elements are no longer guessed, if the elements present in the
           parmed object are not recoginsed (usually given an atomic mass of 0)
           then they will be assigned an empty string.
        """
        structure = self.filename

        #### === ATOMS === ####
        names = []
        masses = []
        charges = []
        types = []
        atomic_numbers = []
        serials = []

        resnames = []
        resids = []
        chainids = []
        segids = []

        altLocs = []
        bfactors = []
        occupancies = []

        screens = []
        solvent_radii = []
        nonbonded_indices = []

        rmins = []
        epsilons = []
        rmin14s = []
        epsilon14s = []

        for atom in structure.atoms:
            names.append(atom.name)
            masses.append(atom.mass)
            charges.append(atom.charge)
            types.append(atom.type)
            atomic_numbers.append(atom.atomic_number)
            serials.append(atom.number)

            resnames.append(atom.residue.name)
            resids.append(atom.residue.number)
            chainids.append(atom.residue.chain)
            segids.append(atom.residue.segid)

            altLocs.append(atom.altloc)
            bfactors.append(atom.bfactor)
            occupancies.append(atom.occupancy)

            screens.append(atom.screen)
            solvent_radii.append(atom.solvent_radius)
            nonbonded_indices.append(atom.nb_idx)

            rmins.append(atom.rmin)
            epsilons.append(atom.epsilon)
            rmin14s.append(atom.rmin_14)
            epsilon14s.append(atom.epsilon_14)

        attrs = []

        n_atoms = len(names)

        elements = []

        for z, name in zip(atomic_numbers, names):
            try:
                elements.append(Z2SYMB[z])
            except KeyError:
                elements.append("")

        # Make Atom TopologyAttrs
        for vals, Attr, dtype in (
            (names, Atomnames, object),
            (masses, Masses, np.float32),
            (charges, Charges, np.float32),
            (types, Atomtypes, object),
            (elements, Elements, object),
            (serials, Atomids, np.int32),
            (chainids, ChainIDs, object),
            (altLocs, AltLocs, object),
            (bfactors, Tempfactors, np.float32),
            (occupancies, Occupancies, np.float32),
            (screens, GBScreens, np.float32),
            (solvent_radii, SolventRadii, np.float32),
            (nonbonded_indices, NonbondedIndices, np.int32),
            (rmins, RMins, np.float32),
            (epsilons, Epsilons, np.float32),
            (rmin14s, RMin14s, np.float32),
            (epsilon14s, Epsilon14s, np.float32),
        ):
            attrs.append(Attr(np.array(vals, dtype=dtype)))

        resids = np.array(resids, dtype=np.int32)
        resnames = np.array(resnames, dtype=object)
        chainids = np.array(chainids, dtype=object)
        segids = np.array(segids, dtype=object)

        residx, (resids, resnames, chainids, segids) = change_squash(
            (resids, resnames, chainids, segids),
            (resids, resnames, chainids, segids),
        )

        n_residues = len(resids)
        attrs.append(Resids(resids))
        attrs.append(Resnums(resids.copy()))
        attrs.append(Resnames(resnames))

        segidx, (segids,) = change_squash((segids,), (segids,))
        n_segments = len(segids)
        attrs.append(Segids(segids))

        #### === OTHERS === ####
        bond_values = {}
        bond_types = []
        bond_orders = []

        ub_values = {}
        ub_types = []

        angle_values = {}
        angle_types = []

        dihedral_values = {}
        dihedral_types = []

        improper_values = {}
        improper_types = []

        cmap_values = {}
        cmap_types = []

        for bond in structure.bonds:
            idx = (bond.atom1.idx, bond.atom2.idx)
            if idx not in bond_values:
                bond_values[idx] = ([bond], [bond.order])
            else:
                bond_values[idx][0].append(bond)
                bond_values[idx][1].append(bond.order)

        try:
            bond_values, values = zip(*list(bond_values.items()))
        except ValueError:
            bond_values, bond_types, bond_orders = [], [], []
        else:
            bond_types, bond_orders = zip(*values)

            bond_types = list(map(squash_identical, bond_types))
            bond_orders = list(map(squash_identical, bond_orders))

        attrs.append(
            Bonds(
                bond_values, types=bond_types, guessed=False, order=bond_orders
            )
        )

        for pmdlist, na, values, types in (
            (structure.urey_bradleys, 2, ub_values, ub_types),
            (structure.angles, 3, angle_values, angle_types),
            (structure.dihedrals, 4, dihedral_values, dihedral_types),
            (structure.impropers, 4, improper_values, improper_types),
            (structure.cmaps, 5, cmap_values, cmap_types),
        ):

            for p in pmdlist:
                atoms = ["atom{}".format(i) for i in range(1, na + 1)]
                idx = tuple(getattr(p, a).idx for a in atoms)
                if idx not in values:
                    values[idx] = [p]
                else:
                    values[idx].append(p)

        for dct, Attr in (
            (ub_values, UreyBradleys),
            (angle_values, Angles),
            (dihedral_values, Dihedrals),
            (improper_values, Impropers),
            (cmap_values, CMaps),
        ):
            try:
                vals, types = zip(*list(dct.items()))
            except ValueError:
                vals, types = [], []

            types = list(map(squash_identical, types))
            attrs.append(Attr(vals, types=types, guessed=False, order=None))

        top = Topology(
            n_atoms,
            n_residues,
            n_segments,
            attrs=attrs,
            atom_resindex=residx,
            residue_segindex=segidx,
        )

        return top