Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[fmt] Format converters modules and tests #4850

Merged
merged 3 commits into from
Dec 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 26 additions & 18 deletions package/MDAnalysis/converters/OpenMM.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,13 +77,17 @@ class OpenMMSimulationReader(base.SingleFrameReaderBase):
"""

format = "OPENMMSIMULATION"
units = {"time": "ps", "length": "nm", "velocity": "nm/ps",
"force": "kJ/(mol*nm)", "energy": "kJ/mol"}
units = {
"time": "ps",
"length": "nm",
"velocity": "nm/ps",
"force": "kJ/(mol*nm)",
"energy": "kJ/mol",
}

@staticmethod
def _format_hint(thing):
"""Can this reader read *thing*?
"""
"""Can this reader read *thing*?"""
try:
from openmm.app import Simulation
except ImportError:
Expand All @@ -104,34 +108,38 @@ def _read_first_frame(self):
self.ts.triclinic_dimensions = self.convert_pos_from_native(
self.ts.triclinic_dimensions, inplace=False
)
self.ts.dimensions[3:] = _sanitize_box_angles(self.ts.dimensions[3:])
self.ts.dimensions[3:] = _sanitize_box_angles(
self.ts.dimensions[3:]
)
self.convert_velocities_from_native(self.ts._velocities)
self.convert_forces_from_native(self.ts._forces)
self.convert_time_from_native(self.ts.dt)

def _mda_timestep_from_omm_context(self):
""" Construct Timestep object from OpenMM context """
"""Construct Timestep object from OpenMM context"""
try:
import openmm.unit as u
except ImportError: # pragma: no cover
import simtk.unit as u

state = self.filename.context.getState(-1, getVelocities=True,
getForces=True, getEnergy=True)
state = self.filename.context.getState(
-1, getVelocities=True, getForces=True, getEnergy=True
)

n_atoms = self.filename.context.getSystem().getNumParticles()

ts = self._Timestep(n_atoms, **self._ts_kwargs)
ts.frame = 0
ts.data["time"] = state.getTime()._value
ts.data["potential_energy"] = (
state.getPotentialEnergy().in_units_of(u.kilojoule/u.mole)._value
state.getPotentialEnergy().in_units_of(u.kilojoule / u.mole)._value
)
ts.data["kinetic_energy"] = (
state.getKineticEnergy().in_units_of(u.kilojoule/u.mole)._value
state.getKineticEnergy().in_units_of(u.kilojoule / u.mole)._value
)
ts.triclinic_dimensions = state.getPeriodicBoxVectors(
asNumpy=True)._value
asNumpy=True
)._value
ts.dimensions[3:] = _sanitize_box_angles(ts.dimensions[3:])
ts.positions = state.getPositions(asNumpy=True)._value
ts.velocities = state.getVelocities(asNumpy=True)._value
Expand All @@ -153,8 +161,7 @@ class OpenMMAppReader(base.SingleFrameReaderBase):

@staticmethod
def _format_hint(thing):
"""Can this reader read *thing*?
"""
"""Can this reader read *thing*?"""
try:
from openmm import app
except ImportError:
Expand All @@ -163,8 +170,7 @@ def _format_hint(thing):
except ImportError:
return False
else:
return isinstance(thing, (app.PDBFile, app.Modeller,
app.PDBxFile))
return isinstance(thing, (app.PDBFile, app.Modeller, app.PDBxFile))

def _read_first_frame(self):
self.n_atoms = self.filename.topology.getNumAtoms()
Expand All @@ -177,10 +183,12 @@ def _read_first_frame(self):
self.ts.triclinic_dimensions = self.convert_pos_from_native(
self.ts.triclinic_dimensions, inplace=False
)
self.ts.dimensions[3:] = _sanitize_box_angles(self.ts.dimensions[3:])
self.ts.dimensions[3:] = _sanitize_box_angles(
self.ts.dimensions[3:]
)

def _mda_timestep_from_omm_app(self):
""" Construct Timestep object from OpenMM Application object """
"""Construct Timestep object from OpenMM Application object"""

omm_object = self.filename
n_atoms = omm_object.topology.getNumAtoms()
Expand All @@ -198,7 +206,7 @@ def _mda_timestep_from_omm_app(self):


def _sanitize_box_angles(angles):
""" Ensure box angles correspond to first quadrant
"""Ensure box angles correspond to first quadrant

See `discussion on unitcell angles <https://github.com/MDAnalysis/mdanalysis/pull/2917/files#r620558575>`_
"""
Expand Down
48 changes: 24 additions & 24 deletions package/MDAnalysis/converters/OpenMMParser.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,9 +84,7 @@

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

