openfe-analysis 0.6.0.post1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. openfe_analysis/__init__.py +8 -0
  2. openfe_analysis/_version.py +24 -0
  3. openfe_analysis/reader.py +227 -0
  4. openfe_analysis/restraints.py +92 -0
  5. openfe_analysis/rmsd.py +372 -0
  6. openfe_analysis/tests/conftest.py +105 -0
  7. openfe_analysis/tests/data/__init__.py +0 -0
  8. openfe_analysis/tests/test_gather_rms_data.py +94 -0
  9. openfe_analysis/tests/test_reader.py +185 -0
  10. openfe_analysis/tests/test_restraints.py +75 -0
  11. openfe_analysis/tests/test_rmsd_classes.py +291 -0
  12. openfe_analysis/tests/test_transformations.py +86 -0
  13. openfe_analysis/tests/utils/__init__.py +0 -0
  14. openfe_analysis/tests/utils/test_apply_transformations.py +142 -0
  15. openfe_analysis/tests/utils/test_multistate.py +220 -0
  16. openfe_analysis/tests/utils/test_plotting.py +46 -0
  17. openfe_analysis/tests/utils/test_serialization.py +43 -0
  18. openfe_analysis/tests/utils/test_universe_utils.py +81 -0
  19. openfe_analysis/transformations.py +131 -0
  20. openfe_analysis/utils/__init__.py +0 -0
  21. openfe_analysis/utils/apply_transformations.py +115 -0
  22. openfe_analysis/utils/multistate.py +293 -0
  23. openfe_analysis/utils/plotting.py +139 -0
  24. openfe_analysis/utils/serialization.py +50 -0
  25. openfe_analysis/utils/universe_utils.py +122 -0
  26. openfe_analysis-0.6.0.post1.dist-info/METADATA +74 -0
  27. openfe_analysis-0.6.0.post1.dist-info/RECORD +31 -0
  28. openfe_analysis-0.6.0.post1.dist-info/WHEEL +5 -0
  29. openfe_analysis-0.6.0.post1.dist-info/entry_points.txt +2 -0
  30. openfe_analysis-0.6.0.post1.dist-info/licenses/LICENSE +21 -0
  31. openfe_analysis-0.6.0.post1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,8 @@
