Skip to content

feat(lammps): load selected dump frames efficiently#1040

Closed
njzjz wants to merge 1 commit into
deepmodeling:masterfrom
njzjz:feat/lammps-selective-frames
Closed

feat(lammps): load selected dump frames efficiently#1040
njzjz wants to merge 1 commit into
deepmodeling:masterfrom
njzjz:feat/lammps-selective-frames

Conversation

@njzjz

@njzjz njzjz commented Jul 22, 2026

Copy link
Copy Markdown
Member

Summary

  • add f_idx support to lammps/dump so callers can load arbitrary non-negative frame indices directly
  • stream trajectory frames one at a time, retain only requested frames, and stop after the largest requested index
  • preserve requested order and duplicate indices for parity with System.sub_system
  • validate empty, negative, out-of-range, and conflicting begin/step selections
  • split selected trajectories at their actual ITEM: TIMESTEP boundaries instead of assuming a fixed block length

Example:

system = dpdata.System(
    "trajectory.dump",
    fmt="lammps/dump",
    type_map=["O", "H"],
    f_idx=[23, 56, 78],
)

Performance benchmark

The benchmark compares direct sparse loading against the existing workflow of loading the complete trajectory and then calling sub_system(indices).

  • synthetic LAMMPS dump: 12.15 MiB, 5,000 frames, 100 atoms per frame
  • selection: 10 evenly distributed frames, including the final frame
  • measurement: one warm-up followed by 5 measured runs per method
  • each measurement ran in a fresh Python process; table values are medians
  • environment: Linux 6.8.0-110-generic, Python 3.13.9, NumPy 2.5.1
Method Median wall time Median peak RSS
System(..., f_idx=indices) 0.092 s 39.38 MiB
System(...).sub_system(indices) 1.328 s 110.59 MiB

Direct sparse loading was 14.38x faster and reduced peak RSS by 64.39% for this workload. Both methods returned the same 10 selected frames. Because the final frame was selected, both methods traversed the full file; the improvement comes from avoiding storage and parsing of unselected frames.

Validation

  • python -m unittest test_lammps_dump_skipload.py test_lammps_dump_to_system.py test_lammps_dump_unfold.py test_lammps_dump_shift_origin.py test_lammps_dump_idx.py test_lammps_read_from_trajs.py test_lammps_spin.py — 70 tests passed
  • ruff check dpdata/ tests/test_lammps_dump_skipload.py — passed
  • ruff format --check dpdata/ tests/test_lammps_dump_skipload.py — passed
  • dpdata --help and dpdata --version — passed
  • full discovery ran 2,241 tests; 12 Amber mask tests errored because the optional parmed dependency is not installed in the environment, and 43 tests were skipped

Closes #367.

Coding agent: Codex
Codex version: codex-cli 0.144.6
Model: gpt-5.6-sol
Reasoning effort: xhigh

Summary by CodeRabbit

  • New Features

    • Added support for loading specific trajectory frames by index, including custom ordering and duplicate selections.
    • Frame loading now stops reading once the requested frames are reached, improving efficiency.
    • Added clearer validation for invalid frame indices and conflicting selection options.
  • Bug Fixes

    • Improved trajectory splitting for files with variable-sized frame blocks.
  • Tests

    • Added coverage for frame selection, ordering, duplicates, validation, and efficient reading.

Add f_idx-based sparse frame loading for LAMMPS dump trajectories while preserving requested order and duplicate indices. Stop scanning after the final requested frame and validate invalid selections explicitly.

Coding-Agent: Codex
Codex-Version: codex-cli 0.144.6
Model: gpt-5.6-sol
Reasoning-Effort: xhigh
Copilot AI review requested due to automatic review settings July 22, 2026 17:23
@codspeed-hq

codspeed-hq Bot commented Jul 22, 2026

Copy link
Copy Markdown

Merging this PR will not alter performance

⚠️ Unknown Walltime execution environment detected

Using the Walltime instrument on standard Hosted Runners will lead to inconsistent data.

For the most accurate results, we recommend using CodSpeed Macro Runners: bare-metal machines fine-tuned for performance measurement consistency.

✅ 2 untouched benchmarks


Comparing njzjz:feat/lammps-selective-frames (376317d) with master (212ab49)

Open in CodSpeed

@njzjz njzjz closed this Jul 22, 2026
@njzjz
njzjz deleted the feat/lammps-selective-frames branch July 22, 2026 17:25
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. enhancement New feature or request lammps labels Jul 22, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR adds efficient sparse frame loading for the lammps/dump format by introducing f_idx selection, enabling callers to load only specific non-negative frame indices without parsing and storing the full trajectory.