"""
"""Can this Parser read object *thing*?"""
try:
from openmm import app
except ImportError:
Expand All @@ -98,7 +96,7 @@
return isinstance(thing, app.Topology)

def _mda_topology_from_omm_topology(self, omm_topology):
""" Construct mda topology from omm topology
"""Construct mda topology from omm topology

Can be used for any openmm object that contains a topology object

Expand Down Expand Up @@ -130,9 +128,11 @@
try:
from simtk.unit import daltons
except ImportError:
msg = ("OpenMM is required for the OpenMMParser but "
"it's not installed. Try installing it with \n"
"conda install -c conda-forge openmm")
msg = (

Check warning on line 131 in package/MDAnalysis/converters/OpenMMParser.py

View check run for this annotation

Codecov / codecov/patch

package/MDAnalysis/converters/OpenMMParser.py#L131

Added line #L131 was not covered by tests
"OpenMM is required for the OpenMMParser but "
"it's not installed. Try installing it with \n"
"conda install -c conda-forge openmm"
)
raise ImportError(msg)

atom_resindex = [a.residue.index for a in omm_topology.atoms()]
Expand Down Expand Up @@ -168,19 +168,21 @@
if elem.symbol.capitalize() in SYMB2Z:
validated_elements.append(elem.symbol)
else:
validated_elements.append('')
validated_elements.append("")
atomtypes.append(elem.symbol)
masses.append(elem.mass.value_in_unit(daltons))
else:
validated_elements.append('')
validated_elements.append("")
masses.append(0.0)
atomtypes.append('X')
atomtypes.append("X")

if not all(validated_elements):
if any(validated_elements):
warnings.warn("Element information missing for some atoms. "
"These have been given an empty element record ")
if any(i == 'X' for i in atomtypes):
warnings.warn(
"Element information missing for some atoms. "
"These have been given an empty element record "
)
if any(i == "X" for i in atomtypes):
warnings.warn(
"For absent elements, atomtype has been "
"set to 'X' and mass has been set to 0.0. "
Expand All @@ -189,10 +191,12 @@
"to_guess=['masses', 'types']). "
"(for MDAnalysis version 2.x "
"this is done automatically,"
" but it will be removed in 3.0).")
" but it will be removed in 3.0)."
)

attrs.append(Elements(np.array(validated_elements,
dtype=object)))
attrs.append(
Elements(np.array(validated_elements, dtype=object))
)

else:
wmsg = (
Expand All @@ -205,7 +209,8 @@
"These can be guessed using "
"universe.guess_TopologyAttrs("
"to_guess=['masses', 'types']) "
"See MDAnalysis.guessers.")
"See MDAnalysis.guessers."
)

warnings.warn(wmsg)
else:
Expand Down Expand Up @@ -239,9 +244,7 @@

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

"""
"""Can this Parser read object *thing*?"""
try:
from openmm import app
except ImportError:
Expand All @@ -252,10 +255,7 @@
else:
return isinstance(
thing,
(
app.PDBFile, app.Modeller,
app.Simulation, app.PDBxFile
)
(app.PDBFile, app.Modeller, app.Simulation, app.PDBxFile),
)

def parse(self, **kwargs):
Expand Down
Loading
Loading