Skip to content

Commit

Permalink
Tidying of topology related things
Browse files Browse the repository at this point in the history
Changed Universe._psf to Universe._topology

topology.base.TopologyReader now has keyword 'universe' which
gets saved as self._u.  This is then passed to Atoms on creation.

Atoms can now be passed their Universe as kwarg.

All '_things' renamed to 'things' in Universe._topology.

Renamed __is_guessed to _is_guessed in Bond (death to double
underscores)

Added absolute_import from future to all topology modules (Issues #132 #216)

Updated tests to reflect new names
  • Loading branch information
richardjgowers committed Apr 9, 2015
1 parent 9f7711a commit 37d4fdb
Show file tree
Hide file tree
Showing 23 changed files with 215 additions and 171 deletions.
49 changes: 24 additions & 25 deletions package/MDAnalysis/core/AtomGroup.py
Original file line number Diff line number Diff line change
Expand Up @@ -386,7 +386,7 @@ class Atom(object):

def __init__(self, number, name, type, resname, resid, segid, mass, charge,
residue=None, segment=None, radius=None, bfactor=None,
resnum=None, serial=None, altLoc=None):
resnum=None, serial=None, altLoc=None, universe=None):
self.number = number
self.name = name
self.altLoc = altLoc
Expand All @@ -402,7 +402,7 @@ def __init__(self, number, name, type, resname, resid, segid, mass, charge,
self.radius = radius
self.bfactor = bfactor
self.serial = serial
self.__universe = None
self.__universe = universe

def __repr__(self):
return ("<Atom {idx}: {name} of type {t} of resname {rname}, "
Expand Down Expand Up @@ -2964,7 +2964,8 @@ class Universe(object):
:attr:`Universe.trajectory.ts` is the current time step
- :attr:`Universe.dimensions`: current system dimensions (simulation unit cell, if
set in the trajectory)
- bonds, angles, dihedrals, impropers (low level access through :attr:`Universe._psf`)
- bonds, angles, dihedrals, impropers
(low level access through :attr:`Universe._topology`)
.. Note::
Expand Down Expand Up @@ -3120,9 +3121,9 @@ def __init__(self, *args, **kwargs):
permissive=perm,
tformat=topology_format)
try:
with parser(self.filename,
with parser(self.filename, universe=self,
guess_bonds_mode=kwargs.get('bonds', False)) as p:
self._psf = p.parse()
self._topology = p.parse()
except IOError as err:
raise IOError("Failed to load from the topology file {}"
" with parser {}.\n"
Expand Down Expand Up @@ -3162,17 +3163,15 @@ def _fill_cache(self, name, value):
self._cache[name] = value

def _init_topology(self):
"""Populate Universe attributes from the structure dictionary *_psf*."""
self.atoms = AtomGroup(self._psf["_atoms"])
"""Populate Universe attributes from the structure dictionary
*_topology*.
"""
self.atoms = AtomGroup(self._topology['atoms'])

# XXX: add H-bond information here if available from psf (or other sources)
# segment instant selectors
self._build_segments()

# Let atoms access the universe
for a in self.atoms:
a.universe = self

def _build_segments(self):
"""Parse list of atoms into segments.
Expand Down Expand Up @@ -3201,7 +3200,7 @@ def _build_segments(self):
self.universe = self # for Writer.write(universe), see Issue 49

def _init_bonds(self):
"""Set bond information from u._psf['_bonds']
"""Set bond information from u._topology['bonds']
.. versionchanged 0.9.0
Now returns a :class:`~MDAnalysis.topology.core.TopologyGroup`
Expand All @@ -3216,11 +3215,11 @@ def fix_order(bondset):

bondlist = set()

defined_bonds = fix_order(self._psf.get('_bonds', set()))
guessed_bonds = fix_order(self._psf.get('_guessed_bonds', set()))
defined_bonds = fix_order(self._topology.get('bonds', set()))
guessed_bonds = fix_order(self._topology.get('guessed_bonds', set()))
# Some topologies define an order for bonds, this is stored
# as dict of bondtuple:value
bondorder = self._psf.get('_bondorder', False)
bondorder = self._topology.get('bondorder', False)
# Defined bonds take priority, remove bonds in 'guessed' that are in 'defined'
guessed_bonds.difference_update(defined_bonds)

Expand All @@ -3246,14 +3245,14 @@ def fix_order(bondset):
return None

def _init_angles(self):
"""Builds angle information from u._psf['_angles']
"""Builds angle information from u._topology['angles']
Returns ``None`` if no angle information is present, otherwise
returns a :class:`~MDAnalysis.topology.core.TopologyGroup`
.. versionadded 0.9.0
"""
angle_entries = self._psf.get('_angles', None)
angle_entries = self._topology.get('angles', None)
if angle_entries is None:
return None
else:
Expand All @@ -3267,14 +3266,14 @@ def _init_angles(self):
return None

def _init_torsions(self):
"""Builds torsion information from u._psf['_dihe']
"""Builds torsion information from u._topology['torsions']
Returns ``None`` if no torsion information is present, otherwise
returns a :class:`~MDAnalysis.topology.core.TopologyGroup`
.. versionadded 0.9.0
"""
torsion_entries = self._psf.get('_dihe', None)
torsion_entries = self._topology.get('torsions', None)
if torsion_entries is None:
return None
else:
Expand All @@ -3288,14 +3287,14 @@ def _init_torsions(self):
return None

def _init_impropers(self):
"""Build improper torsion information from u._psf['_impr']
"""Build improper torsion information from u._topology['impropers']
Returns ``None`` if no improper torsion information is present,
otherwise returns a :class:`~MDAnalysis.topology.core.TopologyGroup`
.. versionadded 0.9.0
"""
torsion_entries = self._psf.get('_impr', None)
torsion_entries = self._topology.get('impropers', None)
if torsion_entries is None:
return None
else:
Expand Down Expand Up @@ -3518,7 +3517,7 @@ def bonds(self, bondlist):
.. versionadded:: 0.9.0
"""
del self.bonds
self._psf['_bonds'] = bondlist
self._topology['bonds'] = bondlist
self._fill_cache('bonds', self._init_bonds())

@bonds.deleter
Expand Down Expand Up @@ -3547,7 +3546,7 @@ def angles(self):
@angles.setter
def angles(self, bondlist):
del self.angles
self._psf['_angles'] = bondlist
self._topology['angles'] = bondlist
self._fill_cache('angles', self._init_angles())

@angles.deleter
Expand All @@ -3570,7 +3569,7 @@ def torsions(self):
@torsions.setter
def torsions(self, bondlist):
del self.torsions
self._psf['_dihe'] = bondlist
self._topology['torsions'] = bondlist
self._fill_cache('torsions', self._init_torsions())

@torsions.deleter
Expand All @@ -3593,7 +3592,7 @@ def impropers(self):
@impropers.setter
def impropers(self, bondlist):
del self.impropers
self._psf['_impr'] = bondlist
self._topology['impropers'] = bondlist
self._fill_cache('impropers', self._init_impropers())

@impropers.deleter
Expand Down
12 changes: 7 additions & 5 deletions package/MDAnalysis/topology/CRDParser.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,11 @@
:inherited-members:
"""
from __future__ import absolute_import

from MDAnalysis.core.AtomGroup import Atom
from MDAnalysis.core.util import openany, FORTRANReader
from MDAnalysis.topology.core import guess_atom_type, guess_atom_mass, guess_atom_charge
from ..core.AtomGroup import Atom
from ..core.util import openany, FORTRANReader
from .core import guess_atom_type, guess_atom_mass, guess_atom_charge
from .base import TopologyReader


Expand Down Expand Up @@ -75,10 +76,11 @@ def parse(self):
atomtype = guess_atom_type(name)
mass = guess_atom_mass(name)
charge = guess_atom_charge(name)
atoms.append(Atom(atom_serial, name, atomtype, resName, TotRes, chainID, mass, charge))
atoms.append(Atom(atom_serial, name, atomtype, resName,
TotRes, chainID, mass, charge, universe=self._u))
atom_serial += 1

structure = {}
structure["_atoms"] = atoms
structure['atoms'] = atoms

return structure
12 changes: 8 additions & 4 deletions package/MDAnalysis/topology/DMSParser.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,13 @@
:inherited-members:
"""
from __future__ import absolute_import

import sqlite3
import os

from MDAnalysis.core.AtomGroup import Atom
from MDAnalysis.topology.core import guess_atom_type
from ..core.AtomGroup import Atom
from .core import guess_atom_type
from .base import TopologyReader


Expand Down Expand Up @@ -92,7 +93,8 @@ def dict_factory(cursor, row):
atoms = [Atom(p["id"], p["name"].strip(),
guess_atom_type(p["name"].strip()),
p["resname"].strip(), p["resid"],
p["segid"].strip(), p["mass"], p["charge"])
p["segid"].strip(), p["mass"], p["charge"],
universe=self._u)
for p in particles]
except KeyError:
raise ValueError("Failed reading atom information")
Expand All @@ -112,6 +114,8 @@ def dict_factory(cursor, row):
# All the records below besides donors and acceptors can be contained in a DMS file.
# In addition to the coordinates and bonds, DMS may contain the entire force-field
# information (terms+parameters),
structure = {"_atoms": atoms, "_bonds": tuple(bondlist), "_bondorder": bondorder}
structure = {"atoms": atoms,
"bonds": tuple(bondlist),
"bondorder": bondorder}

return structure
7 changes: 4 additions & 3 deletions package/MDAnalysis/topology/ExtendedPDBParser.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,9 @@
:inherited-members:
"""
from __future__ import absolute_import

import MDAnalysis.coordinates.PDB
import PrimitivePDBParser
from . import PrimitivePDBParser


class ExtendedPDBParser(PrimitivePDBParser.PrimitivePDBParser):
Expand All @@ -69,4 +69,5 @@ class ExtendedPDBParser(PrimitivePDBParser.PrimitivePDBParser):
"""
def __init__(self, filename, **kwargs):
super(ExtendedPDBParser, self).__init__(filename, **kwargs)
self.PDBReader = MDAnalysis.coordinates.PDB.ExtendedPDBReader
from ..coordinates.PDB import ExtendedPDBReader
self.PDBReader = ExtendedPDBReader
7 changes: 4 additions & 3 deletions package/MDAnalysis/topology/GMSParser.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,12 @@
"""
from __future__ import absolute_import

import re

from ..core.AtomGroup import Atom
from ..core.util import openany
from .core import get_atom_mass, guess_atom_charge, guess_atom_element
from .base import TopologyReader
import re


class GMSParser(TopologyReader):
Expand Down Expand Up @@ -82,10 +83,10 @@ def parse(self):
mass = get_atom_mass(elem)
#TODO: may be use coordinates info from _m.group(3-5) ??
at = Atom(i, name, elem, resname, resid,
segid, mass, charge)
segid, mass, charge, universe=self._u)
atoms.append(at)
i += 1

struc = {"_atoms": atoms}
struc = {"atoms": atoms}

return struc
9 changes: 5 additions & 4 deletions package/MDAnalysis/topology/GROParser.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,10 @@
:inherited-members:
"""
from __future__ import absolute_import

from MDAnalysis.core.util import openany
from MDAnalysis.core.AtomGroup import Atom
from ..core.util import openany
from ..core.AtomGroup import Atom
from .core import get_atom_mass, guess_atom_charge, guess_atom_element
from .base import TopologyReader

Expand Down Expand Up @@ -89,8 +90,8 @@ def parse(self):
# Just use the atom_iter (counting from 0) rather than
# the number in the .gro file (which wraps at 99999)
atoms.append(Atom(atom_iter, name, atype, resname, resid,
segid, mass, charge))
segid, mass, charge, universe=self._u))
atom_iter += 1
structure = {'_atoms':atoms}
structure = {'atoms': atoms}

return structure
Loading

0 comments on commit 37d4fdb

Please sign in to comment.