Skip to content

Commit a28c735

Browse files
Update doc strings (#72)
* Update doc strings * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Apply suggestion from @hannahbaumann * Apply suggestion from @hannahbaumann * address review comments * address review comments * update make_Universe --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
1 parent 3cbc61d commit a28c735

4 files changed

Lines changed: 140 additions & 47 deletions

File tree

‎src/openfe_analysis/reader.py‎

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,17 +13,18 @@
1313

1414
def _determine_iteration_dt(dataset) -> float:
1515
"""
16-
Find out the timestep between each frame in the trajectory.
16+
Determine the time increment between successive iterations
17+
in a MultiStateReporter trajectory.
1718
1819
Parameters
1920
----------
2021
dataset : nc.Dataset
21-
Dataset holding the MultiStateReporter generated NetCDF file.
22+
NetCDF dataset produced by ``openmmtools.multistate.MultiStateReporter``.
2223
2324
Returns
2425
-------
2526
float
26-
The timestep in units of picoseconds.
27+
The time between successive iterations, in picoseconds.
2728
2829
Raises
2930
------
@@ -35,7 +36,8 @@ def _determine_iteration_dt(dataset) -> float:
3536
-----
3637
This assumes an MCMC move which serializes in a manner similar
3738
to `openmmtools.mcmc.LangevinDynamicsMove`, i.e. it must have
38-
both a `timestep` and `n_steps` defined.
39+
both a `timestep` and `n_steps` defined, such that
40+
dt_iteration = n_steps * timestep
3941
"""
4042
# Deserialize the MCMC move information for the 0th entry.
4143
mcmc_move_data = yaml.load(
@@ -149,16 +151,31 @@ def index_method(self) -> str:
149151

150152
@staticmethod
151153
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+
"""
152167
with nc.Dataset(filename) as ds:
153168
n_atoms = ds.dimensions["atom"].size
154169
return n_atoms
155170

156171
def _read_next_timestep(self, ts=None) -> Timestep:
172+
# Advance the trajectory by one frame.
157173
if (self._frame_index + 1) >= len(self):
158174
raise EOFError
159175
return self._read_frame(self._frame_index + 1)
160176

161177
def _read_frame(self, frame: int) -> Timestep:
178+
# Read a single trajectory frame.
162179
self._frame_index = frame
163180

164181
frame = self._frames[self._frame_index]
@@ -197,6 +214,7 @@ def _read_frame(self, frame: int) -> Timestep:
197214

198215
@property
199216
def dt(self) -> float:
217+
# Time difference between successive trajectory frames.
200218
return self._dt
201219

202220
def _reopen(self):

‎src/openfe_analysis/rmsd.py‎

Lines changed: 72 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -16,22 +16,48 @@
1616

1717

1818
def make_Universe(top: pathlib.Path, trj: nc.Dataset, state: int) -> mda.Universe:
19-
"""Makes a Universe and applies some transformations
19+
"""
20+
Construct an MDAnalysis Universe from a MultiState NetCDF trajectory
21+
and apply standard analysis transformations.
22+
23+
The Universe is created using the custom ``FEReader`` to extract a
24+
single state from a multistate simulation.
25+
26+
Parameters
27+
----------
28+
top : pathlib.Path or Topology
29+
Path to a topology file (e.g. PDB) or an already-loaded MDAnalysis
30+
topology object.
31+
trj : nc.Dataset
32+
Open NetCDF dataset produced by
33+
``openmmtools.multistate.MultiStateReporter``.
34+
state : int
35+
Thermodynamic state index to extract from the multistate trajectory.
36+
37+
Returns
38+
-------
39+
MDAnalysis.Universe
40+
A Universe with trajectory transformations applied.
2041
42+
Notes
43+
-----
2144
Identifies two AtomGroups:
2245
- protein, defined as having standard amino acid names, then filtered
2346
down to CA
2447
- ligand, defined as resname UNK
2548
26-
Then applies some transformations.
49+
Depending on whether a protein is present, a sequence of trajectory
50+
transformations is applied:
2751
2852
If a protein is present:
29-
- prevents the protein from jumping between periodic images
30-
- moves the ligand to the image closest to the protein
31-
- aligns the entire system to minimise the protein RMSD
32-
33-
If only a ligand:
34-
- prevents the ligand from jumping between periodic images
53+
- Unwraps protein and ligand atom to be made whole
54+
- Shifts protein chains and the ligand to the image closest to the first
55+
protein chain (:class:`ClosestImageShift`)
56+
- Aligns the entire system to minimise the protein RMSD (:class:`Aligner`)
57+
58+
If only a ligand is present:
59+
- Prevents the ligand from jumping between periodic images
60+
- Aligns the ligand to minimize its RMSD
3561
"""
3662
u = mda.Universe(
3763
top,
@@ -76,23 +102,39 @@ def make_Universe(top: pathlib.Path, trj: nc.Dataset, state: int) -> mda.Univers
76102
def gather_rms_data(
77103
pdb_topology: pathlib.Path, dataset: pathlib.Path, skip: Optional[int] = None
78104
) -> dict[str, list[float]]:
79-
"""Generate structural analysis of RBFE simulation
105+
"""
106+
Compute structural RMSD-based metrics for a multistate BFE simulation.
80107
81108
Parameters
82109
----------
83110
pdb_topology : pathlib.Path
84-
path to pdb topology
111+
Path to the PDB file defining system topology.
85112
dataset : pathlib.Path
86-
path to nc trajectory
113+
Path to the NetCDF trajectory file produced by a multistate simulation.
87114
skip : int, optional
88-
step at which to progress through the trajectory. by default, selects a
89-
step that produces roughly 500 frames of analysis per replicate
90-
91-
Produces, for each lambda state:
92-
- 1D protein RMSD timeseries 'protein_RMSD'
93-
- ligand RMSD timeseries
94-
- ligand COM motion 'ligand_wander'
95-
- 2D protein RMSD plot
115+
Frame stride for analysis. If ``None``, a stride is chosen such that
116+
approximately 500 frames are analyzed per state.
117+
118+
Returns
119+
-------
120+
dict[str, list]
121+
Dictionary containing per-state analysis results with keys:
122+
``protein_RMSD``, ``ligand_RMSD``, ``ligand_wander``,
123+
``protein_2D_RMSD``, and ``time(ps)``.
124+
125+
Notes
126+
-----
127+
For each thermodynamic state (lambda), this function:
128+
- Loads the trajectory using ``FEReader``
129+
- Applies standard PBC-handling and alignment transformations
130+
- Computes protein and ligand structural metrics over time
131+
132+
The following analyses are produced per state:
133+
- 1D protein CA RMSD time series
134+
- 1D ligand RMSD time series
135+
- Ligand center-of-mass displacement from its initial position
136+
(``ligand_wander``)
137+
- Flattened 2D protein RMSD matrix (pairwise RMSD between frames)
96138
"""
97139
output = {
98140
"protein_RMSD": [],
@@ -187,19 +229,25 @@ def gather_rms_data(
187229

188230

189231
def twoD_RMSD(positions, w: Optional[npt.NDArray]) -> list[float]:
190-
"""2 dimensions RMSD
232+
"""
233+
Compute a flattened 2D RMSD matrix from a trajectory.
234+
235+
For all unique frame pairs ``(i, j)`` with ``i < j``, this function
236+
computes the RMSD between atomic coordinates after optimal alignment.
191237
192238
Parameters
193239
----------
194240
positions : np.ndarray
195-
the protein positions for the entire trajectory
241+
Atomic coordinates for all frames in the trajectory.
196242
w : np.ndarray, optional
197-
weights array
243+
Per-atom weights to use in the RMSD calculation. If ``None``,
244+
all atoms are weighted equally.
198245
199246
Returns
200247
-------
201-
rmsd_matrix : list
202-
a flattened version of the 2d
248+
list of float
249+
Flattened list of RMSD values corresponding to all frame pairs
250+
``(i, j)`` with ``i < j``.
203251
"""
204252
nframes, _, _ = positions.shape
205253

‎src/openfe_analysis/transformations.py‎

Lines changed: 34 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,26 @@
1414

1515

1616
class NoJump(TransformationBase):
17-
"""Stops an AtomGroup from moving more than half a box length between frames
18-
19-
This transformation prevents an AtomGroup "teleporting" across the box
20-
border between two subsequent frames. This then simplifies the calculation
21-
of motion over time.
17+
"""
18+
Prevent an AtomGroup from jumping between periodic images.
19+
This transformation removes large apparent
20+
COM displacements caused by periodic boundary conditions.
21+
22+
Parameters
23+
----------
24+
ag : MDAnalysis.AtomGroup
25+
AtomGroup whose center-of-mass motion should be made continuous.
26+
27+
Notes
28+
-----
29+
- This transformation assumes an orthorhombic unit cell.
30+
- Only translations are applied; no rotations or scaling.
31+
- The correction is based on center-of-mass motion and is therefore
32+
most appropriate for compact groups (e.g. proteins, ligands).
33+
- Must be applied before any alignment transformations to avoid
34+
mixing reference frames.
35+
- Is intended to be applied before analyses that rely on smooth
36+
time evolution (e.g. RMSD, COM motion).
2237
"""
2338

2439
ag: mda.AtomGroup
@@ -49,12 +64,13 @@ class ClosestImageShift(TransformationBase):
4964
"""
5065
PBC-safe transformation that shifts one or more target AtomGroups
5166
so that their COM is in the closest image relative to a reference AtomGroup.
52-
Works for any box type (triclinic or orthorhombic).
5367
54-
CAVEAT:
55-
This Transformation requires the AtomGroups to be unwrapped!
68+
CAVEAT: This Transformation requires the AtomGroups to be unwrapped!
5669
57-
Inspired from:
70+
Notes
71+
-----
72+
- Works for any box type (triclinic or orthorhombic).
73+
- Inspired from:
5874
https://github.com/wolberlab/OpenMMDL/blob/main/openmmdl/openmmdl_simulation/scripts/post_md_conversions.py
5975
"""
6076

@@ -75,10 +91,15 @@ def _transform(self, ts):
7591

7692

7793
class Aligner(TransformationBase):
78-
"""On-the-fly transformation to align a trajectory to minimise RMSD
79-
80-
centers all coordinates onto origin
81-
rotates **entire universe** to minimise rmsd relative to **ref_ag**
94+
"""
95+
Align a trajectory to a reference AtomGroup by minimizing RMSD.
96+
97+
Notes
98+
-----
99+
Performs an on-the-fly least-squares alignment
100+
of the entire universe to a reference AtomGroup.
101+
At each frame, the coordinates are translated and rotated to minimize the
102+
RMSD of the atoms relative to their positions in the reference.
82103
"""
83104

84105
ref_pos: npt.NDArray

‎src/openfe_analysis/utils/multistate.py‎

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,11 @@ def _determine_position_indices(dataset: nc.Dataset) -> NDArray:
2424
indices : NDArray[int]
2525
An ordered array of iteration indices which hold positions.
2626
27+
Raises
28+
------
29+
ValueError
30+
If positions are not written at a consistent interval.
31+
2732
Note
2833
----
2934
This assumes that the indices are equally spaced by a given
@@ -55,11 +60,12 @@ def _determine_position_indices(dataset: nc.Dataset) -> NDArray:
5560

5661

5762
def _state_to_replica(dataset: nc.Dataset, state_num: int, frame_num: int) -> int:
58-
"""Convert a state index to replica index at a given Dataset frame
63+
"""
64+
Map a thermodynamic state index to the corresponding replica index.
5965
6066
Parameters
6167
----------
62-
dataset : netCDF4.Dataset
68+
dataset : nc.Dataset
6369
Dataset containing the MultiState reporter generated NetCDF file
6470
with information about all the frames and replica in the system.
6571
state_num : int
@@ -86,7 +92,7 @@ def _replica_positions_at_frame(
8692
8793
Parameters
8894
----------
89-
dataset : netCDF4.Dataset
95+
dataset : nc.Dataset
9096
Dataset containing the MultiState information.
9197
replica_index : int
9298
Replica index to extract positions for.
@@ -125,7 +131,7 @@ def _create_new_dataset(filename: Path, n_atoms: int, title: str) -> nc.Dataset:
125131
126132
Returns
127133
-------
128-
netCDF4.Dataset
134+
nc.Dataset
129135
AMBER Conventions compliant NetCDF dataset to store information
130136
contained in MultiState reporter generated NetCDF file.
131137
"""
@@ -170,13 +176,13 @@ def _get_unitcell(
170176
dataset: nc.Dataset, replica_index: int, frame_num: int
171177
) -> Optional[Tuple[unit.Quantity]]:
172178
"""
173-
Helper method to extract a unit cell from the stored
179+
Helper method to extract unit cell dimensions from the stored
174180
box vectors in a MultiState reporter generated NetCDF file
175181
at a given state and Dataset frame.
176182
177183
Parameters
178184
----------
179-
dataset : netCDF4.Dataset
185+
dataset : nc.Dataset
180186
Dataset of MultiState reporter generated NetCDF file.
181187
replica_index : int
182188
Replica for which to get the unit cell for.

0 commit comments

Comments
 (0)