1616from __future__ import annotations
1717
1818import logging
19- import math
2019from collections import defaultdict
2120from collections .abc import Mapping
22- from dataclasses import dataclass
2321from typing import Any
2422
2523import pandas as pd
2927from CodeEntropy .entropy .water import WaterEntropy
3028from CodeEntropy .levels .hierarchy import HierarchyBuilder
3129from CodeEntropy .levels .level_dag import LevelDAG
30+ from CodeEntropy .trajectory .frames import FrameSelection
31+ from CodeEntropy .trajectory .source import FrameSource
3232
3333logger = logging .getLogger (__name__ )
3434console = LoggingConfig .get_console ()
3535
3636SharedData = dict [str , Any ]
3737
3838
39- @dataclass (frozen = True )
40- class TrajectorySlice :
41- """Trajectory slicing parameters.
42-
43- Attributes:
44- start: Inclusive start frame index.
45- end: Exclusive end frame index (or a concrete index derived from args).
46- step: Step size between frames.
47- n_frames: Number of frames in the slice.
48- """
49-
50- start : int
51- end : int
52- step : int
53- n_frames : int
54-
55-
5639class EntropyWorkflow :
5740 """Coordinate entropy calculations across structural levels.
5841
@@ -95,21 +78,22 @@ def execute(self) -> None:
9578 """Run the full entropy workflow and emit results.
9679
9780 This orchestrates the complete entropy pipeline:
98- 1. Build trajectory slice .
99- 2. Apply atom and frame selection to create a reduced universe.
81+ 1. Build trajectory frame selection .
82+ 2. Apply atom/ frame selection to create the current analysis universe.
10083 3. Detect hierarchy levels.
10184 4. Group molecules.
10285 5. Split groups into water and non-water.
103- 6. Optionally compute water entropy (only if solute exists) .
86+ 6. Optionally compute water entropy.
10487 7. Run level DAG and entropy graph.
10588 8. Finalize and persist results.
10689 """
107- traj = self ._build_trajectory_slice ()
90+ frame_selection = self ._build_frame_selection ()
10891 console .print (
109- f"Analyzing a total of { traj .n_frames } frames in this calculation."
92+ f"Analyzing a total of { frame_selection .n_frames } "
93+ f"frames in this calculation."
11094 )
11195
112- reduced_universe = self ._build_reduced_universe ()
96+ reduced_universe = self ._build_reduced_universe (frame_selection )
11397
11498 levels = self ._detect_levels (reduced_universe )
11599 groups = self ._group_molecules .grouping_molecules (
@@ -121,15 +105,15 @@ def execute(self) -> None:
121105 )
122106
123107 if self ._args .water_entropy and water_groups and nonwater_groups :
124- self ._compute_water_entropy (traj , water_groups )
108+ self ._compute_water_entropy (frame_selection , water_groups )
125109 else :
126110 nonwater_groups .update (water_groups )
127111
128112 shared_data = self ._build_shared_data (
129113 reduced_universe = reduced_universe ,
130114 levels = levels ,
131115 groups = nonwater_groups ,
132- traj = traj ,
116+ frame_selection = frame_selection ,
133117 )
134118
135119 with self ._reporter .progress (transient = False ) as p :
@@ -139,24 +123,47 @@ def execute(self) -> None:
139123 self ._finalize_molecule_results ()
140124 self ._reporter .log_tables ()
141125
126+ def _build_frame_selection (self ) -> FrameSelection :
127+ """Build the workflow frame selection.
128+
129+ Returns:
130+ FrameSelection containing absolute source-trajectory frame indices.
131+
132+ Notes:
133+ Physical frame slicing is not used. The selected frame indices are the
134+ global workflow frame contract and are consumed by FrameSource.
135+ """
136+ start , end , step = self ._get_trajectory_bounds ()
137+ return FrameSelection .from_bounds (
138+ start = start ,
139+ stop = end ,
140+ step = step ,
141+ )
142+
142143 def _build_shared_data (
143144 self ,
144145 reduced_universe : Any ,
145146 levels : Any ,
146147 groups : Mapping [int , Any ],
147- traj : TrajectorySlice ,
148+ frame_selection : FrameSelection ,
148149 ) -> SharedData :
149150 """Build the shared_data dict used by nodes and graphs.
150151
151152 Args:
152- reduced_universe: Universe after applying selection.
153+ reduced_universe: Active analysis universe after atom selection.
154+ The trajectory is not physically frame-sliced.
153155 levels: Level definition per molecule id.
154- groups: Mapping of group id -> list of molecule ids.
155- traj: Trajectory slice parameters .
156+ groups: Mapping of group id to molecule ids.
157+ frame_selection: Explicit absolute workflow frame selection .
156158
157159 Returns:
158160 Shared data dictionary for DAG/graph execution.
159161 """
162+ frame_source = FrameSource (
163+ universe = reduced_universe ,
164+ selection = frame_selection ,
165+ )
166+
160167 shared_data : SharedData = {
161168 "entropy_manager" : self ,
162169 "run_manager" : self ._run_manager ,
@@ -166,10 +173,14 @@ def _build_shared_data(
166173 "reduced_universe" : reduced_universe ,
167174 "levels" : levels ,
168175 "groups" : dict (groups ),
169- "start" : traj .start ,
170- "end" : traj .end ,
171- "step" : traj .step ,
172- "n_frames" : traj .n_frames ,
176+ "start" : frame_selection .source_start ,
177+ "end" : frame_selection .source_stop_exclusive ,
178+ "step" : frame_selection .infer_source_step (),
179+ "n_frames" : frame_selection .n_frames ,
180+ "frame_selection" : frame_selection ,
181+ "frame_source" : frame_source ,
182+ "frame_indices" : list (frame_selection .indices ),
183+ "source_frame_indices" : list (frame_selection .indices ),
173184 }
174185 return shared_data
175186
@@ -198,66 +209,56 @@ def _run_entropy_graph(
198209 entropy_results = EntropyGraph ().build ().execute (shared_data , progress = progress )
199210 shared_data .update (entropy_results )
200211
201- def _build_trajectory_slice (self ) -> TrajectorySlice :
202- """Compute trajectory slicing parameters from args.
212+ def _get_trajectory_bounds (self ) -> tuple [ int , int , int ] :
213+ """Return validated start, end, and step frame indices from args.
203214
204215 Returns:
205- A TrajectorySlice describing the frames to analyze.
216+ Tuple of ``(start, end, step)``.
217+
218+ Raises:
219+ ValueError: If the frame window is invalid.
206220 """
207- start , end , step = self ._get_trajectory_bounds ()
208- n_frames = self ._get_number_frames (start , end , step )
209- return TrajectorySlice (start = start , end = end , step = step , n_frames = n_frames )
221+ n_total = len (self ._universe .trajectory )
210222
211- def _get_trajectory_bounds (self ) -> tuple [int , int , int ]:
212- """Return start, end, and step frame indices from args.
223+ start = 0 if self ._args .start is None else int (self ._args .start )
224+ end = (
225+ n_total
226+ if self ._args .end is None or int (self ._args .end ) == - 1
227+ else int (self ._args .end )
228+ )
229+ step = 1 if self ._args .step is None else int (self ._args .step )
213230
214- Returns:
215- Tuple of (start, end, step).
216- """
217- start = self ._args .start or 0
218- end = len (self ._universe .trajectory ) if self ._args .end == - 1 else self ._args .end
219- step = self ._args .step or 1
220231 return start , end , step
221232
222- def _get_number_frames (self , start : int , end : int , step : int ) -> int :
223- """Compute the number of frames in a trajectory slice .
233+ def _build_reduced_universe (self , frame_selection : FrameSelection ) -> Any :
234+ """Apply atom selection and return the active analysis universe .
224235
225236 Args:
226- start: Inclusive start frame index.
227- end: Exclusive end frame index.
228- step: Step between frames.
237+ frame_selection: Workflow frame selection. Used for validation.
229238
230239 Returns:
231- Number of frames processed.
232- """
233- return math .floor ((end - start ) / step )
240+ MDAnalysis Universe after atom selection. Frames are not physically
241+ sliced; selected-frame access is handled by FrameSource.
234242
235- def _build_reduced_universe (self ) -> Any :
236- """Apply atom and frame selection and return the reduced universe.
237-
238- Returns:
239- MDAnalysis Universe (reduced according to user selections).
243+ Raises:
244+ ValueError: If no frames are selected.
240245 """
246+ if frame_selection .n_frames == 0 :
247+ raise ValueError ("Frame selection is empty." )
248+
241249 selection = self ._args .selection_string
242- start = self ._args .start
243- end = len (self ._universe .trajectory ) if self ._args .end == - 1 else self ._args .end
244- step = self ._args .step
250+
245251 if selection == "all" :
246- reduced_atoms = self ._universe
247- else :
248- reduced_atoms = self ._universe_operations .select_atoms (
249- self ._universe , selection
250- )
251- name = f"{ len (reduced_atoms .trajectory )} _frame_dump_atom_selection"
252- self ._run_manager .write_universe (reduced_atoms , name )
252+ return self ._universe
253253
254- reduced_frames = self ._universe_operations .select_frames (
255- reduced_atoms , start , end , step
254+ reduced_atoms = self ._universe_operations .select_atoms (
255+ self ._universe ,
256+ selection ,
256257 )
257- name = f"{ len (reduced_frames .trajectory )} _frame_dump_frame_selection "
258- self ._run_manager .write_universe (reduced_frames , name )
258+ name = f"{ len (reduced_atoms .trajectory )} _frame_dump_atom_selection "
259+ self ._run_manager .write_universe (reduced_atoms , name )
259260
260- return reduced_frames
261+ return reduced_atoms
261262
262263 def _detect_levels (self , reduced_universe : Any ) -> Any :
263264 """Detect hierarchy levels for each molecule in the reduced universe.
@@ -316,25 +317,34 @@ def _split_water_groups(
316317 return nonwater_groups , water_groups
317318
318319 def _compute_water_entropy (
319- self , traj : TrajectorySlice , water_groups : Mapping [int , Any ]
320+ self ,
321+ frame_selection : FrameSelection ,
322+ water_groups : Mapping [int , Any ],
320323 ) -> None :
321324 """Compute water entropy for each water group and adjust selection string.
322325
323326 Args:
324- traj: Trajectory slice parameters .
325- water_groups: Mapping of group id -> molecule ids for waters.
327+ frame_selection: Workflow frame selection .
328+ water_groups: Mapping of group id to molecule ids for waters.
326329 """
327330 if not water_groups or not self ._args .water_entropy :
328331 return
329332
333+ start = frame_selection .source_start
334+ end = frame_selection .source_stop_exclusive
335+ step = frame_selection .infer_source_step ()
336+
337+ if start is None or end is None :
338+ return
339+
330340 water_entropy = WaterEntropy (self ._args , self ._reporter )
331341
332342 for group_id in water_groups .keys ():
333343 water_entropy .calculate_and_log (
334344 universe = self ._universe ,
335- start = traj . start ,
336- end = traj . end ,
337- step = traj . step ,
345+ start = start ,
346+ end = end ,
347+ step = step ,
338348 group_id = group_id ,
339349 )
340350
@@ -344,8 +354,8 @@ def _compute_water_entropy(
344354 else "not water"
345355 )
346356
347- logger .debug (f "WaterEntropy: molecule_data= { self ._reporter .molecule_data } " )
348- logger .debug (f "WaterEntropy: residue_data= { self ._reporter .residue_data } " )
357+ logger .debug ("WaterEntropy: molecule_data= %s" , self ._reporter .molecule_data )
358+ logger .debug ("WaterEntropy: residue_data= %s" , self ._reporter .residue_data )
349359
350360 def _finalize_molecule_results (self ) -> None :
351361 """Aggregate group totals and persist results to JSON.
0 commit comments