diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index 26372c9..14dbfaa 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -2248,6 +2248,16 @@ are per-sample and windows stay frozen, but feed all samples to a single `generate`. The per-sample cache (`--cache-dir`) makes re-running one large invocation cheap after the first pass. +**gzip level.** `merge-pairs` writes its merged FASTQs at gzip level 6 (`--gzip-level`), and +`generate` writes its caches at level 6 (`--cache-gzip-level`). Python's default is level 9. On the +96 delta smelt GT-seq samples (14.4 million pairs, 8 jobs), `merge-pairs` took 210 s at level 9 +and 122 s at level 6, and the merged files were 3.9% larger at level 6. Writing one sample's cache +took 1.9 s to 3.3 s at level 9 and 0.7 s to 1.2 s at level 6 on the alfalfa, sweetpotato and pecan +cohorts, and the caches were 5% to 6% larger at level 6. The alfalfa cohort (356 samples, 8 jobs) +ran in 422 s with its caches at level 9 and in 363 s at level 6, and peak memory was the same +(9.4 GB). The level changes no merged read, cache content or MADC row, so it is not part of the +cache key. + FASTQ input to `generate` is one primer-started single-end file per sample, while `normalize-reads` accepts any read that contains a panel window. Paired-end data enters through one of the two 0.9.0 routes, @@ -2263,9 +2273,9 @@ By default sample columns use the unique FASTQ filename stem. python3 -m unittest discover -s tests -v ``` -The suite contains 248 unit and end-to-end tests across nine files: +The suite contains 251 unit and end-to-end tests across nine files: -- `test_madcats.py` (93): core `generate` pipeline and intake subcommands +- `test_madcats.py` (96): core `generate` pipeline and intake subcommands - `test_unresolved.py` (23), `test_read_continuation.py` (27), and `test_reading_ties.py` (15): row alignment, unresolved-end handling, read continuation, and Ref/Alt tie-breaking - `test_remove_primers.py` (31): `--remove-primers` trimming, merging, and collision guards diff --git a/docs/src/commands/generate.md b/docs/src/commands/generate.md index 39a27d5..8d49cc7 100644 --- a/docs/src/commands/generate.md +++ b/docs/src/commands/generate.md @@ -74,6 +74,7 @@ See the [Evidence Model](../reference/evidence-model.md) for a detailed descript | `--partial-read-mode {on,off}` | `on` | Credit reads shorter than `--tag-length` to a single evidence-passing full-length allele whose prefix they match, provided the read is longer than any prefix shared by two alleles at that locus. `off` discards partial reads | | `--min-partial-length ` | tag length − 9 | Minimum length for a partial read to be salvaged | | `--cache-dir ` | none | Directory for reusable per-sample assignment caches | +| `--cache-gzip-level ` | 6 | gzip compression level of the caches written to `--cache-dir`, from 1 (fastest) to 9 (smallest files). The level changes the run time and the cache size, not the results, and `generate` reuses a cache written at any level | | `--jobs ` | up to 4 | Number of samples processed in parallel (also parallelizes denoising) | ## Evidence (stage 4) diff --git a/docs/src/commands/merge-pairs.md b/docs/src/commands/merge-pairs.md index cb61a48..2124e9d 100644 --- a/docs/src/commands/merge-pairs.md +++ b/docs/src/commands/merge-pairs.md @@ -50,6 +50,7 @@ Samples are processed independently in parallel using `--jobs`. Each sample is w | `--min-overlap ` | 15 | Shortest overlap, in bases, that lets a pair merge | | `--max-mismatch-rate ` | 0.1 | Mismatch fraction tolerated inside the overlap | | `--unmerged ` | `r1` | For unmergeable pairs, `r1` keeps the R1, `pool` keeps both mates, and `drop` discards the pair | +| `--gzip-level ` | 6 | gzip compression level of the merged FASTQs, from 1 (fastest) to 9 (smallest files). The level changes the run time and the file size, not the merged reads | | `--jobs ` | up to 4 | Samples processed in parallel | ## Examples diff --git a/docs/src/development/architecture.md b/docs/src/development/architecture.md index 50df060..4a9d7ea 100644 --- a/docs/src/development/architecture.md +++ b/docs/src/development/architecture.md @@ -78,6 +78,8 @@ annotation and primer removal read the same `row_decision`, so those stages alwa - The per-sample cache (`--cache-dir`) is keyed by the panel definition and all read-assignment parameters, so downstream evidence or denoising changes do not invalidate it. Bump `CACHE_FORMAT_VERSION` whenever the serialized cache layout or raw-read processing logic changes. + The gzip level (`--cache-gzip-level`) is not part of the key, because a cache holds the same + content at every level. Each cache entry also stores downstream read-continuation summaries (`keeps_continuation`) used to settle unresolved ends during classification. diff --git a/docs/src/development/changelog.md b/docs/src/development/changelog.md index e973e2e..953764c 100644 --- a/docs/src/development/changelog.md +++ b/docs/src/development/changelog.md @@ -33,6 +33,11 @@ Notable changes by version. Measurements behind each change are in the `--leading-anchor-mismatches 1` accepts an anchor with one substitution (the default `0` requires an exact match, as in 0.13.0). `infer-design --leading-anchor` now cuts raw reads in its fuzzy pass as well. +- **gzip level (`merge-pairs --gzip-level`, `generate --cache-gzip-level`, default 6).** + `merge-pairs` now writes its merged FASTQs at gzip level 6 instead of 9, and `generate` does the + same for the caches in `--cache-dir`. Both steps run faster, and the files are 4% to 6% larger. + The level does not change the merged reads or the MADC, and the two options set it from 1 + (fastest) to 9 (smallest files). - **Vendor count overflow.** `validate` and `filter-paralogs` warn when a MADC contains negative read counts, which appear when a vendor table stores counts above 127 in a signed byte. MADCATS uses the stored counts without modifying them. diff --git a/madcats.py b/madcats.py index 17a5422..9db5380 100644 --- a/madcats.py +++ b/madcats.py @@ -247,6 +247,7 @@ LEADING_ANCHOR_MISMATCH_MIN_LENGTH = 12 # shortest anchor that may be matched with a substitution (fewer bases match junk by chance) DENOISE_LOOKUP_THRESHOLD = 2 # denoiser: look up single-substitution neighbours once centroids exceed this many per tag base GAP_OPEN_SCALE = 1 << 10 # annotation alignments weigh one edit this much more than one gap opening +GZIP_LEVEL_DEFAULT = 6 # --gzip-level, --cache-gzip-level: level 9 takes nearly three times as long for files 5% smaller class MadcError(RuntimeError): @@ -2197,9 +2198,9 @@ def merge_read_pair(seq1, qual1, seq2, qual2, min_overlap, max_mismatch_rate): def _merge_pairs_sample(task): """Merge one sample's pair of FASTQ files (worker for run_merge_pairs).""" - r1_path, r2_path, out_path, sample, min_overlap, max_mismatch_rate, unmerged = task + r1_path, r2_path, out_path, sample, min_overlap, max_mismatch_rate, unmerged, gzip_level = task stats: Counter = Counter() - with gzip.open(out_path, "wt") as out: + with gzip.open(out_path, "wt", compresslevel=gzip_level) as out: number = 0 for mate1, mate2 in itertools.zip_longest( fastq_records_named(Path(r1_path)), fastq_records_named(Path(r2_path)) @@ -2633,7 +2634,9 @@ def _load_cache(path: Path, sample: Sample, source_stat: os.stat_result) -> Opti return None -def _write_cache(path: Path, result: SampleResult, source_stat: os.stat_result) -> None: +def _write_cache( + path: Path, result: SampleResult, source_stat: os.stat_result, gzip_level: int = GZIP_LEVEL_DEFAULT +) -> None: path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_suffix(path.suffix + f".{os.getpid()}.tmp") payload: Dict[str, object] = { @@ -2662,7 +2665,7 @@ def _write_cache(path: Path, result: SampleResult, source_stat: os.stat_result) [marker, sequence, *entries] for (marker, sequence), entries in result.continuation_residuals.items() ] - with gzip.open(temporary, "wt") as handle: + with gzip.open(temporary, "wt", compresslevel=gzip_level) as handle: json.dump(payload, handle, separators=(",", ":")) temporary.replace(path) @@ -3071,6 +3074,7 @@ def process_sample( primer_index: PrimerIndex, settings: AssignmentSettings, cache_path: Optional[Path] = None, + cache_gzip_level: int = GZIP_LEVEL_DEFAULT, ) -> SampleResult: """Stage 2: stream one sample's FASTQ into exact per-sequence tag counts. @@ -3235,7 +3239,7 @@ def process_sample( continuation_residuals=continuation_residuals, ) if cache_path is not None: - _write_cache(cache_path, result, source_stat) + _write_cache(cache_path, result, source_stat, cache_gzip_level) return result @@ -5255,7 +5259,7 @@ def run_merge_pairs(args: argparse.Namespace) -> int: raise MadcError(f"Missing mate file for {sample}: {r2_path.name}") tasks.append( (str(r1_path), str(r2_path), str(out_dir / f"{sample}.fastq.gz"), - sample, args.min_overlap, args.max_mismatch_rate, args.unmerged) + sample, args.min_overlap, args.max_mismatch_rate, args.unmerged, args.gzip_level) ) totals: Counter = Counter() if args.jobs == 1: @@ -6084,6 +6088,7 @@ def _assign_samples( settings: AssignmentSettings, cache_dir: Optional[str], jobs: int, + cache_gzip_level: int = GZIP_LEVEL_DEFAULT, ) -> List[SampleResult]: """Stage 2: per-sample read processing — the only FASTQ-touching, expensive stage — parallel across samples and skipped entirely on cache hits.""" @@ -6092,7 +6097,7 @@ def _assign_samples( worker_arguments = [] for sample in samples: cache_path = Path(cache_dir) / f"{sample.sample_id}.{cache_fingerprint}.json.gz" if cache_dir else None - worker_arguments.append((sample, loci, primer_index, settings, cache_path)) + worker_arguments.append((sample, loci, primer_index, settings, cache_path, cache_gzip_level)) print(f"Processing {len(samples)} samples across {len(loci)} loci with {jobs} worker(s)...", file=sys.stderr) if jobs == 1: results = [] @@ -6254,7 +6259,7 @@ def run_generate(args: argparse.Namespace) -> int: _report_tile_families(loci, families, args.tile_groups) settings = _assignment_settings(args, families) _warn_about_evidence_routes(rule, len(samples)) - results = _assign_samples(samples, loci, settings, args.cache_dir, args.jobs) + results = _assign_samples(samples, loci, settings, args.cache_dir, args.jobs, args.cache_gzip_level) # Stage 3: optional partial-read salvage; stages 4-5: evidence and denoising # with evidence-passing sequences protected from absorption. results, partial_summary = apply_partial_reads(results, loci, mode=args.partial_read_mode, rule=rule) @@ -6720,6 +6725,13 @@ def nonnegative_int(value: str) -> int: return parsed +def compression_level(value: str) -> int: + parsed = int(value) + if not 1 <= parsed <= 9: + raise argparse.ArgumentTypeError("must be from 1 to 9") + return parsed + + def probability(value: str) -> float: parsed = float(value) if not 0 < parsed <= 1: @@ -6882,6 +6894,13 @@ def _add_merge_pairs_command(subparsers) -> None: "(for dual-anchored designs whose mates cover opposite locus halves), and drop discards the pair (default: r1)" ), ) + merge.add_argument( + "--gzip-level", type=compression_level, default=GZIP_LEVEL_DEFAULT, metavar="1-9", + help=( + "gzip compression level of the merged FASTQs, from 1 (fastest) to 9 (smallest files). " + f"(default: {GZIP_LEVEL_DEFAULT})" + ), + ) _add_jobs_argument(merge) merge.add_argument("--out-dir", required=True, help="folder for merged per-sample FASTQs") merge.set_defaults(func=run_merge_pairs) @@ -7166,6 +7185,13 @@ def _add_generate_command(subparsers) -> None: "mismatches), --primer-mismatches, --gapped-rescue, --max-indel-length, and --min-partial-length match" ), ) + assignment.add_argument( + "--cache-gzip-level", type=compression_level, default=GZIP_LEVEL_DEFAULT, metavar="1-9", + help=( + "gzip compression level of the caches written to --cache-dir, from 1 (fastest) to 9 (smallest files). " + f"Generate reuses a cache written at any level (default: {GZIP_LEVEL_DEFAULT})" + ), + ) _add_jobs_argument(assignment) evidence = generate.add_argument_group("evidence (stage 4: which novel sequences become rows)") diff --git a/tests/test_madcats.py b/tests/test_madcats.py index c5a1082..28a0320 100644 --- a/tests/test_madcats.py +++ b/tests/test_madcats.py @@ -9,6 +9,7 @@ import tempfile import unittest from pathlib import Path +from unittest import mock import madcats as mp @@ -2212,7 +2213,7 @@ def test_merge_pairs_rejects_mates_out_of_step(self): seq = "ACGT" * 10 r1.write_text(f"@read1/1\n{seq}\n+\n{'I' * 40}\n") r2.write_text(f"@read2/2\n{mp.reverse_complement(seq)}\n+\n{'I' * 40}\n") - task = (str(r1), str(r2), str(Path(tmp) / "a.fastq.gz"), "a", 15, 0.1, "drop") + task = (str(r1), str(r2), str(Path(tmp) / "a.fastq.gz"), "a", 15, 0.1, "drop", mp.GZIP_LEVEL_DEFAULT) with self.assertRaises(mp.MadcError): mp._merge_pairs_sample(task) r2.write_text(f"@read1/2\n{mp.reverse_complement(seq)}\n+\n{'I' * 40}\n") @@ -2574,3 +2575,93 @@ def test_generate_counts_tiles_in_one_panel(self): self.assertEqual(qc["sample_qc"][0]["reads_ambiguous"], 22) # The families are part of the cache key: two runs, two cache entries. self.assertEqual(len(list((root / "cache").glob("s1.*.json.gz"))), 2) + + +class GzipLevelTests(unittest.TestCase): + """``merge-pairs --gzip-level`` and ``generate --cache-gzip-level`` change file sizes, never contents.""" + + def quiet(self, arguments): + with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()): + return mp.main(arguments) + + def test_merge_pairs_level_changes_the_file_size_not_the_reads(self): + rng = random.Random(11) + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + raw = root / "raw" + raw.mkdir() + with (raw / "a_R1.fastq").open("w") as r1, (raw / "a_R2.fastq").open("w") as r2: + for number in range(400): + fragment = "".join(rng.choice("ACGT") for _ in range(120)) + mate1, mate2 = fragment[:100], mp.reverse_complement(fragment[20:]) + r1.write(f"@read{number}/1\n{mate1}\n+\n{'I' * 100}\n") + r2.write(f"@read{number}/2\n{mate2}\n+\n{'I' * 100}\n") + merged, size = {}, {} + for name, level in (("default", ()), ("fast", ("--gzip-level", "1")), ("small", ("--gzip-level", "9"))): + out = root / name + self.assertEqual(self.quiet(["merge-pairs", "--fastq-dir", str(raw), "--r1-suffix", "_R1.fastq", + "--r2-suffix", "_R2.fastq", "--jobs", "1", "--out-dir", str(out), *level]), 0) + with gzip.open(out / "a.fastq.gz", "rt") as handle: + merged[name] = handle.read() + size[name] = (out / "a.fastq.gz").stat().st_size + self.assertEqual(merged["default"].count("\n"), 4 * 400) + self.assertEqual(merged["fast"], merged["default"]) + self.assertEqual(merged["small"], merged["default"]) + self.assertLess(size["small"], size["fast"]) + + def test_cache_level_changes_the_cache_size_not_the_results(self): + rng = random.Random(12) + ref = "".join(rng.choice("ACGT") for _ in range(30)) + alt = ref[:15] + ("A" if ref[15] != "A" else "C") + ref[16:] + locus = mp.Locus(0, "m1", ref[:8], "", ref[15], alt[15], 15, ref, alt) + reads = [ref] * 40 + [alt] * 30 + for _ in range(300): # many distinct tags, so the cache has something to compress + position = rng.randrange(8, 30) + reads.append(ref[:position] + rng.choice("ACGT") + ref[position + 1:]) + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + fastq_dir = root / "fastq" + fastq_dir.mkdir() + for sample in ("s1", "s2"): + with (fastq_dir / f"{sample}.fastq").open("w") as handle: + for number, sequence in enumerate(reads): + handle.write(f"@{sample}_{number}\n{sequence}\n+\n{'I' * len(sequence)}\n") + tags = root / "tags.csv" + mp.write_reference_tags(tags, [locus]) + + def generate(name, cache, *level): + output = root / f"{name}.csv" + self.assertEqual(self.quiet(["generate", "--fastq-dir", str(fastq_dir), "--reference-tags", str(tags), + "--tag-length", "30", "--jobs", "1", "--cache-dir", str(root / cache), + "--output", str(output), *level]), 0) + return output.read_bytes() + + def payloads(cache): + found = {} + for path in sorted((root / cache).glob("*.json.gz")): + with gzip.open(path, "rt") as handle: + found[path.name] = json.load(handle) + return found + + def stored(cache): + return sum(path.stat().st_size for path in (root / cache).glob("*.json.gz")) + + table = generate("default", "cache_default") + self.assertEqual(generate("fast", "cache_fast", "--cache-gzip-level", "1"), table) + self.assertEqual(generate("small", "cache_small", "--cache-gzip-level", "9"), table) + self.assertEqual(len(payloads("cache_default")), 2) + self.assertEqual(payloads("cache_fast"), payloads("cache_default")) + self.assertEqual(payloads("cache_small"), payloads("cache_default")) + self.assertLess(stored("cache_small"), stored("cache_fast")) + # The level is not part of the cache key: a run at another level reuses the caches as they are. + with mock.patch.object(mp, "_write_cache", side_effect=AssertionError("the cache was not used")): + self.assertEqual(generate("again", "cache_fast", "--cache-gzip-level", "9"), table) + + def test_levels_outside_one_to_nine_are_rejected(self): + parser = mp.build_parser() + merge = ["merge-pairs", "--fastq-dir", "raw", "--out-dir", "merged"] + self.assertEqual(parser.parse_args(merge).gzip_level, mp.GZIP_LEVEL_DEFAULT) + self.assertEqual(parser.parse_args(merge + ["--gzip-level", "3"]).gzip_level, 3) + for bad in ("0", "10", "fast"): + with self.subTest(level=bad), contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit): + parser.parse_args(merge + ["--gzip-level", bad])