1
+ from ._version import __version__ # isort: skip
2
+ from . import rmsd
3
+ from .reader import FEReader
4
+ from .transformations import (
5
+ Aligner,
6
+ ClosestImageShift,
7
+ NoJump,
8
+ )
@@ -0,0 +1,24 @@
1
+ # file generated by vcs-versioning
2
+ # don't change, don't track in version control
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "__version__",
7
+ "__version_tuple__",
8
+ "version",
9
+ "version_tuple",
10
+ "__commit_id__",
11
+ "commit_id",
12
+ ]
13
+
14
+ version: str
15
+ __version__: str
16
+ __version_tuple__: tuple[int | str, ...]
17
+ version_tuple: tuple[int | str, ...]
18
+ commit_id: str | None
19
+ __commit_id__: str | None
20
+
21
+ __version__ = version = '0.6.0.post1'
22
+ __version_tuple__ = version_tuple = (0, 6, 0, 'post1')
23
+
24
+ __commit_id__ = commit_id = None
@@ -0,0 +1,227 @@
1
+ import pathlib
2
+ from typing import Literal, Optional
3
+
4
+ import netCDF4 as nc
5
+ import numpy as np
6
+ import yaml
7
+ from MDAnalysis.coordinates.base import ReaderBase, Timestep
8
+ from openff.units import unit
9
+
10
+ from openfe_analysis.utils import multistate, serialization
11
+ from openfe_analysis.utils.multistate import _determine_position_indices
12
+
13
+
14
+ def _determine_iteration_dt(dataset) -> float:
15
+ """
16
+ Determine the time increment between successive iterations
17
+ in a MultiStateReporter trajectory.
18
+
19
+ Parameters
20
+ ----------
21
+ dataset : nc.Dataset
22
+ NetCDF dataset produced by ``openmmtools.multistate.MultiStateReporter``.
23
+
24
+ Returns
25
+ -------
26
+ float
27
+ The time between successive iterations, in picoseconds.
28
+
29
+ Raises
30
+ ------
31
+ KeyError
32
+ If either `timestep` or `n_steps` cannot be found in the
33
+ zeroth MCMC move.
34
+
35
+ Notes
36
+ -----
37
+ This assumes an MCMC move which serializes in a manner similar
38
+ to `openmmtools.mcmc.LangevinDynamicsMove`, i.e. it must have
39
+ both a `timestep` and `n_steps` defined, such that
40
+ dt_iteration = n_steps * timestep
41
+ """
42
+ # Deserialize the MCMC move information for the 0th entry.
43
+ mcmc_move_data = yaml.load(
44
+ dataset.groups["mcmc_moves"]["move0"][0],
45
+ Loader=serialization.UnitedYamlLoader,
46
+ )
47
+
48
+ try:
49
+ dt = mcmc_move_data["n_steps"] * mcmc_move_data["timestep"]
50
+ except KeyError:
51
+ msg = "Either `n_steps` or `timestep` are missing from the MCMC move"
52
+ raise KeyError(msg)
53
+
54
+ return dt.to("picosecond").m
55
+
56
+
57
+ class FEReader(ReaderBase):
58
+ """
59
+ MDAnalysis Reader for NetCDF files created by
60
+ `openmmtools.multistate.MultiStateReporter`
61
+
62
+ Provides a 1D trajectory along either:
63
+
64
+ - constant Hamiltonian state (`index_method="state"`)
65
+ - constant replica (`index_method="replica"`)
66
+
67
+ selected via the `index` argument.
68
+ """
69
+
70
+ _multistate_index: int
71
+ _index_method: str
72
+ _frame_index: int
73
+ _dataset: nc.Dataset
74
+ _dataset_owner: bool
75
+
76
+ format = "MultiStateReporter"
77
+
78
+ units = {"time": "ps", "length": "nanometer"}
79
+
80
+ def __init__(
81
+ self,
82
+ filename: str | pathlib.Path | nc.Dataset,
83
+ *,
84
+ index: int,
85
+ index_method: Literal["state", "replica"] = "state",
86
+ convert_units: bool = True,
87
+ **kwargs,
88
+ ):
89
+ """
90
+ Parameters
91
+ ----------
92
+ filename : pathlike or nc.Dataset
93
+ Path to the .nc file or an open Dataset.
94
+ index : int
95
+ Index of the state or replica to extract. May be negative.
96
+ index_method : {"state", "replica"}, default "state"
97
+ Whether `index` refers to a Hamiltonian state or a replica.
98
+ convert_units : bool
99
+ Convert positions to Angstrom.
100
+ """
101
+ super().__init__(filename, convert_units, **kwargs)
102
+
103
+ if isinstance(filename, nc.Dataset):
104
+ self._dataset = filename
105
+ self._dataset_owner = False
106
+ else:
107
+ self._dataset = nc.Dataset(filename)
108
+ self._dataset_owner = True
109
+
110
+ if index_method not in {"state", "replica"}:
111
+ raise ValueError(f"index_method must be 'state' or 'replica', got {index_method}")
112
+
113
+ self._index_method = index_method
114
+
115
+ # Handle the negative ID case
116
+ if index_method == "state":
117
+ size = self._dataset.dimensions["state"].size
118
+ else:
119
+ size = self._dataset.dimensions["replica"].size
120
+
121
+ self._multistate_index = index % size
122
+
123
+ self._n_atoms = self._dataset.dimensions["atom"].size
124
+ self.ts = Timestep(self._n_atoms)
125
+ self._frames = _determine_position_indices(self._dataset)
126
+ # The MDAnalysis trajectory "dt" is the iteration dt
127
+ # multiplied by the number of iterations between frames.
128
+ self._dt = _determine_iteration_dt(self._dataset) * np.diff(self._frames)[0]
129
+ self._read_frame(0)
130
+
131
+ @staticmethod
132
+ def _format_hint(thing) -> bool:
133
+ # can pass raw nc datasets through to reduce open/close operations
134
+ return isinstance(thing, nc.Dataset)
135
+
136
+ @property
137
+ def multistate_index(self) -> int:
138
+ return self._multistate_index
139
+
140
+ @property
141
+ def n_atoms(self) -> int:
142
+ return self._n_atoms
143
+
144
+ @property
145
+ def n_frames(self) -> int:
146
+ return len(self._frames)
147
+
148
+ @property
149
+ def index_method(self) -> str:
150
+ return self._index_method
151
+
152
+ @staticmethod
153
+ def parse_n_atoms(filename, **kwargs) -> int:
154
+ """
155
+ Determine the number of atoms stored in a MultiStateReporter NetCDF file.
156
+
157
+ Parameters
158
+ ----------
159
+ filename : path-like
160
+ Path to the NetCDF file.
161
+
162
+ Returns
163
+ -------
164
+ int
165
+ Number of atoms in the system.
166
+ """
167
+ with nc.Dataset(filename) as ds:
168
+ n_atoms = ds.dimensions["atom"].size
169
+ return n_atoms
170
+
171
+ def _read_next_timestep(self, ts=None) -> Timestep:
172
+ # Advance the trajectory by one frame.
173
+ if (self._frame_index + 1) >= len(self):
174
+ raise EOFError
175
+ return self._read_frame(self._frame_index + 1)
176
+
177
+ def _read_frame(self, frame: int) -> Timestep:
178
+ # Read a single trajectory frame.
179
+ self._frame_index = frame
180
+
181
+ frame = self._frames[self._frame_index]
182
+
183
+ if self._index_method == "state":
184
+ rep = multistate._state_to_replica(
185
+ self._dataset,
186
+ self._multistate_index,
187
+ frame,
188
+ )
189
+ else:
190
+ rep = self._multistate_index
191
+
192
+ pos = multistate._replica_positions_at_frame(self._dataset, rep, frame)
193
+ dim = multistate._get_unitcell(self._dataset, rep, frame)
194
+
195
+ if pos is None:
196
+ errmsg = (
197
+ "NetCDF dataset frame without positions was accessed "
198
+ "this likely indicates that the reader failed to work out "
199
+ "the write frequency and there is a deeper issue with how "
200
+ "this file was written."
201
+ )
202
+ raise RuntimeError(errmsg)
203
+
204
+ # Convert to base MDAnalysis distance units (Angstrom) if requested
205
+ if self.convert_units:
206
+ self.ts.positions = (pos.to(unit.angstrom)).m
207
+ else:
208
+ self.ts.positions = pos.m
209
+ self.ts.dimensions = dim
210
+ self.ts.frame = self._frame_index
211
+ self.ts.time = self._frame_index * self._dt
212
+
213
+ return self.ts
214
+
215
+ @property
216
+ def dt(self) -> float:
217
+ # Time difference between successive trajectory frames.
218
+ return self._dt
219
+
220
+ def _reopen(self):
221
+ self._frame_index = -1
222
+
223
+ def close(self):
224
+ if self._dataset is not None:
225
+ if self._dataset_owner:
226
+ self._dataset.close()
227
+ self._dataset = None
@@ -0,0 +1,92 @@
1
+ import MDAnalysis as mda
2
+ import numpy as np
3
+ from MDAnalysis.analysis.base import AnalysisBase
4
+
5
+
6
+ class BoreschRestraintAnalysis(AnalysisBase):
7
+ """
8
+ Boresch restraint geometry (bond, 2 angles, 3 dihedrals) time series.
9
+
10
+ Parameters
11
+ ----------
12
+ atomgroup : mda.AtomGroup
13
+ Exactly 6 atoms, ordered [H0, H1, H2, G0, G1, G2] (host atoms then
14
+ guest atoms), matching the atom ordering used by
15
+ ``openfe.protocols.restraint_utils.geometry.boresch``.
16
+
17
+ Raises
18
+ ------
19
+ ValueError
20
+ If ``atomgroup`` does not contain exactly 6 atoms.
21
+
22
+ Notes
23
+ -----
24
+ Bond length is reported in Angstrom; angles and dihedrals are reported
25
+ in radians, matching the units returned by MDAnalysis's
26
+ ``calc_bonds``/``calc_angles``/``calc_dihedrals``. Reported quantities
27
+ are, in order: the H0-G0 bond, the H1-H0-G0 and H0-G0-G1 angles, and the
28
+ H2-H1-H0-G0, H1-H0-G0-G1, and H0-G0-G1-G2 dihedrals.
29
+ """
30
+
31
+ _analysis_algorithm_is_parallelizable = False
32
+
33
+ def __init__(self, atomgroup: mda.AtomGroup, **kwargs):
34
+ super().__init__(atomgroup.universe.trajectory, **kwargs)
35
+ if len(atomgroup) != 6:
36
+ raise ValueError(
37
+ f"atomgroup must contain exactly 6 atoms (3 host + 3 guest), got {len(atomgroup)}."
38
+ )
39
+ self._ag = atomgroup
40
+
41
+ def _prepare(self) -> None:
42
+ self.results.bond = np.zeros(self.n_frames, dtype=np.float64)
43
+ self.results.angle1 = np.zeros(self.n_frames, dtype=np.float64)
44
+ self.results.angle2 = np.zeros(self.n_frames, dtype=np.float64)
45
+ self.results.dihedral1 = np.zeros(self.n_frames, dtype=np.float64)
46
+ self.results.dihedral2 = np.zeros(self.n_frames, dtype=np.float64)
47
+ self.results.dihedral3 = np.zeros(self.n_frames, dtype=np.float64)
48
+
49
+ def _single_frame(self) -> None:
50
+ atoms = self._ag.atoms
51
+ box = self._ag.dimensions
52
+
53
+ self.results.bond[self._frame_index] = mda.lib.distances.calc_bonds(
54
+ atoms[0].position,
55
+ atoms[3].position,
56
+ box=box,
57
+ )
58
+
59
+ self.results.angle1[self._frame_index] = mda.lib.distances.calc_angles(
60
+ atoms[1].position,
61
+ atoms[0].position,
62
+ atoms[3].position,
63
+ box=box,
64
+ )
65
+ self.results.angle2[self._frame_index] = mda.lib.distances.calc_angles(
66
+ atoms[0].position,
67
+ atoms[3].position,
68
+ atoms[4].position,
69
+ box=box,
70
+ )
71
+
72
+ self.results.dihedral1[self._frame_index] = mda.lib.distances.calc_dihedrals(
73
+ atoms[2].position,
74
+ atoms[1].position,
75
+ atoms[0].position,
76
+ atoms[3].position,
77
+ box=box,
78
+ )
79
+ self.results.dihedral2[self._frame_index] = mda.lib.distances.calc_dihedrals(
80
+ atoms[1].position,
81
+ atoms[0].position,
82
+ atoms[3].position,
83
+ atoms[4].position,
84
+ box=box,
85
+ )
86
+ self.results.dihedral3[self._frame_index] = mda.lib.distances.calc_dihedrals(
87
+ atoms[0].position,
88
+ atoms[3].position,
89
+ atoms[4].position,
90
+ atoms[5].position,
91
+ box=box,
92
+ )