From 9bb6a7f35f93e07bc7541f1aeb58015456a38174 Mon Sep 17 00:00:00 2001 From: Alexander Sandercock <39815775+alex-sandercock@users.noreply.github.com> Date: Wed, 2 Dec 2026 20:58:46 -0500 Subject: [PATCH 1/2] generate: about half the run time and memory, for the same output Three things took most of the read pass, and each now does less work for the same answer: - A tag with an N is compared with a sequence in the stretches between its N's, as whole strings (`_n_tag_fits`). - The gapped prescreen makes a design tag's bit masks once, stops at the first of its two passes that settles the question, and `_gapped_edits` skips the Alt tag when the Ref tag's bound is already too far. - `PrimerIndex.match` takes its search up from its state after 12 bases, which reads of one amplicon share. Most of a run's memory is sequences seen once or twice: - `apply_partial_reads` adds partial reads without copying a sample's tables. - Protection is decided from the sequences that reach a route's read count in some sample (`_could_pass`). No other sequence can pass. - `finalize_counts` lets each sample as read go once it is denoised. - The per-sequence quality tallies stay in the worker unless the quality route is on. They are still counted and cached. With 8 jobs: pecan (376 samples) 1,376 s to 657 s and 15.9 GB to 7.0 GB, alfalfa (356) 464 s to 262 s and 9.4 GB to 3.8 GB, sweetpotato (80) 381 s to 204 s and 3.4 GB to 1.75 GB. Memory is the main process's peak footprint. On all three the table, the variants sidecar and the QC JSON are the same byte for byte, and so are the read-pass caches. `tests/test_same_answers.py` sets each shortcut beside the plain computation it stands in for. --- docs/DEVELOPMENT.md | 30 ++- docs/src/development/changelog.md | 1 + madcats.py | 278 +++++++++++++++++++------- tests/test_same_answers.py | 316 ++++++++++++++++++++++++++++++ 4 files changed, 549 insertions(+), 76 deletions(-) create mode 100644 tests/test_same_answers.py diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index 26372c9..1d9c0cb 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -2125,9 +2125,8 @@ continuation of those nine has 40% to 59%. In seven of them it is far ahead of t reads against 7): read errors scatter the rest. The pooled denoiser reads rows with the same continuations as the table. -With 8 jobs the pecan cohort (376 samples) takes 1,384 s, sweetpotato (80) 381 s and alfalfa (356) -466 s. Counting continuations from a tag's first read, without the three-read rule, took 1,929 s -on pecan. +Counting continuations from a tag's first read, without the three-read rule, added 39% to the +pecan cohort's run time (1,929 s against 1,384 s when it was measured). **Ties between the Ref and Alt readings.** When the Alt tag needs fewer separate gaps for the same number of edits, 0.03% to 0.10% of rows change category (0.002% to 0.04% of reads), all of them to @@ -2168,6 +2167,27 @@ marker. A marker that leads its group has an empty `LocusGroup` cell and now cou On the grapevine panel `auto` had linked `12_996164__t192` with `13_13607473` that way; their shared window is chromosome 12 sequence. +**Run time and memory.** With 8 jobs the pecan cohort (376 samples) takes 657 s, alfalfa (356) +262 s and sweetpotato (80) 204 s. 0.13.0 took 1,249 s, 409 s and 343 s. The main process peaks at +7.0 GB, 3.8 GB and 1.75 GB (peak memory footprint, which counts compressed pages). + +The read pass is about four fifths of a run, and three things dominate it. Each is done the cheap +way that gives the same answer. A tag with an N is compared with a sequence in the stretches +between its N's. The gapped prescreen makes a design tag's bit masks once, stops at the first of +its two passes that settles the question, and skips the Alt tag when the Ref tag's bound is +already too far. The primer search is taken up from its state after 12 bases, which reads of one +amplicon share. + +Most of a run's memory is sequences seen once or twice: 82% of the sequences of an alfalfa sample +have one read. Partial reads are added without copying a sample's tables. Evidence is tallied +only for sequences that reach a route's read count in some sample, because no other sequence can +pass. A sample as read is let go once it is denoised. The per-sequence quality tallies are +counted and cached, and they stay in the worker unless the quality route is on. + +Each shortcut gives the answer of the plain computation (`tests/test_same_answers.py`), and the +three cohorts' tables, variants sidecars and QC files are the same byte for byte with the +shortcuts as without. + ## Downstream fixed allele IDs This pipeline's responsibility ends with generation of the raw MADC-like @@ -2263,7 +2283,7 @@ 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 260 unit and end-to-end tests across ten files: - `test_madcats.py` (93): core `generate` pipeline and intake subcommands - `test_unresolved.py` (23), `test_read_continuation.py` (27), and `test_reading_ties.py` (15): @@ -2273,6 +2293,8 @@ The suite contains 248 unit and end-to-end tests across nine files: real `mappy` aligner are skipped when `mappy` is not installed) - `test_tiled_markers.py` (4): tiled markers across `generate` and `filter-paralogs` (1 `mappy` test is skipped when `mappy` is not installed) +- `test_same_answers.py` (12): each shortcut that saves time or memory in `generate` beside the + plain computation it stands in for - `test_example.py` (5): bundled `examples/madcats-demo` project against simulated truth - `test_docs.py` (1): synchronization between `docs/src/commands/` tables and the CLI parser diff --git a/docs/src/development/changelog.md b/docs/src/development/changelog.md index e973e2e..c839f01 100644 --- a/docs/src/development/changelog.md +++ b/docs/src/development/changelog.md @@ -38,6 +38,7 @@ Notable changes by version. Measurements behind each change are in the uses the stored counts without modifying them. - **Other changes.** MADC readers accept a header whose first column is not `AlleleID`, as in HapApp's fixed-allele-ID output. The cache format is now 0.8.0, so existing caches rebuild once. + `generate` also runs faster: three DArTag cohorts took 36% to 47% less time than with 0.13.0. This release also revises the CLI help text across subcommands. ## 0.13.0 diff --git a/madcats.py b/madcats.py index 17a5422..92ae195 100644 --- a/madcats.py +++ b/madcats.py @@ -569,6 +569,16 @@ def pearson_from_sums(n: int, sx: float, sy: float, sxx: float, syy: float, sxy: # ============================================================================ +@functools.lru_cache(maxsize=16384) +def _design_pattern_masks(pattern: str) -> Dict[str, int]: + """Per observed base, the positions of a design template that it matches (the template is the Myers pattern).""" + masks: Dict[str, int] = {} + for i, design in enumerate(pattern): + for observed in IUPAC_BASES.get(design, frozenset(design)) | {design}: + masks[observed] = masks.get(observed, 0) | (1 << i) + return masks + + def _myers_prefix_distances(pattern: str, text: str, design_is_pattern: bool) -> List[int]: """Global edit distance of ``pattern`` against every prefix of ``text``. @@ -586,32 +596,26 @@ def _myers_prefix_distances(pattern: str, text: str, design_is_pattern: bool) -> m = len(pattern) if m == 0: return list(range(len(text) + 1)) - peq: Dict[str, int] = {} if design_is_pattern: - for i, design in enumerate(pattern): - for observed in IUPAC_BASES.get(design, frozenset(design)) | {design}: - peq[observed] = peq.get(observed, 0) | (1 << i) + eqs = _design_pattern_masks(pattern) else: + peq: Dict[str, int] = {} for i, observed in enumerate(pattern): peq[observed] = peq.get(observed, 0) | (1 << i) - eq_cache: Dict[str, int] = {} - - def eq_for(design: str) -> int: # text is the design: every read position whose base lies in the code's set - got = eq_cache.get(design) - if got is None: + eqs = {} + for design in set(text): got = 0 for observed in IUPAC_BASES.get(design, frozenset(design)) | {design}: got |= peq.get(observed, 0) - eq_cache[design] = got - return got - + eqs[design] = got + get_eq = eqs.get mask = (1 << m) - 1 high = 1 << (m - 1) pv, mv, score = mask, 0, m out = [m] for base in text: - eq = peq.get(base, 0) if design_is_pattern else eq_for(base) + eq = get_eq(base, 0) xv = eq | mv xh = (((eq & pv) + pv) ^ pv) | eq ph = mv | (~(xh | pv) & mask) @@ -628,18 +632,23 @@ def eq_for(design: str) -> int: return out -def gapped_prescreen(read: str, ref: str, band: int) -> int: +def gapped_prescreen(read: str, ref: str, band: int, enough: Optional[int] = None) -> int: """Lower bound on the start-anchored, end-free gapped edit distance. The end may overhang by up to ``band`` bases on either side (a read tail past the reference is a deletion's signature; a reference tail past the read an insertion's). Unbanded, so never above the banded distance: a value over the budget proves the banded alignment is too. + + A caller that only asks whether the bound is at most ``enough`` can say + so: the first of the two passes that shows it ends the search, and the + value returned is then at or under ``enough`` but may be above the bound. """ n, m = len(read), len(ref) - read_consumed = _myers_prefix_distances(read, ref, design_is_pattern=False) - ref_consumed = _myers_prefix_distances(ref, read, design_is_pattern=True) - return min(min(read_consumed[max(0, m - band):]), min(ref_consumed[max(0, n - band):])) + read_consumed = min(_myers_prefix_distances(read, ref, design_is_pattern=False)[max(0, m - band):]) + if enough is not None and read_consumed <= enough: + return read_consumed + return min(read_consumed, min(_myers_prefix_distances(ref, read, design_is_pattern=True)[max(0, n - band):])) def _gapped_dp(read: str, ref: str, band: int): @@ -845,7 +854,7 @@ def _unverified_gapped_reading( return None if substitutions is None: substitutions = tag_mismatches(sequence, template) - if substitutions <= 1 or gapped_prescreen(sequence, template, gap_band) >= substitutions: + if substitutions <= 1 or gapped_prescreen(sequence, template, gap_band, substitutions - 1) >= substitutions: return None ops, end_read, end_ref, edits = gapped_alignment(sequence, template, gap_band) if edits >= substitutions: @@ -2252,6 +2261,11 @@ def select_scan_subset(fastqs: Sequence[Path], count: int, seed: Optional[int]) # ============================================================================ +PRIMER_MATCH_HEAD = 12 # leading bases after which PrimerIndex.match keeps the state of its search +PRIMER_MATCH_MEMO = 200_000 # such states kept before the store is emptied +_NO_BASES: frozenset = frozenset() + + class PrimerIndex: """Compact trie that reports all best primer-prefix matches.""" @@ -2260,6 +2274,7 @@ def __init__(self, loci: Sequence[Locus]): self.terminals: List[List[int]] = [[]] self.max_length = 0 self.has_degenerate = False + self._heads: Dict[Tuple[str, int], Tuple[tuple, frozenset]] = {} # (first bases, budget) -> search so far for locus in loci: node = 0 self.max_length = max(self.max_length, len(locus.left_primer)) @@ -2289,33 +2304,54 @@ def match(self, sequence: str, max_mismatches: int = 0) -> List[int]: resolves multi-locus candidates by full-tag identity, which is the stronger signal. """ + start = sequence[: self.max_length] + children, terminals = self.children, self.terminals if max_mismatches == 0 and not self.has_degenerate: node = 0 matches: List[int] = [] - for base in sequence[: self.max_length]: - child = self.children[node].get(base) + for base in start: + child = children[node].get(base) if child is None: break node = child - if self.terminals[node]: - matches.extend(self.terminals[node]) + if terminals[node]: + matches.extend(terminals[node]) return matches - states = [(0, 0)] - candidates: set = set() - for base in sequence[: self.max_length]: + # The first bases cost the most: every primer of the panel is still in + # play there. Reads of one amplicon share them, so the search is kept + # as it stands after PRIMER_MATCH_HEAD bases and taken up from there. + head = start[:PRIMER_MATCH_HEAD] + known = self._heads.get((head, max_mismatches)) + if known is None: + if len(self._heads) >= PRIMER_MATCH_MEMO: + self._heads.clear() + states, found = self._search([(0, 0)], set(), head, max_mismatches) + known = self._heads[(head, max_mismatches)] = (tuple(states), frozenset(found)) + states, found = known + if not states or len(start) <= len(head): + return sorted(found) + return sorted(self._search(states, set(found), start[len(head):], max_mismatches)[1]) + + def _search(self, states, candidates: set, bases: str, max_mismatches: int): + """Follow ``bases`` from ``states`` (node, mismatches so far): the states left and the candidates met.""" + children, terminals = self.children, self.terminals + for base in bases: next_states: List[Tuple[int, int]] = [] for node, mismatches in states: - for expected, child in self.children[node].items(): - accepted = expected == base or base in IUPAC_BASES.get(expected, frozenset()) - new_mismatches = mismatches + (0 if accepted else 1) - if new_mismatches <= max_mismatches: - next_states.append((child, new_mismatches)) - candidates.update(self.terminals[child]) - if not next_states: - break + for expected, child in children[node].items(): + if expected != base and base not in IUPAC_BASES.get(expected, _NO_BASES): + if mismatches >= max_mismatches: + continue + next_states.append((child, mismatches + 1)) + else: + next_states.append((child, mismatches)) + if terminals[child]: + candidates.update(terminals[child]) states = next_states - return sorted(candidates) + if not states: + break + return states, candidates def locate_leading_anchor(sequence: str, anchor: str, max_mismatches: int = 0) -> Tuple[int, int]: @@ -2761,14 +2797,26 @@ def root(index: int) -> int: return tuple(sorted(tuple(group) for group in components)) +@functools.lru_cache(maxsize=16384) +def _tags_apart(ref_tag: str, alt_tag: str) -> int: + """Positions at which two tags of one length hold another character.""" + return sum(1 for a, b in zip(ref_tag, alt_tag) if a != b) + + def _gapped_edits(tag: str, locus: Locus, max_mismatches: int, gap_band: int) -> Optional[int]: """Fewest edits of an accepted gapped reading of ``tag`` against the locus's Ref or Alt tag, or ``None`` when neither reading is believed.""" best: Optional[int] = None + ref_bound: Optional[int] = None for template in (locus.ref_tag, locus.alt_tag): if len(template) != len(tag): continue - if gapped_prescreen(tag, template, gap_band) > max_mismatches: + if ref_bound is not None and ref_bound - _tags_apart(locus.ref_tag, locus.alt_tag) > max_mismatches: + continue # each base the two tags differ at moves the bound by one at most, so the Alt tag's is over the budget too + bound = gapped_prescreen(tag, template, gap_band, max_mismatches) + if ref_bound is None: + ref_bound = bound + if bound > max_mismatches: continue edits, substitutions, gap_bases, gap_events, _, _ = gapped_stats(tag, template, gap_band) if edits > max_mismatches or not gapped_explanation_ok(substitutions, gap_bases, gap_events): @@ -2868,6 +2916,22 @@ def select_marker( return (markers[0] if markers else None), status +def _n_tag_fits(stretches: Sequence[str], sequence: str) -> bool: + """Whether a tag fits a sequence of A, C, G and T only, given the tag's stretches between its N's. + + The same answer as ``compatible_mismatches(tag, sequence, 0) == 0`` for a + tag whose only ambiguity code is N: an N fits any base, and every other + base must be equal. + """ + start = 0 + for stretch in stretches: + end = start + len(stretch) + if stretch != sequence[start:end]: + return False + start = end + 1 + return True + + def resolve_n_tags( counts: MutableMapping[Tuple[int, str], int], quality_support: MutableMapping[Tuple[int, str], List[int]], @@ -2894,12 +2958,24 @@ def resolve_n_tags( for marker_index, sequence in counts: if "N" not in sequence: concrete_by_marker[marker_index].append(sequence) + # Per marker, the sequences an N tag may go to: those of A, C, G and T only, which + # _n_tag_fits compares in stretches, and any other N-free ones, compared base by base. + pools: Dict[int, Tuple[List[str], List[str]]] = {} for marker_index, tag in n_keys: - locus = loci[marker_index] - pool = set(concrete_by_marker[marker_index]) | { - tag_ for tag_ in (locus.ref_tag, locus.alt_tag) if _CONCRETE.issuperset(tag_) - } - matches = [s for s in pool if len(s) == len(tag) and compatible_mismatches(tag, s, 0) == 0] + if marker_index not in pools: + locus = loci[marker_index] + pool = set(concrete_by_marker[marker_index]) | { + tag_ for tag_ in (locus.ref_tag, locus.alt_tag) if _CONCRETE.issuperset(tag_) + } + plain = [s for s in pool if _CONCRETE.issuperset(s)] + pools[marker_index] = (plain, [s for s in pool if not _CONCRETE.issuperset(s)]) + plain, coded = pools[marker_index] + stretches = tag.split("N") + if all(_CONCRETE.issuperset(stretch) for stretch in stretches): + matches = [s for s in plain if len(s) == len(tag) and _n_tag_fits(stretches, s)] + else: # the tag holds another ambiguity code as well + matches = [s for s in plain if len(s) == len(tag) and compatible_mismatches(tag, s, 0) == 0] + matches += [s for s in coded if len(s) == len(tag) and compatible_mismatches(tag, s, 0) == 0] count = counts.pop((marker_index, tag)) support = quality_support.pop((marker_index, tag), None) if len(matches) == 1: @@ -3240,7 +3316,18 @@ def process_sample( def _process_sample_worker(arguments): - return process_sample(*arguments) + """One sample's read pass, as ``_assign_samples`` hands it out. + + The last argument says whether the caller reads the quality tallies. + Only the quality route does. They are counted and cached either way, + but a result that crosses back without them is about a third smaller, + and the cohort's results are what the run's memory is made of. + """ + *process_arguments, keep_quality = arguments + result = process_sample(*process_arguments) + if keep_quality: + return result + return dataclasses.replace(result, quality_support={}, partial_quality_support={}) def discover_fastqs(directory: Path, pattern: str) -> List[Path]: @@ -3421,11 +3508,36 @@ def evaluate( return False, "failed_evidence" +def _could_pass( + per_sample_counts: Sequence[Mapping[Tuple[int, str], int]], rule: EvidenceRule +) -> Optional[Set[Tuple[int, str]]]: + """The sequences that can pass ``rule`` at all, or ``None`` when any sequence can. + + The reproducibility and depth routes each need one sample with a set + number of reads, so a sequence that reaches the smaller of the two + numbers in no sample passes neither. Most sequences of a cohort are + read errors seen once, and their evidence need not be added up. The + quality route, and a rule with no route, count reads across samples: + any sequence can pass those. + """ + if rule.quality_route_enabled or not rule.any_route_enabled: + return None + needed = min( + ([rule.reproducible_min_reads] if rule.reproducibility_route_enabled else []) + + ([rule.depth_min_reads] if rule.depth_route_enabled else []) + ) + if needed <= 1: + return None + return {key for counts in per_sample_counts for key, count in counts.items() if count >= needed} + + def collect_evidence( per_sample_counts: Sequence[Mapping[Tuple[int, str], int]], per_sample_quality: Sequence[Mapping[Tuple[int, str], Sequence[int]]], rule: EvidenceRule, + only: Optional[Set[Tuple[int, str]]] = None, ) -> Dict[Tuple[int, str], EvidenceSupport]: + """Each sequence's evidence, added up over the samples; with ``only``, of those sequences alone.""" """Aggregate (global count, clean reads, supporting samples, max sample count) per key.""" quality_index = QUALITY_THRESHOLDS.index(rule.discovery_min_quality) floor = rule.min_supporting_freq @@ -3436,6 +3548,8 @@ def collect_evidence( for (marker_index, _), count in counts.items(): locus_totals[marker_index] += count for key, count in counts.items(): + if only is not None and key not in only: + continue entry = evidence[key] entry[0] += count if floor > 0.0 and count < floor * locus_totals[key[0]]: @@ -3448,6 +3562,8 @@ def collect_evidence( if count > entry[3]: entry[3] = count for key, values in quality.items(): + if only is not None and key not in only: + continue if len(values) > quality_index: evidence[key][1] += values[quality_index] return {key: EvidenceSupport(entry[0], entry[1], entry[2], entry[3]) for key, entry in evidence.items()} @@ -3533,6 +3649,7 @@ def supported_sequences( [result.counts for result in sample_results], [result.quality_support for result in sample_results], rule, + only=_could_pass([result.counts for result in sample_results], rule), ) protected: Dict[int, set[str]] = { locus.index: {locus.ref_tag, locus.alt_tag} for locus in loci @@ -3621,12 +3738,11 @@ def apply_partial_reads( summary = Counter() updated = [] for result in sample_results: - counts: Dict[Tuple[int, str], int] = defaultdict(int, result.counts) - quality_support: Dict[Tuple[int, str], List[int]] = defaultdict( - lambda: [0] * len(QUALITY_THRESHOLDS) - ) - for key, values in result.quality_support.items(): - quality_support[key] = list(values) + # The sample's own tables stand until a partial read lands in them: most + # samples have none, and copying every sequence of every sample is the + # larger part of this stage's time and memory. + counts = result.counts + quality_support = result.quality_support qc = Counter(result.qc) for key, count in result.partial_counts.items(): destination_sequence, status = mappings[key] @@ -3635,17 +3751,18 @@ def apply_partial_reads( if destination_sequence is None: continue destination = (key[0], destination_sequence) - counts[destination] += count - for quality_index_, value in enumerate(result.partial_quality_support.get(key, ())): - quality_support[destination][quality_index_] += value - updated.append( - dataclasses.replace( - result, - counts=dict(counts), - quality_support={key: tuple(values) for key, values in quality_support.items()}, - qc=dict(qc), - ) - ) + if counts is result.counts: + counts = dict(counts) + counts[destination] = counts.get(destination, 0) + count + added = result.partial_quality_support.get(key, ()) + if added: + if quality_support is result.quality_support: + quality_support = dict(quality_support) + tally = list(quality_support.get(destination) or [0] * len(QUALITY_THRESHOLDS)) + for quality_index_, value in enumerate(added): + tally[quality_index_] += value + quality_support[destination] = tuple(tally) + updated.append(dataclasses.replace(result, counts=counts, quality_support=quality_support, qc=dict(qc))) return updated, dict(summary) @@ -3781,9 +3898,14 @@ def finalize_counts( rule: EvidenceRule, gap_band: int = GAP_BAND_DEFAULT, jobs: int = 1, + release: bool = False, ) -> List[SampleResult]: """Stage 5: denoise counts while preserving every evidence-passing sequence. + With ``release`` the list given is emptied as the samples are denoised + (each entry becomes ``None``): the caller hands its results over and + keeps only what is returned. + Protection is decided first, from pre-denoise evidence, so a real low-abundance allele cannot be absorbed by an abundant neighbor before it has had the chance to prove itself. Abundance-skew denoising then runs @@ -3812,6 +3934,10 @@ def _stage(label: str) -> None: protected = supported_sequences(sample_results, loci, rule) _stage("evidence protection") parallel_samples = jobs > 1 and len(sample_results) > 1 + # A sample as read holds every sequence, read errors included, and is several + # times its denoised size. With ``release`` each one is let go as soon as its + # denoised form is back, so the two never stand side by side for the cohort. + sample_denoised: List[SampleResult] = [] if parallel_samples: # Each sample's pass depends only on its own counts and the shared # protected set, so the samples are denoised across the workers; @@ -3820,23 +3946,26 @@ def _stage(label: str) -> None: max_workers=jobs, initializer=_finalize_init, initargs=(protected, denoise.sample_distance, denoise.alpha), ) as executor: - sample_denoised = list(executor.map(_denoise_sample_worker, sample_results)) + for index, denoised in enumerate(executor.map(_denoise_sample_worker, sample_results)): + sample_denoised.append(denoised) + if release: + sample_results[index] = None else: - sample_denoised = [ - _denoise_sample_result( - result, - protected, - max_distance=denoise.sample_distance, - alpha=denoise.alpha, + for index in range(len(sample_results)): + sample_denoised.append( + _denoise_sample_result( + sample_results[index], protected, max_distance=denoise.sample_distance, alpha=denoise.alpha + ) ) - for result in sample_results - ] + if release: + sample_results[index] = None _stage(f"per-sample denoise ({len(sample_results)} samples, jobs={jobs if parallel_samples else 1})") aggregate: Dict[int, Dict[str, int]] = defaultdict(lambda: defaultdict(int)) for result in sample_denoised: for (marker_index, sequence), count in result.counts.items(): aggregate[marker_index][sequence] += count - pooled_after_tag, _ = pooled_continuations(sample_results) if denoise.global_distance > 0 else ({}, 0) + # Denoising leaves a sample's continuations as they were read. + pooled_after_tag, _ = pooled_continuations(sample_denoised) if denoise.global_distance > 0 else ({}, 0) moves: Dict[int, Dict[str, str]] = {} if jobs > 1 and len(aggregate) > 1: # The pooled pass is independent per locus (its aggregate, the @@ -6084,15 +6213,20 @@ def _assign_samples( settings: AssignmentSettings, cache_dir: Optional[str], jobs: int, + keep_quality: bool = True, ) -> List[SampleResult]: """Stage 2: per-sample read processing — the only FASTQ-touching, expensive - stage — parallel across samples and skipped entirely on cache hits.""" + stage — parallel across samples and skipped entirely on cache hits. + + ``keep_quality`` is False when no evidence route reads the per-sequence + quality tallies: the results then come back without them + (_process_sample_worker).""" primer_index = PrimerIndex(loci) cache_fingerprint = _cache_fingerprint(loci, settings.cache_arguments())[:16] 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, keep_quality)) print(f"Processing {len(samples)} samples across {len(loci)} loci with {jobs} worker(s)...", file=sys.stderr) if jobs == 1: results = [] @@ -6254,12 +6388,12 @@ 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, keep_quality=rule.quality_route_enabled) # 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) denoise = DenoiseSettings(args.denoise_distance, args.global_denoise_distance, args.denoise_alpha) - results = finalize_counts(results, loci, denoise, rule, gap_band=settings.gap_band, jobs=args.jobs) + results = finalize_counts(results, loci, denoise, rule, gap_band=settings.gap_band, jobs=args.jobs, release=True) # Stage 6: evidence-gated emission with forced canonical rows. output = Path(args.output) output_summary = write_madc(output, loci, results, rule, _output_options(args, samples, output), settings.gap_band) diff --git a/tests/test_same_answers.py b/tests/test_same_answers.py new file mode 100644 index 0000000..86006ff --- /dev/null +++ b/tests/test_same_answers.py @@ -0,0 +1,316 @@ +"""Shortcuts that save time or memory in ``generate`` must give the answer of the plain way. + +Each test sets a shortcut beside the computation it stands in for, on made-up cases: + +- an N tag compared with a sequence in stretches (``_n_tag_fits``), beside the base-by-base comparison; +- the gapped prescreen that stops at the first pass that settles the question, beside the full bound; +- ``_gapped_edits`` skipping the Alt tag when the Ref tag's bound is too far, beside both tags in full; +- ``PrimerIndex.match`` taking its search up from a stored state, beside a search from the first base; +- protection decided from the sequences that could pass (``_could_pass``), beside every sequence's evidence; +- partial reads added without copying a sample's tables, beside the tables built anew; +- ``finalize_counts`` letting the samples go as it denoises them, beside keeping them; +- a read pass that returns no quality tallies when no route reads them, beside one that does. +""" + +import dataclasses +import random +import sys +import unittest +from collections import Counter, defaultdict +from pathlib import Path + +REPO = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(REPO)) + +import madcats as mp # noqa: E402 + +BAND = 10 + + +def random_bases(rng, length, alphabet="ACGT"): + return "".join(rng.choice(alphabet) for _ in range(length)) + + +def mutated(rng, sequence, edits, alphabet="ACGT"): + """``sequence`` after ``edits`` random substitutions, insertions and deletions, at its own length.""" + bases = list(sequence) + for _ in range(edits): + at = rng.randrange(len(bases)) + kind = rng.choice("ssid") + if kind == "s": + bases[at] = rng.choice(alphabet) + elif kind == "i": + bases.insert(at, rng.choice(alphabet)) + elif len(bases) > 5: + del bases[at] + return ("".join(bases) + random_bases(rng, len(sequence)))[: len(sequence)] + + +def marker(index, ref, target, alt_base, left=20, name=None): + return mp.Locus(index, name or f"m{index}", ref[:left], "", ref[target], alt_base, target, ref, + ref[:target] + alt_base + ref[target + 1:]) + + +def sample_result(counts, quality=None, partial=None, partial_quality=None, name="s1"): + return mp.SampleResult(mp.Sample(name, name, "unused", {}), dict(counts), dict(quality or {}), dict(partial or {}), + dict(partial_quality or {}), {}) + + +class ModuleTests(unittest.TestCase): + def test_the_module_under_test_is_the_repository_s(self): + self.assertEqual(Path(mp.__file__).resolve().parent, REPO) + + +class NTagTests(unittest.TestCase): + def test_stretches_between_the_ns_decide_as_the_base_by_base_comparison_does(self): + rng = random.Random(11) + fits = 0 + for _ in range(3000): + sequence = random_bases(rng, rng.choice((20, 54, 81))) + tag = list(sequence if rng.random() < 0.6 else mutated(rng, sequence, rng.randrange(1, 3))) + for _ in range(rng.randrange(1, 4)): + tag[rng.randrange(len(tag))] = "N" + tag = "".join(tag) + expected = mp.compatible_mismatches(tag, sequence, 0) == 0 + self.assertEqual(mp._n_tag_fits(tag.split("N"), sequence), expected, (tag, sequence)) + fits += expected + self.assertGreater(fits, 500) + + def test_a_tag_with_another_ambiguity_code_goes_to_the_base_by_base_comparison(self): + # R fits A and G: the stretches differ from the sequence, yet the tag fits it. + # The Ref tag holds a C there, so the tag fits the one sequence only. + ref = "ACGTACGTACGTACGTACGTAAAACCCCGGGGTTTTACGT" + locus = marker(0, ref, 30, "A") + concrete = ref[:9] + "A" + ref[10:] + coded = ref[:9] + "R" + ref[10:20] + "N" + ref[21:] + counts = {(0, concrete): 40, (0, coded): 3} + quality = defaultdict(lambda: [0, 0, 0, 0]) + qc = Counter() + mp.resolve_n_tags(counts, quality, [locus], qc) + self.assertEqual(counts, {(0, concrete): 43}) + self.assertEqual(qc["reads_n_mapped"], 3) + + +class PrescreenTests(unittest.TestCase): + def cases(self, seed, count): + rng = random.Random(seed) + for _ in range(count): + length = rng.choice((41, 54, 81)) + ref = random_bases(rng, length) + if rng.random() < 0.2: + ref = ref[:7] + rng.choice("RYSWKM") + ref[8:] + read = random_bases(rng, length) if rng.random() < 0.2 else mutated(rng, ref.translate(str.maketrans("RYSWKM", "ACCAGA")), rng.randrange(0, 9)) + yield rng, read, ref + + def test_stopping_at_the_first_pass_never_changes_the_side_of_the_budget(self): + for rng, read, ref in self.cases(5, 3000): + bound = mp.gapped_prescreen(read, ref, BAND) + for enough in (0, 2, 5, 9, 16): + quick = mp.gapped_prescreen(read, ref, BAND, enough) + self.assertEqual(quick <= enough, bound <= enough, (read, ref, enough)) + self.assertGreaterEqual(quick, bound) + + def test_gapped_edits_is_the_same_with_the_alt_tag_skipped(self): + def plain(tag, locus, budget): + best = None + for template in (locus.ref_tag, locus.alt_tag): + if mp.gapped_prescreen(tag, template, BAND) > budget: + continue + edits, substitutions, gap_bases, gap_events, _, _ = mp.gapped_stats(tag, template, BAND) + if edits > budget or not mp.gapped_explanation_ok(substitutions, gap_bases, gap_events): + continue + best = edits if best is None else min(best, edits) + return best + + believed = 0 + for rng, read, ref in self.cases(6, 1500): + target = rng.randrange(25, len(ref) - 2) + if ref[target] not in "ACGT": + continue + locus = marker(0, ref, target, rng.choice([b for b in "ACGT" if b != ref[target]])) + for budget in (4, len(ref) // 5): + got = mp._gapped_edits(read, locus, budget, BAND) + self.assertEqual(got, plain(read, locus, budget), (read, ref, budget)) + believed += got is not None + self.assertGreater(believed, 200) + + +class PrimerMatchTests(unittest.TestCase): + def test_a_search_taken_up_from_a_stored_state_finds_what_a_fresh_one_finds(self): + rng = random.Random(3) + loci = [] + stem = random_bases(rng, 14) + for index in range(60): + primer = (stem[: rng.randrange(6, 14)] if index % 3 == 0 else "") + random_bases(rng, rng.randrange(8, 20)) + if index % 10 == 0: + primer = primer[:5] + "R" + primer[6:] + tag = primer + random_bases(rng, 60 - len(primer)) + loci.append(mp.Locus(index, f"m{index}", primer, "", tag[45], "A" if tag[45] != "A" else "C", 45, tag, + tag[:45] + ("A" if tag[45] != "A" else "C") + tag[46:])) + loci.append(dataclasses.replace(loci[0], index=60, marker="nested", left_primer=loci[0].left_primer[:9])) + index = mp.PrimerIndex(loci) + found = 0 + for _ in range(4000): + read = loci[rng.randrange(len(loci))].ref_tag + if rng.random() < 0.5: + read = mutated(rng, read, rng.randrange(1, 3), "ACGTN") + if rng.random() < 0.2: + read = read[: rng.randrange(1, 30)] # shorter than a primer, or than the stored head + for budget in (0, 1): + fresh = mp.PrimerIndex(loci).match(read, budget) + self.assertEqual(index.match(read, budget), fresh, (read, budget)) + found += bool(fresh) + self.assertGreater(found, 2000) + self.assertEqual(index.match("", 1), []) + + +class EvidenceTests(unittest.TestCase): + RULES = ( + mp.EvidenceRule(1, 20, 0, 10, 2, 30, 0.0), # the defaults + mp.EvidenceRule(3, 20, 0, 10, 2, 0, 0.0), # reproducibility only + mp.EvidenceRule(1, 20, 0, 10, 0, 30, 0.0), # depth only + mp.EvidenceRule(1, 20, 0, 5, 2, 15, 0.10), # with the supporting-frequency floor + mp.EvidenceRule(1, 20, 4, 10, 2, 30, 0.0), # the quality route as well: any sequence can pass + mp.EvidenceRule(2, 20, 0, 0, 0, 0, 0.0), # no route: the global count alone + mp.EvidenceRule(1, 20, 0, 1, 1, 0, 0.0), # one read in one sample is enough + ) + + def cohort(self, seed): + rng = random.Random(seed) + ref = random_bases(rng, 30) + loci = [marker(0, ref, 20, "A" if ref[20] != "A" else "C", left=8)] + sequences = [mutated(rng, ref, rng.randrange(1, 3)) for _ in range(25)] + results = [] + for number in range(6): + counts, quality = {}, {} + for sequence in sequences: + if rng.random() < 0.6: + reads = rng.choice((1, 1, 1, 2, 4, 9, 10, 12, 29, 30, 45)) + counts[(0, sequence)] = reads + quality[(0, sequence)] = (reads, rng.randrange(reads + 1), 0, 0) + results.append(sample_result(counts, quality, name=f"s{number}")) + return loci, results + + def test_protection_from_the_sequences_that_could_pass_is_protection_from_all_of_them(self): + some = 0 + for seed in range(40): + loci, results = self.cohort(seed) + for rule in self.RULES: + evidence = mp.collect_evidence([r.counts for r in results], [r.quality_support for r in results], rule) + expected = {loci[0].ref_tag, loci[0].alt_tag} | { + sequence for (_, sequence), values in evidence.items() if rule.evaluate(*values)[0] + } + self.assertEqual(mp.supported_sequences(results, loci, rule), {0: expected}, (seed, rule)) + some += len(expected) > 2 + self.assertGreater(some, 100) + + def test_a_sequence_left_out_is_one_that_fails(self): + loci, results = self.cohort(1) + rule = self.RULES[0] + could = mp._could_pass([r.counts for r in results], rule) + evidence = mp.collect_evidence([r.counts for r in results], [r.quality_support for r in results], rule) + self.assertTrue(0 < len(could) < len(evidence)) + for key, values in evidence.items(): + if key not in could: + self.assertFalse(rule.evaluate(*values)[0]) + self.assertIsNone(mp._could_pass([r.counts for r in results], self.RULES[4])) + self.assertIsNone(mp._could_pass([r.counts for r in results], self.RULES[5])) + self.assertIsNone(mp._could_pass([r.counts for r in results], self.RULES[6])) + + +class PartialReadTests(unittest.TestCase): + def setUp(self): + rng = random.Random(8) + self.ref = random_bases(rng, 40) + self.locus = marker(0, self.ref, 30, "A" if self.ref[30] != "A" else "C", left=10) + self.rule = mp.EvidenceRule(1, 20, 0, 10, 2, 30, 0.0) + ref, alt = self.locus.ref_tag, self.locus.alt_tag + noise = ref[:15] + ("A" if ref[15] != "A" else "C") + ref[16:] + self.full = {(0, ref): 50, (0, alt): 40, (0, noise): 1} + self.quality = {(0, ref): (50, 48, 40, 0), (0, alt): (40, 40, 30, 0), (0, noise): (1, 1, 0, 0)} + + def test_a_sample_without_partial_reads_keeps_its_tables(self): + results = [sample_result(self.full, self.quality, name=f"s{i}") for i in range(2)] + updated, summary = mp.apply_partial_reads(results, [self.locus], "on", self.rule) + for before, after in zip(results, updated): + self.assertIs(after.counts, before.counts) + self.assertIs(after.quality_support, before.quality_support) + self.assertEqual(summary, {}) + + def test_a_partial_read_lands_in_a_copy_and_adds_its_reads_and_tallies(self): + ref, alt = self.locus.ref_tag, self.locus.alt_tag + partial = {(0, alt[:35]): 7, (0, ref[:20]): 3, (0, "T" * 33): 2} # assigned, ambiguous, unmapped + partial_quality = {(0, alt[:35]): (7, 6, 0, 0)} + results = [ + sample_result(self.full, self.quality, partial, partial_quality, name="s1"), + sample_result({(0, ref): 60}, {(0, ref): (60, 60, 60, 0)}, {(0, alt[:36]): 4}, {(0, alt[:36]): (4, 4, 4, 1)}, name="s2"), + sample_result(self.full, self.quality, name="s3"), + ] + kept = [dict(r.counts) for r in results], [dict(r.quality_support) for r in results] + updated, summary = mp.apply_partial_reads(results, [self.locus], "on", self.rule) + self.assertEqual(updated[0].counts, {**self.full, (0, alt): 47}) + self.assertEqual(updated[0].quality_support, {**self.quality, (0, alt): (47, 46, 30, 0)}) + # The Alt row is new to the second sample: it comes after the rows the sample had. + self.assertEqual(list(updated[1].counts.items()), [((0, ref), 60), ((0, alt), 4)]) + self.assertEqual(updated[1].quality_support, {(0, ref): (60, 60, 60, 0), (0, alt): (4, 4, 4, 1)}) + self.assertEqual(summary, {"reads_assigned": 11, "reads_ambiguous": 3, "reads_unmapped": 2}) + self.assertEqual(updated[0].qc, {"partial_reads_assigned": 7, "partial_reads_ambiguous": 3, "partial_reads_unmapped": 2}) + # The samples handed in are as they were. + self.assertEqual(([dict(r.counts) for r in results], [dict(r.quality_support) for r in results]), kept) + self.assertIs(updated[2].counts, results[2].counts) + + +class ReleaseTests(unittest.TestCase): + def cohort(self): + rng = random.Random(21) + ref = random_bases(rng, 40) + locus = marker(0, ref, 30, "A" if ref[30] != "A" else "C", left=10) + error = ref[:12] + ("A" if ref[12] != "A" else "C") + ref[13:] + novel = ref[:22] + ("A" if ref[22] != "A" else "C") + ref[23:] + results = [ + sample_result({(0, ref): 80, (0, locus.alt_tag): 60, (0, error): 2, (0, novel): 25}, + {(0, ref): (80, 80, 70, 0), (0, error): (2, 1, 0, 0)}, name=f"s{i}") + for i in range(4) + ] + return locus, results + + def test_letting_the_samples_go_changes_nothing_but_the_list_handed_in(self): + rule = mp.EvidenceRule(1, 20, 0, 10, 2, 30, 0.0) + denoise = mp.DenoiseSettings(1, 1, 2.0) + locus, results = self.cohort() + kept = mp.finalize_counts(results, [locus], denoise, rule, BAND) + self.assertEqual(len([r for r in results if r is not None]), 4) + handed_over = list(results) + released = mp.finalize_counts(handed_over, [locus], denoise, rule, BAND, release=True) + self.assertEqual(handed_over, [None] * 4) + self.assertEqual([(r.counts, r.quality_support, r.qc) for r in released], [(r.counts, r.quality_support, r.qc) for r in kept]) + self.assertEqual(released[0].counts[(0, locus.ref_tag)], 82) # the error's reads went to the Ref row + + +class QualityTallyTests(unittest.TestCase): + def test_a_result_without_tallies_is_the_same_result_otherwise(self): + import gzip + import tempfile + rng = random.Random(4) + ref = random_bases(rng, 40) + locus = marker(0, ref, 30, "A" if ref[30] != "A" else "C", left=10) + with tempfile.TemporaryDirectory() as directory: + fastq = Path(directory) / "s1.fastq.gz" + with gzip.open(fastq, "wt") as handle: + for number, sequence in enumerate([ref] * 12 + [locus.alt_tag] * 9 + [ref[:33]] * 3): + handle.write(f"@r{number}\n{sequence}\n+\n{'I' * len(sequence)}\n") + settings = mp.AssignmentSettings( + tag_length=40, max_offtarget_mismatches=8, primer_mismatches=1, gap_band=BAND, partial_min_length=31, + ) + sample = mp.Sample("s1", "s1", str(fastq), {}) + with_tallies, without = ( + mp._assign_samples([sample], [locus], settings, None, 1, keep_quality=keep)[0] for keep in (True, False) + ) + self.assertEqual(with_tallies.quality_support[(0, ref)], (12, 12, 12, 12)) + self.assertEqual(with_tallies.partial_quality_support[(0, ref[:33])], (3, 3, 3, 3)) + self.assertEqual((without.quality_support, without.partial_quality_support), ({}, {})) + self.assertEqual((without.counts, without.partial_counts, without.qc), (with_tallies.counts, with_tallies.partial_counts, with_tallies.qc)) + + +if __name__ == "__main__": + unittest.main() From 766536f408518a03d2f9f631abfb2d1fe7b1fb82 Mon Sep 17 00:00:00 2001 From: Alexander Sandercock <39815775+alex-sandercock@users.noreply.github.com> Date: Thu, 3 Dec 2026 13:45:32 -0500 Subject: [PATCH 2/2] generate: review fixes for the time and memory shortcuts The primer search no longer keeps a read start that leads to no primer. Reads that match no primer share few starts, and keeping theirs added about 100 MB to a worker on a sample of random reads (189 MB against 86 MB). On real samples the store is now 5 MB to 13 MB. The gapped prescreen runs the design tag's pass first, because its bit masks are cached. No decision changes on 136,628 calls recorded from one pecan, one alfalfa and one sweetpotato sample. collect_evidence has one docstring, finalize_counts says its list must be mutable, and _n_tag_fits says it expects one length. Five new tests: the primer search beside a primer-by-primer comparison, the store without dead starts, an emptied store, release across worker processes, and Alt tags several bases from the Ref tag. The quality-tally test now also reads a cache written by a run that returned no tallies. The three cohorts' tables, variants sidecars and cache contents are the same as before these changes, and the QC files are the same apart from the time stamp and the output paths. The development record now says so, gives back-to-back times against 0.13.0 for sweetpotato and alfalfa, and gives the workers' memory. --- docs/DEVELOPMENT.md | 34 +++++--- docs/src/development/changelog.md | 2 +- madcats.py | 28 ++++--- tests/test_same_answers.py | 130 +++++++++++++++++++++++++++--- 4 files changed, 161 insertions(+), 33 deletions(-) diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index d5010e2..1233064 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -2167,16 +2167,25 @@ marker. A marker that leads its group has an empty `LocusGroup` cell and now cou On the grapevine panel `auto` had linked `12_996164__t192` with `13_13607473` that way; their shared window is chromosome 12 sequence. -**Run time and memory.** With 8 jobs the pecan cohort (376 samples) takes 657 s, alfalfa (356) -262 s and sweetpotato (80) 204 s. 0.13.0 took 1,249 s, 409 s and 343 s. The main process peaks at -7.0 GB, 3.8 GB and 1.75 GB (peak memory footprint, which counts compressed pages). +**Run time and memory.** With 8 jobs, and run back to back with 0.13.0, the sweetpotato cohort +(80 samples) takes 189 s against 323 s, and the alfalfa cohort (356) takes 221 s against 417 s. +The pecan cohort (376) took 657 s against 1,249 s. Those two pecan runs were not back to back, and +the 657 s is from before the caches moved to gzip level 6. The main process peaks at 7.0 GB on +pecan, 4.1 GB on alfalfa and 1.8 GB on sweetpotato, against 12.5 GB, 9.4 GB and 2.9 GB with 0.13.0 +(peak memory footprint, which counts compressed pages). + +Each worker holds one sample at a time. Its read pass peaks at 136 MB to 293 MB on one sample of +these cohorts (peak resident size). That is 2% to 9% more than without the shortcuts, because the +primer search keeps a store of 5 MB to 13 MB. The read pass is about four fifths of a run, and three things dominate it. Each is done the cheap way that gives the same answer. A tag with an N is compared with a sequence in the stretches -between its N's. The gapped prescreen makes a design tag's bit masks once, stops at the first of -its two passes that settles the question, and skips the Alt tag when the Ref tag's bound is -already too far. The primer search is taken up from its state after 12 bases, which reads of one -amplicon share. +between its N's. The gapped prescreen makes a design tag's bit masks once, runs that tag's pass +first, stops at the first of its two passes that settles the question, and skips the Alt tag when +the Ref tag's bound is already too far. The primer search is taken up from its state after 12 +bases, which reads of one amplicon share. A start that leads to no primer is not kept. Reads that +match no primer share few starts, and keeping theirs added about 100 MB to a worker on a sample of +random reads. Most of a run's memory is sequences seen once or twice: 82% of the sequences of an alfalfa sample have one read. Partial reads are added without copying a sample's tables. Evidence is tallied @@ -2184,9 +2193,10 @@ only for sequences that reach a route's read count in some sample, because no ot pass. A sample as read is let go once it is denoised. The per-sequence quality tallies are counted and cached, and they stay in the worker unless the quality route is on. -Each shortcut gives the answer of the plain computation (`tests/test_same_answers.py`), and the -three cohorts' tables, variants sidecars and QC files are the same byte for byte with the -shortcuts as without. +Each shortcut gives the answer of the plain computation (`tests/test_same_answers.py`). With the +shortcuts, the three cohorts' tables and variants sidecars are the same byte for byte as without, +the cache contents are the same, and the QC files are the same apart from the time stamp and the +output paths. ## Downstream fixed allele IDs @@ -2293,7 +2303,7 @@ By default sample columns use the unique FASTQ filename stem. python3 -m unittest discover -s tests -v ``` -The suite contains 263 unit and end-to-end tests across ten files: +The suite contains 268 unit and end-to-end tests across ten files: - `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): @@ -2303,7 +2313,7 @@ The suite contains 263 unit and end-to-end tests across ten files: real `mappy` aligner are skipped when `mappy` is not installed) - `test_tiled_markers.py` (4): tiled markers across `generate` and `filter-paralogs` (1 `mappy` test is skipped when `mappy` is not installed) -- `test_same_answers.py` (12): each shortcut that saves time or memory in `generate` beside the +- `test_same_answers.py` (17): each shortcut that saves time or memory in `generate` beside the plain computation it stands in for - `test_example.py` (5): bundled `examples/madcats-demo` project against simulated truth - `test_docs.py` (1): synchronization between `docs/src/commands/` tables and the CLI parser diff --git a/docs/src/development/changelog.md b/docs/src/development/changelog.md index caeb9b0..bd02ae7 100644 --- a/docs/src/development/changelog.md +++ b/docs/src/development/changelog.md @@ -43,7 +43,7 @@ Notable changes by version. Measurements behind each change are in the uses the stored counts without modifying them. - **Other changes.** MADC readers accept a header whose first column is not `AlleleID`, as in HapApp's fixed-allele-ID output. The cache format is now 0.8.0, so existing caches rebuild once. - `generate` also runs faster: three DArTag cohorts took 36% to 47% less time than with 0.13.0. + `generate` also runs faster: three DArTag cohorts took 41% to 47% less time than with 0.13.0. This release also revises the CLI help text across subcommands. ## 0.13.0 diff --git a/madcats.py b/madcats.py index 2e0cadd..4f31cca 100644 --- a/madcats.py +++ b/madcats.py @@ -166,7 +166,9 @@ import time from collections import Counter, defaultdict from pathlib import Path -from typing import Dict, Iterable, Iterator, List, Mapping, MutableMapping, NamedTuple, Optional, Sequence, Set, Tuple +from typing import ( + Dict, Iterable, Iterator, List, Mapping, MutableMapping, MutableSequence, NamedTuple, Optional, Sequence, Set, Tuple, +) # ============================================================================ @@ -646,10 +648,11 @@ def gapped_prescreen(read: str, ref: str, band: int, enough: Optional[int] = Non value returned is then at or under ``enough`` but may be above the bound. """ n, m = len(read), len(ref) - read_consumed = min(_myers_prefix_distances(read, ref, design_is_pattern=False)[max(0, m - band):]) - if enough is not None and read_consumed <= enough: - return read_consumed - return min(read_consumed, min(_myers_prefix_distances(ref, read, design_is_pattern=True)[max(0, n - band):])) + # The pass with the design tag as the pattern goes first: its bit masks are made once per tag. + ref_consumed = min(_myers_prefix_distances(ref, read, design_is_pattern=True)[max(0, n - band):]) + if enough is not None and ref_consumed <= enough: + return ref_consumed + return min(ref_consumed, min(_myers_prefix_distances(read, ref, design_is_pattern=False)[max(0, m - band):])) def _gapped_dp(read: str, ref: str, band: int): @@ -2328,7 +2331,11 @@ def match(self, sequence: str, max_mismatches: int = 0) -> List[int]: if len(self._heads) >= PRIMER_MATCH_MEMO: self._heads.clear() states, found = self._search([(0, 0)], set(), head, max_mismatches) - known = self._heads[(head, max_mismatches)] = (tuple(states), frozenset(found)) + known = (tuple(states), frozenset(found)) + if states or found: + # A head that leads to no primer is not kept. Reads that match no primer share few + # heads, so keeping theirs would fill the store and save little. + self._heads[(head, max_mismatches)] = known states, found = known if not states or len(start) <= len(head): return sorted(found) @@ -2924,7 +2931,8 @@ def _n_tag_fits(stretches: Sequence[str], sequence: str) -> bool: The same answer as ``compatible_mismatches(tag, sequence, 0) == 0`` for a tag whose only ambiguity code is N: an N fits any base, and every other - base must be equal. + base must be equal. The tag and the sequence must have one length, which + the caller checks. """ start = 0 for stretch in stretches: @@ -3541,8 +3549,8 @@ def collect_evidence( rule: EvidenceRule, only: Optional[Set[Tuple[int, str]]] = None, ) -> Dict[Tuple[int, str], EvidenceSupport]: - """Each sequence's evidence, added up over the samples; with ``only``, of those sequences alone.""" - """Aggregate (global count, clean reads, supporting samples, max sample count) per key.""" + """Each sequence's evidence (global count, clean reads, supporting samples, max sample count), + added up over the samples; with ``only``, of those sequences alone.""" quality_index = QUALITY_THRESHOLDS.index(rule.discovery_min_quality) floor = rule.min_supporting_freq evidence: Dict[Tuple[int, str], List[int]] = defaultdict(lambda: [0, 0, 0, 0]) @@ -3896,7 +3904,7 @@ def _pooled_worker(item: Tuple[int, Dict[str, int]]) -> Tuple[int, Dict[str, str def finalize_counts( - sample_results: Sequence[SampleResult], + sample_results: MutableSequence[SampleResult], loci: Sequence[Locus], denoise: DenoiseSettings, rule: EvidenceRule, diff --git a/tests/test_same_answers.py b/tests/test_same_answers.py index 86006ff..d77a17b 100644 --- a/tests/test_same_answers.py +++ b/tests/test_same_answers.py @@ -5,7 +5,8 @@ - an N tag compared with a sequence in stretches (``_n_tag_fits``), beside the base-by-base comparison; - the gapped prescreen that stops at the first pass that settles the question, beside the full bound; - ``_gapped_edits`` skipping the Alt tag when the Ref tag's bound is too far, beside both tags in full; -- ``PrimerIndex.match`` taking its search up from a stored state, beside a search from the first base; +- ``PrimerIndex.match`` taking its search up from a stored state, beside a search from the first base + and beside a primer-by-primer comparison; - protection decided from the sequences that could pass (``_could_pass``), beside every sequence's evidence; - partial reads added without copying a sample's tables, beside the tables built anew; - ``finalize_counts`` letting the samples go as it denoises them, beside keeping them; @@ -18,6 +19,7 @@ import unittest from collections import Counter, defaultdict from pathlib import Path +from unittest import mock REPO = Path(__file__).resolve().parents[1] sys.path.insert(0, str(REPO)) @@ -123,21 +125,51 @@ def plain(tag, locus, budget): return best believed = 0 - for rng, read, ref in self.cases(6, 1500): - target = rng.randrange(25, len(ref) - 2) + skipped = Counter() # Alt tags skipped, by how many bases the two tags are apart + for rng, read, ref in self.cases(6, 3000): + target = rng.randrange(25, len(ref) - 6) if ref[target] not in "ACGT": continue locus = marker(0, ref, target, rng.choice([b for b in "ACGT" if b != ref[target]])) + design = rng.choice(("one base", "several bases", "deletion")) + if design == "several bases": + alt = list(locus.alt_tag) + for at in rng.sample(range(target + 1, len(ref)), 5): + alt[at] = rng.choice([b for b in "ACGT" if b != alt[at]]) + locus = dataclasses.replace(locus, alt_tag="".join(alt)) + elif design == "deletion": + locus = dataclasses.replace(locus, alt_tag=ref[:target] + ref[target + 3:] + random_bases(rng, 3)) + if rng.random() < 0.5: # a read of the Alt haplotype: far from the Ref tag, near the Alt tag + read = mutated(rng, locus.alt_tag.translate(str.maketrans("RYSWKM", "ACCAGA")), rng.randrange(1, 4)) + apart = mp._tags_apart(locus.ref_tag, locus.alt_tag) for budget in (4, len(ref) // 5): got = mp._gapped_edits(read, locus, budget, BAND) - self.assertEqual(got, plain(read, locus, budget), (read, ref, budget)) + self.assertEqual(got, plain(read, locus, budget), (read, locus.ref_tag, locus.alt_tag, budget)) believed += got is not None - self.assertGreater(believed, 200) + if mp.gapped_prescreen(read, locus.ref_tag, BAND) - apart > budget: + skipped["one base" if apart == 1 else "more"] += 1 + self.assertGreater(believed, 400) + self.assertGreater(skipped["one base"], 50) + self.assertGreater(skipped["more"], 50) + + def test_the_alt_tag_is_read_when_the_two_tags_are_several_bases_apart(self): + # Six edits from the Ref tag is over a budget of four, but the tags are six bases apart: + # the Alt tag may still fit, so it must not be skipped. + ref = "ACGTTGCAAGCTTGACCGATAGGCTTACGGATCAGTTCGAC" + alt = list(ref) + for at in (20, 24, 28, 32, 35, 38): + alt[at] = "A" if alt[at] != "A" else "C" + alt = "".join(alt) + locus = dataclasses.replace(marker(0, ref, 20, alt[20]), alt_tag=alt) + read = alt[:10] + alt[11:] + "T" # the Alt haplotype with one base deleted + self.assertEqual(mp._tags_apart(ref, alt), 6) + self.assertGreater(mp.gapped_prescreen(read, ref, BAND), 4 + 1) + self.assertEqual(mp._gapped_edits(read, locus, 4, BAND), mp.gapped_stats(read, alt, BAND)[0]) + self.assertLessEqual(mp._gapped_edits(read, locus, 4, BAND), 2) class PrimerMatchTests(unittest.TestCase): - def test_a_search_taken_up_from_a_stored_state_finds_what_a_fresh_one_finds(self): - rng = random.Random(3) + def panel(self, rng): loci = [] stem = random_bases(rng, 14) for index in range(60): @@ -148,14 +180,23 @@ def test_a_search_taken_up_from_a_stored_state_finds_what_a_fresh_one_finds(self loci.append(mp.Locus(index, f"m{index}", primer, "", tag[45], "A" if tag[45] != "A" else "C", 45, tag, tag[:45] + ("A" if tag[45] != "A" else "C") + tag[46:])) loci.append(dataclasses.replace(loci[0], index=60, marker="nested", left_primer=loci[0].left_primer[:9])) - index = mp.PrimerIndex(loci) - found = 0 - for _ in range(4000): + return loci + + def reads(self, rng, loci, count): + for _ in range(count): read = loci[rng.randrange(len(loci))].ref_tag if rng.random() < 0.5: read = mutated(rng, read, rng.randrange(1, 3), "ACGTN") if rng.random() < 0.2: read = read[: rng.randrange(1, 30)] # shorter than a primer, or than the stored head + yield read + + def test_a_search_taken_up_from_a_stored_state_finds_what_a_fresh_one_finds(self): + rng = random.Random(3) + loci = self.panel(rng) + index = mp.PrimerIndex(loci) + found = 0 + for read in self.reads(rng, loci, 4000): for budget in (0, 1): fresh = mp.PrimerIndex(loci).match(read, budget) self.assertEqual(index.match(read, budget), fresh, (read, budget)) @@ -163,6 +204,55 @@ def test_a_search_taken_up_from_a_stored_state_finds_what_a_fresh_one_finds(self self.assertGreater(found, 2000) self.assertEqual(index.match("", 1), []) + def test_the_search_finds_the_primers_a_primer_by_primer_comparison_finds(self): + def one_by_one(read, loci, budget): + start = read[: max(len(locus.left_primer) for locus in loci)] + found = [] + for locus in loci: + primer = locus.left_primer + if len(primer) > len(start): + continue + apart = sum( + 1 for expected, base in zip(primer, start) + if base != expected and base not in mp.IUPAC_BASES.get(expected, ()) + ) + if apart <= budget: + found.append(locus.index) + return sorted(found) + + rng = random.Random(8) + loci = self.panel(rng) + index = mp.PrimerIndex(loci) + found = 0 + for read in list(self.reads(rng, loci, 3000)) + [random_bases(rng, 60) for _ in range(500)]: + for budget in (0, 1): + expected = one_by_one(read, loci, budget) + self.assertEqual(sorted(index.match(read, budget)), expected, (read, budget)) + found += bool(expected) + self.assertGreater(found, 1500) + + def test_a_head_that_leads_to_no_primer_is_not_kept(self): + rng = random.Random(9) + loci = self.panel(rng) + index = mp.PrimerIndex(loci) + met = sum(bool(index.match(random_bases(rng, 60), 1)) for _ in range(2000)) + self.assertLess(met, 200) # a random read seldom starts with one of 60 primers + self.assertLess(len(index._heads), 200) # and the 2,000 heads are not all kept + self.assertTrue(all(states or found for states, found in index._heads.values())) + self.assertTrue(all(index.match(locus.ref_tag, 1) for locus in loci)) + + def test_an_emptied_store_changes_no_answer(self): + rng = random.Random(10) + loci = self.panel(rng) + reads = list(self.reads(rng, loci, 1500)) + roomy = mp.PrimerIndex(loci) + expected = [roomy.match(read, 1) for read in reads] + with mock.patch.object(mp, "PRIMER_MATCH_MEMO", 5): + cramped = mp.PrimerIndex(loci) + self.assertEqual([cramped.match(read, 1) for read in reads], expected) + self.assertLessEqual(len(cramped._heads), 5) + self.assertGreater(len(roomy._heads), 5) + class EvidenceTests(unittest.TestCase): RULES = ( @@ -286,6 +376,17 @@ def test_letting_the_samples_go_changes_nothing_but_the_list_handed_in(self): self.assertEqual([(r.counts, r.quality_support, r.qc) for r in released], [(r.counts, r.quality_support, r.qc) for r in kept]) self.assertEqual(released[0].counts[(0, locus.ref_tag)], 82) # the error's reads went to the Ref row + def test_letting_the_samples_go_across_worker_processes_gives_the_same_samples(self): + rule = mp.EvidenceRule(1, 20, 0, 10, 2, 30, 0.0) + denoise = mp.DenoiseSettings(1, 1, 2.0) + locus, results = self.cohort() + kept = mp.finalize_counts(results, [locus], denoise, rule, BAND) + handed_over = list(results) + released = mp.finalize_counts(handed_over, [locus], denoise, rule, BAND, jobs=2, release=True) + self.assertEqual(handed_over, [None] * 4) + self.assertEqual([(r.sample.sample_id, r.counts, r.quality_support, r.qc) for r in released], + [(r.sample.sample_id, r.counts, r.quality_support, r.qc) for r in kept]) + class QualityTallyTests(unittest.TestCase): def test_a_result_without_tallies_is_the_same_result_otherwise(self): @@ -306,6 +407,15 @@ def test_a_result_without_tallies_is_the_same_result_otherwise(self): with_tallies, without = ( mp._assign_samples([sample], [locus], settings, None, 1, keep_quality=keep)[0] for keep in (True, False) ) + # A cache written by a run that reads no tallies serves a later run that does. + cache = str(Path(directory) / "cache") + written = mp._assign_samples([sample], [locus], settings, cache, 1, keep_quality=False)[0] + reused = mp._assign_samples([sample], [locus], settings, cache, 1, keep_quality=True)[0] + self.assertEqual((written.cache_hit, reused.cache_hit), (False, True)) + self.assertEqual((written.quality_support, written.partial_quality_support), ({}, {})) + self.assertEqual((reused.quality_support, reused.partial_quality_support), + (with_tallies.quality_support, with_tallies.partial_quality_support)) + self.assertEqual((reused.counts, reused.partial_counts), (with_tallies.counts, with_tallies.partial_counts)) self.assertEqual(with_tallies.quality_support[(0, ref)], (12, 12, 12, 12)) self.assertEqual(with_tallies.partial_quality_support[(0, ref[:33])], (3, 3, 3, 3)) self.assertEqual((without.quality_support, without.partial_quality_support), ({}, {}))