Changes:

  • Added f_idx support to LAMMPSDumpFormat.from_system and propagated it down to the dump loader.
  • Implemented streaming frame iteration and index normalization/validation in dpdata/formats/lammps/dump.py to load only requested frames and stop early when possible.
  • Updated trajectory splitting to respect actual ITEM: TIMESTEP boundaries, and added tests covering order/duplicates, scalar index input, and validation errors.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.

File Description
tests/test_lammps_dump_skipload.py Adds tests for f_idx selection semantics, validation, and early-stop behavior.
dpdata/plugins/lammps.py Extends the lammps/dump plugin API to accept f_idx and forwards it to the loader.
dpdata/formats/lammps/dump.py Implements streaming frame parsing, f_idx validation/selection, and robust frame splitting by TIMESTEP markers.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +21 to +23
def __next__(self):
self.lines_read += 1
return super().__next__()
@coderabbitai

coderabbitai Bot commented Jul 22, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The LAMMPS dump reader now supports explicit sparse frame selection, streaming reads with early termination, clearer index validation, and marker-based trajectory splitting. The LAMMPS plugin forwards the new selection parameter, with tests covering selection behavior and errors.

Changes

LAMMPS frame selection

Layer / File(s) Summary
Streaming frame selection
dpdata/formats/lammps/dump.py
Frame iteration is generator-based; f_idx accepts ordered non-negative indices, preserves duplicates, stops after the highest target, and remains incompatible with non-default begin or step.
Plugin wiring and validation
dpdata/plugins/lammps.py, tests/test_lammps_dump_skipload.py
from_system forwards f_idx; tests cover ordering, duplicates, single-frame loading, early stopping, and invalid inputs.
Variable-length trajectory splitting
dpdata/formats/lammps/dump.py
split_traj delimits frames using successive ITEM: TIMESTEP markers or end-of-file.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Caller
  participant LAMMPSDumpFormat
  participant load_file
  participant _iter_frames
  Caller->>LAMMPSDumpFormat: request f_idx
  LAMMPSDumpFormat->>load_file: forward f_idx
  load_file->>_iter_frames: read frames sequentially
  _iter_frames-->>load_file: yield frame lines
  load_file-->>LAMMPSDumpFormat: return selected frames
  LAMMPSDumpFormat-->>Caller: return system data
Loading

Possibly related PRs

Suggested reviewers: copilot

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title concisely describes the main change: efficient loading of selected LAMMPS dump frames.
Linked Issues check ✅ Passed The PR implements sparse LAMMPS frame loading with f_idx, preserving order/duplicates and stopping after the last requested frame as requested.
Out of Scope Changes check ✅ Passed The changes stay focused on sparse LAMMPS dump loading, related plugin wiring, and tests, with no clear unrelated additions.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@tests/test_lammps_dump_skipload.py`:
- Around line 14-23: Update CountingStringIO to track maximum stream position
across read, readline, readlines, and __next__, rather than only incrementing
lines_read in __next__. In the early-termination assertion around the affected
test, verify the recorded maximum position remains below len(content),
preserving the probe’s intended detection of any full-stream consumption.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: fc0e87d7-32b7-4dcf-bb42-971836541fe3

📥 Commits

Reviewing files that changed from the base of the PR and between 212ab49 and 376317d.

📒 Files selected for processing (3)
  • dpdata/formats/lammps/dump.py
  • dpdata/plugins/lammps.py
  • tests/test_lammps_dump_skipload.py

Comment on lines +14 to +23
class CountingStringIO(io.StringIO):
"""Track how many lines the trajectory reader consumes."""

def __init__(self, value):
super().__init__(value)
self.lines_read = 0

def __next__(self):
self.lines_read += 1
return super().__next__()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Make the early-termination probe detect all stream consumption.

lines_read only tracks __next__; a full read()/readline() regression would still pass line 85. Track the maximum stream position from read, readline, readlines, and __next__, then assert it remains below len(content).

Also applies to: 76-85

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/test_lammps_dump_skipload.py` around lines 14 - 23, Update
CountingStringIO to track maximum stream position across read, readline,
readlines, and __next__, rather than only incrementing lines_read in __next__.
In the early-termination assertion around the affected test, verify the recorded
maximum position remains below len(content), preserving the probe’s intended
detection of any full-stream consumption.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request lammps size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

A more efficient way of reading MD trajectory

2 participants