harbor run -t openthoughts/tasktrove-exp-rpt-scaffold-v2-scaffold-1771harbor download openthoughts/tasktrove-exp-rpt-scaffold-v2-scaffold-1771# Task: Implement the scaffolded MPI-enabled PDB dihedral/binning benchmark
Goal
- Replace all NotImplementedError stubs with a functional, well-documented implementation.
- Ensure the module can discover PDB files, extract CA coordinates, compute pseudo dihedrals, bin dihedrals and distances, save per-PDB results, and verify outputs.
- Provide a clean, deterministic, non-MPI workflow suitable for pytest-based tests while keeping MPI-compatible entry points for future enhancement.
What you need to implement (high level, behavior-focused)
1) MPIDihedralBenchmark.discover_pdb_files(self) -> List[str]
- Purpose: find all PDB files under the configured data directory.
- Behavior:
- Recursively search self.data_dir for files with a .pdb extension (case-insensitive).
- Return a sorted list of full paths to ensure deterministic order for tests.
- If none are found, return an empty list.
- Edge cases: handle missing data_dir gracefully (empty list rather than raising an exception).
2) MPIDihedralBenchmark.parse_ca_coordinates(self, pdb_path: str) -> List[Coordinate3D]
- Purpose: extract CA atom coordinates from a PDB file in residue order.
- Behavior:
- Read the PDB file and collect coordinates for atoms with atom name "CA" (case-sensitive to match PDB conventions).
- Return coordinates as a list of (x, y, z) tuples, preserving residue order as encountered.
- If no CA atoms are found, return an empty list.
- Edge cases:
- Handle lines with missing or malformed coordinates gracefully (skip them rather than crash).
- If the file is unreadable, propagate a clear exception (e.g., IOError/OSError).
3) MPIDihedralBenchmark.compute_phi_psi(self, ca_coords: CAList) -> Tuple[List[float], List[float]]
- Purpose: produce two aligned sequences of pseudo dihedral angles from CA coordinates.
- Behavior:
- If there are fewer than 4 CA coordinates, return two empty lists.
- Compute two lists (phis, psis) of equal length using a consistent, well-documented scheme for pseudo dihedrals:
- Example approach (described, not enforced here): compute phi for residues using CA[i-1], CA[i], CA[i+1], CA[i+2] (i ranges from 1 to N-3) and psi using CA[i], CA[i+1], CA[i+2], CA[i+3] (i ranges from 0 to N-4); the two lists will have length N-3 (or 0 if N<4).
- Return (phis, psis) as two Python lists of floats.
- Edge cases: if any coordinates are NaN/inf, handle gracefully (either filter or propagate by returning empty lists if they invalidate results).
4) MPIDihedralBenchmark.bin_dihedrals(self, phis: List[float], psis: List[float], n_bins: int) -> np.ndarray
- Purpose: create a 2D histogram of dihedral angles.
- Behavior:
- Input sequences phis and psis must be of the same length. If not, handle gracefully (e.g., use the minimum length or raise a clear error).
- Convert angle ranges to bins in the typical dihedral range [-180, 180).
- Produce a 2D NumPy array with shape (n_bins, n_bins) where each (i, j) bin counts the number of occurrences for (phi in bin i, psi in bin j).
- Return the histogram as a 2D NumPy array of integers (or floats if you prefer).
- Edge cases: if there are no pairs, return a zero-initialized array of shape (n_bins, n_bins).
5) MPIDihedralBenchmark.compute_pairwise_distances(self, ca_coords: CAList) -> np.ndarray
- Purpose: compute all pairwise CA-CA distances.
- Behavior:
- Given N CA coordinates, compute Euclidean distances for all unordered pairs (i < j).
- Return a 1D NumPy array of length N*(N-1)/2 containing the distances.
- If fewer than 2 coordinates, return an empty array.
- Edge cases: robust to small inputs and numerical stability; coordinates should be treated as 3D float values.
6) MPIDihedralBenchmark.bin_distances(self, distances: np.ndarray, distance_edges: List[float]) -> np.ndarray
- Purpose: histogram of pairwise distances using explicit edges.
- Behavior:
- Validate that distance_edges is a strictly increasing sequence; if not, normalize or raise an informative error.
- Use numpy.histogram (or equivalent) to bin distances into len(distance_edges)-1 bins.
- Return a 1D NumPy array of counts with length len(distance_edges)-1.
- Edge cases: if distances is empty, return a zeroed histogram of appropriate length.
7) MPIDihedralBenchmark.save_results(self, pdb_path: str, dihedral_hist: np.ndarray, distances_hist: np.ndarray, output_dir: str) -> str
- Purpose: persist per-PDB results to disk and provide the path to the saved file.
- Behavior:
- Ensure the output_dir directory exists (create if needed).
- Determine a stable output filename derived from pdb_path (for example, base name without extension plus ".npz").
- Save the following into a compressed NumPy archive (.npz) using clear keys:
- pdb_path (the input path, for traceability)
- dihedral_hist (the 2D histogram)
- distances_hist (the 1D histogram)
- Return the path to the saved .npz file as a string.
- Edge cases: handle write failures with a clear exception.
8) MPIDihedralBenchmark.run(self) -> None
- Purpose: end-to-end, MPI-aware (but implement a robust sequential workflow suitable for tests).
- Behavior:
- Discover PDB files via discover_pdb_files.
- For each PDB file:
- Parse CA coordinates via parse_ca_coordinates.
- Compute phis/psis via compute_phi_psi.
- Bin dihedrals via bin_dihedrals.
- Compute pairwise distances and bin via bin_distances.
- Save per-PDB results via save_results to a dedicated output directory (e.g., data_dir/output or data_dir/results).
- If mpi4py is available, you may leave a simple sequential fallback, ensuring correct behavior even when MPI is present or not. Tests will exercise the non-MPI path.
- Edge cases: handle empty pdb_lists gracefully; ensure deterministic output order; ensure output directory is created.
9) verify_outputs(data_dir: str) -> bool
- Purpose: validate that every input PDB has a corresponding saved results file.
- Behavior:
- Locate all PDB files under data_dir (same search as discover_pdb_files would).
- For each PDB, determine the expected .npz path (matching the naming scheme used in save_results, e.g., base name + ".npz" inside the output directory).
- Return True if all expected .npz files exist; otherwise return False.
- Edge cases: if there are no PDB files, return True (trivially satisfied).
10) main() -> int
- Purpose: provide a simple CLI to run the scaffold.
- Behavior:
- Parse arguments:
- --data-dir: required root data directory (the scaffold assumes data/KrasHras or a provided path).
- --di-bin: optional, default from scaffold (number of bins per dihedral axis).
- --dist-bins: optional, space-separated list of floats (edges for distance histogram).
- Instantiate MPIDihedralBenchmark with parsed parameters.
- Call run() to execute the pipeline.
- Return 0 on success.
- Edge cases: provide helpful error messages for invalid arguments; keep behavior deterministic for tests.
What files you will modify
- The Python module under /app/ that defines:
- PDBProcessingResult (already implemented, no NotImplementedError)
- MPIDihedralBenchmark (all NotImplementedError stubs to replace)
- verify_outputs(data_dir: str) -> bool
- main() -> int
- Do not modify tests. Ensure backward-compatible signatures and import paths so tests can import these components as the scaffold intends.
Testing approach (pytest)
- Tests will exercise the implemented functions and workflow in a deterministic, non-MPI path.
- Expected test coverage ideas (not explicit in tests you’ll run, but indicative of intent):
- discover_pdb_files returns all and only .pdb files under data_dir.
- parse_ca_coordinates returns CA coordinates in correct order (or empty if none).
- compute_phi_psi returns two aligned lists with expected length given input CA count.
- bin_dihedrals produces a correct 2D histogram shape and counts for known inputs.
- compute_pairwise_distances returns the correct number of distances for N CA atoms.
- bin_distances yields a histogram with correct bin counts for known distances.
- save_results creates a .npz with expected keys and path, and verify_outputs validates presence of all outputs after run.
- main() parses arguments and triggers run without raising NotImplementedError.
Notes and expectations
- Do not reveal the exact implementation details in the task description; focus on behavior and interfaces.
- The implementation should be robust to edge cases and provide clear, deterministic results suitable for pytest-based assertions.
- MPI integration may be left as a sequential fallback for the tests, but keep the code structured to support MPI later with minimal changes.
Deliverable
- Implement all NotImplementedError stubs in the module under /app/ following the behavior guidelines above.
- Ensure the code remains well-documented, with docstrings and comments clarifying any non-trivial decisions (especially the phi/psi computation scheme and binning rules).
- All tests (pytest) should pass with the implemented behavior.
Important: place your implementation at `/app/solution.py` so the tests can `import solution`.