-
Notifications
You must be signed in to change notification settings - Fork 728
feature: IMDReader Integration #4923
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
Changes from 9 commits
a6f2bb2
a67cbfb
8c00bc1
bc88b7b
cf15cf9
7aed3b4
b5ff03d
6263151
efbb903
2ff3935
073430b
45ad921
eb825c6
5f30313
a8b4157
0dfb194
83d9443
a169cb6
d48fec1
c23fa3e
809d592
a25ff7a
7ae4b21
577f785
93cdb22
7e5bcb0
103278b
5501df6
a9eab43
97d0636
b2239bc
5932f66
808b998
2d95ac7
57948c6
c40a829
05f58e5
b181cb9
2199882
10d260d
f89a75c
2167620
831b46e
38f96a6
e2c0913
07756f8
fd61753
db59525
bfc7e94
bbcb14e
60c434c
3c04d37
6a9115a
27597e7
d04ff96
10dfe27
c6a9f39
65a1bf8
b1502ff
74050f4
9338d96
8f154f2
c9ac065
a2b2136
481163b
b2e4bd9
aad39f1
17f2de7
b1b0fa7
dcb29d9
844a371
806a0ff
f69d741
3e81d96
230f1a6
c89c0b7
0ba7d0c
2e149aa
4aec1fe
a481b56
d50d307
6a739ea
4818a30
a66122a
6ffbe37
b404b04
0583c2e
73d7852
f04c434
a383185
474981d
e32df0d
e4211a1
7aa10d6
ab38548
b63df7e
d663d89
87311d0
6aee915
350af5f
0deecc0
54f17fd
849b8db
487753e
a9d4fd4
8e7a89c
aa395dc
6634706
04424a8
d68de42
16454a6
19a2526
b465bf1
5138b54
cd21d6b
feb6c9d
35fcc8e
f2a5050
ea85bb5
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,215 @@ | ||
""" | ||
IMDReader --- :mod:`MDAnalysis.coordinates.IMD` | ||
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | ||
Read and analyze simulation data interactively using `IMDClient`_. | ||
hmacdope marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
amruthesht marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
.. _IMDClient: https://github.com/Becksteinlab/imdclient | ||
Units | ||
----- | ||
The units in IMDv3 are fixed. | ||
.. list-table:: | ||
:widths: 10 10 | ||
:header-rows: 1 | ||
* - Measurement | ||
- Unit | ||
* - Length | ||
- angstrom | ||
* - Velocity | ||
- angstrom/picosecond | ||
* - Force | ||
- kilojoules/(mol*angstrom) | ||
* - Time | ||
- picosecond | ||
* - Energy | ||
- kilojoules/mol | ||
amruthesht marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
Classes | ||
------- | ||
.. autoclass:: IMDReader | ||
:members: | ||
:inherited-members: | ||
""" | ||
|
||
import numpy as np | ||
import logging | ||
import warnings | ||
|
||
from MDAnalysis.coordinates import core | ||
from MDAnalysis.lib.util import store_init_arguments | ||
from MDAnalysis.coordinates.base import StreamReaderBase | ||
|
||
|
||
from packaging.version import Version | ||
|
||
MIN_IMDCLIENT_VERSION = Version("0.1.4") | ||
|
||
try: | ||
import imdclient | ||
from imdclient.IMDClient import IMDClient | ||
hmacdope marked this conversation as resolved.
Show resolved
Hide resolved
|
||
except ImportError: | ||
HAS_IMDCLIENT = False | ||
imdclient_version = Version("0.0.0") | ||
|
||
# Allow building documentation without imdclient | ||
import types | ||
|
||
class MockIMDClient: | ||
pass | ||
imdclient = types.ModuleType("imdclient") | ||
imdclient.IMDClient = MockIMDClient | ||
imdclient.__version__ = "0.0.0" | ||
|
||
else: | ||
HAS_IMDCLIENT = True | ||
imdclient_version = Version(imdclient.__version__) | ||
|
||
# Check for compatibility: currently needs to be >=0.1.4 | ||
if imdclient_version < MIN_IMDCLIENT_VERSION: | ||
warnings.warn( | ||
f"imdclient version {imdclient_version} is too old; " | ||
f"need at least {imdclient_version}, Your installed version of " | ||
"imdclient will NOT be used.", | ||
category=RuntimeWarning, | ||
) | ||
HAS_IMDCLIENT = False | ||
|
||
logger = logging.getLogger("MDAnalysis.coordinates.IMDReader") | ||
|
||
|
||
class IMDReader(StreamReaderBase): | ||
hmacdope marked this conversation as resolved.
Show resolved
Hide resolved
|
||
""" | ||
Reader for IMD protocol packets. | ||
Parameters | ||
---------- | ||
filename : a string of the form "imd://host:port" where host is the hostname | ||
amruthesht marked this conversation as resolved.
Show resolved
Hide resolved
|
||
or IP address of the listening GROMACS server and port | ||
is the port number. | ||
n_atoms : int (optional) | ||
number of atoms in the system. defaults to number of atoms | ||
in the topology. Don't set this unless you know what you're doing. | ||
kwargs : dict (optional) | ||
keyword arguments passed to the constructed :class:`IMDClient` | ||
orbeckst marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
""" | ||
amruthesht marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
format = "IMD" | ||
one_pass = True | ||
hmacdope marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
||
@store_init_arguments | ||
def __init__( | ||
self, | ||
filename, | ||
convert_units=True, | ||
n_atoms=None, | ||
**kwargs, | ||
): | ||
if not HAS_IMDCLIENT: | ||
raise ImportError( | ||
"IMDReader requires the imdclient package. " | ||
"Please install it with 'pip install imdclient'." | ||
) | ||
|
||
super(IMDReader, self).__init__(filename, **kwargs) | ||
|
||
self._imdclient = None | ||
logger.debug("IMDReader initializing") | ||
|
||
if n_atoms is None: | ||
raise ValueError("IMDReader: n_atoms must be specified") | ||
self.n_atoms = n_atoms | ||
|
||
host, port = parse_host_port(filename) | ||
|
||
# This starts the simulation | ||
self._imdclient = IMDClient(host, port, n_atoms, **kwargs) | ||
|
||
imdsinfo = self._imdclient.get_imdsessioninfo() | ||
# NOTE: after testing phase, fail out on IMDv2 | ||
ljwoods2 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
||
self.ts = self._Timestep( | ||
self.n_atoms, | ||
positions=imdsinfo.positions, | ||
velocities=imdsinfo.velocities, | ||
forces=imdsinfo.forces, | ||
**self._ts_kwargs, | ||
) | ||
|
||
self._frame = -1 | ||
|
||
try: | ||
self._read_next_timestep() | ||
except StopIteration as e: | ||
raise RuntimeError("IMDReader: No data found in stream") from e | ||
|
||
def _read_frame(self, frame): | ||
|
||
try: | ||
imdf = self._imdclient.get_imdframe() | ||
except EOFError as e: | ||
raise e | ||
amruthesht marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
||
self._frame = frame | ||
self._load_imdframe_into_ts(imdf) | ||
|
||
logger.debug("IMDReader: Loaded frame %d", self._frame) | ||
return self.ts | ||
|
||
def _load_imdframe_into_ts(self, imdf): | ||
self.ts.frame = self._frame | ||
if imdf.time is not None: | ||
self.ts.time = imdf.time | ||
# NOTE: timestep.pyx "dt" method is suspicious bc it uses "new" keyword for a float | ||
amruthesht marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
self.ts.data["dt"] = imdf.dt | ||
orbeckst marked this conversation as resolved.
Show resolved
Hide resolved
|
||
self.ts.data["step"] = imdf.step | ||
orbeckst marked this conversation as resolved.
Show resolved
Hide resolved
|
||
if imdf.energies is not None: | ||
self.ts.data.update( | ||
orbeckst marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{k: v for k, v in imdf.energies.items() if k != "step"} | ||
) | ||
if imdf.box is not None: | ||
self.ts.dimensions = core.triclinic_box(*imdf.box) | ||
if imdf.positions is not None: | ||
# must call copy because reference is expected to reset | ||
# see 'test_frame_collect_all_same' in MDAnalysisTests.coordinates.base | ||
np.copyto(self.ts.positions, imdf.positions) | ||
orbeckst marked this conversation as resolved.
Show resolved
Hide resolved
|
||
if imdf.velocities is not None: | ||
np.copyto(self.ts.velocities, imdf.velocities) | ||
if imdf.forces is not None: | ||
np.copyto(self.ts.forces, imdf.forces) | ||
|
||
@staticmethod | ||
def _format_hint(thing): | ||
try: | ||
parse_host_port(thing) | ||
except: | ||
return False | ||
return HAS_IMDCLIENT and True | ||
|
||
def close(self): | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Above it says: \
Does that mean that if the IMDReader is not closed gracefully with this function that it will stay active and prevent another connection to the stream? I ask because this can be an issue with Jupyter notebooks where people are in the habit of restarting the kernel which will not close the IMDReader gracefully. This is an active issue I have with python interfacing with postgres There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Yes, the socket connection would saty active unless terminated properly. The Side Note: But technically it is possible to form multiple conenctions to the same port address. This is however limited by the host. Currently only NAMD supports this. But each connection has its seperate socket and stream of data which would need to be processed sperately by each client object seperately. The distinction is that these data streams may not always necessarily have the same data, depending on how the host has been configured. So, one can't make an independent copy on the same stream of data but can open a new connection while an existing connection is present (at least in NAMD). There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Add a note to the docs on best practices for using IMDReader in notebooks. Regarding connecting multiple streams to one MD engine port, mention that the behavior is MD engine implementation dependent (some may allow it, others may fail). There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I am moving the details on MD engine capability to the imdclient docs, so that there's only a single place Becksteinlab/imdclient#114 . I replaced the details with a link. (I also fixed the section level and rearranged where the warning is shown.) @jaclark5 please have a look an resolve if you're happy. |
||
"""Gracefully shut down the reader. Stops the producer thread.""" | ||
logger.debug("IMDReader close() called") | ||
if self._imdclient is not None: | ||
self._imdclient.stop() | ||
# NOTE: removeme after testing | ||
logger.debug("IMDReader shut down gracefully.") | ||
amruthesht marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
||
# NOTE: think of other edge cases as well- should be robust | ||
def parse_host_port(filename): | ||
hmacdope marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
if not filename.startswith("imd://"): | ||
raise ValueError("IMDReader: URL must be in the format 'imd://host:port'") | ||
# Check if the format is correct | ||
parts = filename.split("imd://")[1].split(":") | ||
if len(parts) == 2: | ||
host = parts[0] | ||
try: | ||
port = int(parts[1]) | ||
return (host, port) | ||
except ValueError as e: | ||
raise ValueError("IMDReader: Port must be an integer") from e | ||
else: | ||
raise ValueError("IMDReader: URL must be in the format 'imd://host:port'") |
Uh oh!
There was an error while loading. Please reload this page.