harbor run -t openthoughts/tasktrove-exp-rpt-curriculum-hard-curriculum-hard-0002harbor download openthoughts/tasktrove-exp-rpt-curriculum-hard-curriculum-hard-0002Harder task: enhanced preprocessing for cite_seq_count
Overview
You must implement a hardened Python package at /app/cite_seq_count with a preprocessing module that underpins a set of tests now requiring robustness, performance, and edge-case handling for large-scale data. The public API remains the same, but the implementation must be resilient, scalable, and deterministic under varied inputs. All code must use only the Python standard library.
What to build
- A Python package located at /app/cite_seq_count (directory with __init__.py).
- A module inside it named preprocessing.py that implements the following functions with the exact signatures:
- parse_whitelist_csv(whitelist_path: str, barcode_length: int, n: int) -> tuple[set[str], int]
- parse_tags_csv(tags_path: str) -> dict[str, str]
- check_tags(tags: dict[str, str], max_distance: int) -> collections.OrderedDict[str, str]
- check_barcodes_lengths(barcode_len: int, barcode_start: int, barcode_slice_end: int, umi_slice_end: int, barcode_umi_length: int) -> tuple[slice, slice, int]
- get_n_lines(path: str) -> int
Public behavior expectations (as exercised by tests)
- Import path: tests import via from cite_seq_count import preprocessing
- The tests exercise the functions described above and expect outputs consistent with the original task, but under stricter, real-world conditions (large files, malformed input, edge cases).
Detailed requirements and design constraints
1) parse_whitelist_csv(whitelist_path: str, barcode_length: int, n: int) -> tuple[set[str], int]
- Behavior
- Read the CSV file at whitelist_path in a memory-efficient streaming fashion.
- Treat each row as a sequence of comma-separated tokens. For every token:
- Strip whitespace, skip empty tokens.
- If token length equals barcode_length, add token to the resulting whitelist set.
- Return (whitelist_set, n) where whitelist_set is a set of unique barcode strings of the requested length.
- Robustness and edge cases
- Support Unicode input; do not assume ASCII.
- Ignore malformed tokens gracefully (non-string types via CSV parsing should not crash; filter non-str tokens after stripping).
- If the file is empty or contains no valid tokens, return an empty set with n unchanged.
- If the file cannot be opened, raise an informative exception (e.g., FileNotFoundError).
- Performance
- Stream the file; do not load the entire file into memory. The final whitelist_set may still be large, but processing should be O(total_tokens) time with minimal per-token overhead.
- Use csv.reader for robust tokenization, but avoid unnecessary intermediate copies.
- Internationalization and validation
- Do not enforce whitelist token formats beyond exact length; do not mutate tokens.
- Preserve the case of tokens exactly as read.
2) parse_tags_csv(tags_path: str) -> dict[str, str]
- Behavior
- Read the CSV file at tags_path in a streaming fashion.
- Each valid line must contain at least two fields: a tag sequence (first field) and its label (second field).
- Build and return a dict mapping tag_sequence -> label. If the same tag_sequence appears multiple times, the last occurrence wins (deterministic overwriting).
- Skip malformed lines (e.g., fewer than two fields) with no exception; they should not crash the function.
- Robustness
- Support Unicode; trim whitespace around both fields.
- Ignore empty tag sequences.
- Performance
- Streaming parsing; no assumption about the number of lines. Works efficiently for large files.
- Edge cases
- If no valid lines exist, return an empty dict.
3) check_tags(tags: dict[str, str], max_distance: int) -> collections.OrderedDict[str, str]
- Behavior
- Given a mapping tag -> label, produce an OrderedDict where:
- Entries are ordered by descending tag length (longest first). Within the same length, preserve the original input order (stable ordering with respect to the input dict’s iteration order).
- Each value is the string "<label>-<tag>" (i.e., label-tag).
- Velocity and determinism
- The ordering must be deterministic for a given input dict (preserve input order among equal lengths).
- Distance validation (error handling)
- Compute the distinct tag lengths present. Sort them in descending order and determine the maximum gap between consecutive lengths.
- If max_distance > maximum_gap_between_lengths, raise SystemExit (with a concise, descriptive message). This enforces a sanity check on how spread out the tag lengths are.
- If there is zero or one distinct length, maximum_gap_between_lengths is 0; in that case, only max_distance > 0 would raise.
- If the input dict is empty, return an empty OrderedDict.
- Design notes
- Do not reorder beyond the specified criteria.
- The output mapping keys should be the tag strings; the corresponding values should be "label-tag" as described.
- Example
- With a test fixture containing 20-, 18-, and 12-length tags, the OrderedDict should place 20-length entries first (in their input order), then 18-length, then 12-length, with values like 'CITE_LEN_20_1-TGTGAC...'.
4) check_barcodes_lengths(barcode_len: int, barcode_start: int, barcode_slice_end: int, umi_slice_end: int, barcode_umi_length: int) -> tuple[slice, slice, int]
- Behavior
- Return three values:
- barcode_slice = slice(0, barcode_slice_end)
- umi_slice = slice(barcode_slice_end, barcode_umi_length)
- barcode_umi_length (as the third element)
- Validation
- The slices should align exactly with the expectations described below. The test example demonstrates:
- Input: (26, 1, 16, 17, 26)
- Output: (slice(0, 16), slice(16, 26), 26)
- Implement strictly as described; do not apply extra offset calculations beyond the provided parameters.
- Edge cases
- If inputs are inconsistent (e.g., negative indices), raise ValueError with a clear message.
5) get_n_lines(path: str) -> int
- Behavior
- Open the given path as a gzipped file and count the total number of lines.
- If the total number of lines is not a multiple of 4, raise SystemExit with an informative message.
- Otherwise, return the total number of lines.
- Edge cases and robustness
- If the file is not a valid gzip file, raise a clear exception (e.g., OSError with a helpful message).
- Support large files efficiently by streaming and counting without loading entire content into memory.
- Tests
- The test suite will verify a correct multiple-of-4 count (e.g., 800 lines) and a failure case for a corrupted file that does not align to 4 lines.
Implementation and quality constraints
- Location and layout
- /app/cite_seq_count/__init__.py (minimal; package should be importable as cite_seq_count)
- /app/cite_seq_count/preprocessing.py (contains the five functions above with exact signatures)
- Language and dependencies
- Python only; no third-party libraries. Use standard libraries: csv, gzip, sys, collections, typing.
- Type hints and documentation
- Provide clear function-level docstrings describing behavior, edge cases, and side effects.
- Include type hints for all public functions.
- Performance and scalability
- Strive for linear-time streaming behavior where applicable.
- Keep memory usage proportional to the data being processed, not to the total input size when possible.
- Determinism and reliability
- Ordering in check_tags must be deterministic for a given input.
- Behavior for malformed or empty inputs should be well-defined and predictable.
Notes for maintainers
- Tests will import: from cite_seq_count import preprocessing
- The revised hard requirements should be compatible with existing test scaffolding, but tests may be extended to exercise edge cases, large inputs, and failure modes described above.
- Ensure __init__.py remains simple and does not interfere with module loading.
Example usage
- from cite_seq_count import preprocessing
- whitelist, n_out = preprocessing.parse_whitelist_csv("path/to/whitelist.csv", 16, 1)
- tags = preprocessing.parse_tags_csv("path/to/tags.csv")
- ordered = preprocessing.check_tags(tags, max_distance=5)
- slices = preprocessing.check_barcodes_lengths(26, 1, 16, 17, 26)
- lines = preprocessing.get_n_lines("path/to/file.fastq.gz")
Deliverable
- A fully functional Python package located at /app/cite_seq_count with:
- __init__.py (minimal)
- preprocessing.py implementing all five functions per the hardened specifications above
- The implementation must pass the updated test suite designed for the harder difficulty level.