diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index 530e30a..26372c9 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -2263,12 +2263,12 @@ By default sample columns use the unique FASTQ filename stem. python3 -m unittest discover -s tests -v ``` -The suite contains 247 unit and end-to-end tests across nine files: +The suite contains 248 unit and end-to-end tests across nine 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): row alignment, unresolved-end handling, read continuation, and Ref/Alt tie-breaking -- `test_remove_primers.py` (30): `--remove-primers` trimming, merging, and collision guards +- `test_remove_primers.py` (31): `--remove-primers` trimming, merging, and collision guards - `test_filter_paralogs.py` (49): genome-based paralog filtering (13 tests invoking the real `mappy` aligner are skipped when `mappy` is not installed) - `test_tiled_markers.py` (4): tiled markers across `generate` and `filter-paralogs` (1 `mappy` diff --git a/docs/src/commands/generate.md b/docs/src/commands/generate.md index 2932f2c..39a27d5 100644 --- a/docs/src/commands/generate.md +++ b/docs/src/commands/generate.md @@ -157,6 +157,11 @@ Important considerations before enabling `--remove-primers on`: colliding rows retain their right primer and remain separate so reads never move between target alleles. The QC JSON records these events under `rows_right_primer_kept_collision`, while canonical Ref and Alt rows are still trimmed. +- **Rows that keep their right primer are reported.** The table does not mark these rows, so + `generate` prints how many rows kept their right primer, and for which reason, when it finishes. + The QC JSON lists each row under `primer_removal.rows_right_primer_kept` with its marker, + `AlleleID`, sequence as written, and reason (`target`, `short`, or `collision`). On the pecan, + alfalfa, and sweetpotato DArTag cohorts, fewer than 0.2% of rows kept their right primer. - **Trimmed tables are incompatible with untrimmed allele databases.** Any tool that matches full `AlleleSequence` strings requires the same primer setting on both sides (including `validate` against a vendor MADC). In particular, HapApp matches whole sequences against its allele database: diff --git a/docs/src/development/changelog.md b/docs/src/development/changelog.md index 7fa115a..5b2576a 100644 --- a/docs/src/development/changelog.md +++ b/docs/src/development/changelog.md @@ -31,7 +31,8 @@ Notable changes by version. Measurements behind each change are in the target are trimmed where their primer is detected. If right-primer trimming would collapse rows from different allele groups (Ref/RefMatch, Alt/AltMatch, or Other) into the same sequence, non-canonical colliding rows retain their right primer and remain separate so no reads ever move - between target alleles (`rows_right_primer_kept_collision`). + between target alleles (`rows_right_primer_kept_collision`). `generate` prints how many rows kept + their right primer and lists them in the QC JSON under `primer_removal.rows_right_primer_kept`. - **Unresolved trailing gaps in `generate`.** When a gapped alignment explains a row with fewer edits than substitutions alone but leaves fewer than 12 bases after its last gap, `generate` no longer guesses at fixed offsets. It reads the row only up to the first position where the gap and diff --git a/madcats.py b/madcats.py index a54f741..17a5422 100644 --- a/madcats.py +++ b/madcats.py @@ -4541,9 +4541,16 @@ def trim_locus_rows( gap_band: int, tally: Counter, continuations: Optional[Mapping[str, str]] = None, + kept: Optional[Dict[str, str]] = None, ): """One marker's rows without their primers: ``(locus, rows, counts, readings)`` as the table shows them. + ``kept``, when given, receives every row that keeps its right primer, as + ``{sequence as printed: reason}``. The reason is ``target`` (the cut + would remove the base the category was read from), ``short`` (fewer than + TRIM_MIN_BASES would remain) or ``collision`` (the row would become the + sequence of a row of another allele group). + ``rows`` are write_madc's ``(order, category, sequence)`` and ``counts`` the per-sample reads of each sequence. Categories were decided on the full tags and are carried, never re-derived. The left primer is a @@ -4617,6 +4624,8 @@ def settled_alignment(sequence: str): tally["rows_right_primer_removed"] += after_left + len(trimmed) < len(sequence) if cuts[sequence][1]: tally[f"rows_right_primer_kept_{cuts[sequence][1]}"] += 1 + if kept is not None: + kept.setdefault(trimmed, cuts[sequence][1]) groups[trimmed].append((category, sequence, total)) if trimmed not in summed_counts: summed_counts[trimmed] = list(reads) @@ -4943,6 +4952,7 @@ def write_madc( continuations, bases_after_tag = pooled_continuations(results) read_continuation = {"bases_after_tag": bases_after_tag, "rows_settled": 0, "reads_settled": 0} primer_tally: Counter = Counter() + primer_kept_rows: List[Dict[str, str]] = [] if options.remove_primers: geometry = amplicon_geometry(loci) primer_sites = {locus.marker: right_primer_site(locus, geometry) for locus in loci} @@ -4990,10 +5000,12 @@ def write_madc( sequence: [result.counts.get((locus.index, sequence), 0) for result in results] for _, _, sequence in rows } readings = designed = None + kept_primer: Dict[str, str] = {} if options.remove_primers: # From here on ``locus`` is the marker as the table shows it. locus, rows, counts_by_sequence, readings = trim_locus_rows( - locus, rows, counts_by_sequence, primer_sites[locus.marker][0], gap_band, primer_tally, after_tag + locus, rows, counts_by_sequence, primer_sites[locus.marker][0], gap_band, primer_tally, after_tag, + kept_primer, ) designed = _describe(locus.ref_tag, locus.alt_tag, gap_band, *readings[locus.alt_tag]) type_serials = Counter() @@ -5009,6 +5021,10 @@ def write_madc( if options.number_match_ids and category in ("RefMatch", "AltMatch", "Other"): suffix += f"_{type_serials[category]:04d}" allele_id = f"{locus.marker}|{suffix}" + if sequence in kept_primer: + primer_kept_rows.append({ + "marker": locus.marker, "allele_id": allele_id, "sequence": sequence, "reason": kept_primer[sequence], + }) if category in ("Ref", "Alt"): call_rate = format_number(canonical_call_rate) avg_count_ref = format_number(avg_ref) @@ -5078,6 +5094,9 @@ def write_madc( "right_primers_reverse_complemented": geometry[1] if geometry else None, "markers_by_right_primer": dict(Counter(reason for _, reason in primer_sites.values())), **{name: primer_tally[name] for name in PRIMER_REMOVAL_TALLIES}, + # The rows as written that still end in their right primer. The + # counts above are taken before rows merge, so they can exceed this list. + "rows_right_primer_kept": primer_kept_rows, } return { **primer_removal, @@ -6277,20 +6296,37 @@ def run_generate(args: argparse.Namespace) -> int: } _write_json(qc_path, qc) if "primer_removal" in output_summary: - removal = output_summary["primer_removal"] - length = removal["amplicon_length"] - print( - f"Removed primers: the right primer was located at {removal['markers_by_right_primer'].get('located', 0):,} " - f"of {len(loci):,} markers (" - + (f"amplicon length {length}" if length else "the panel shows no single amplicon length") - + f"); {removal['rows_merged']:,} rows became identical to another and were added to it", - file=sys.stderr, - ) + print(primer_removal_notice(output_summary["primer_removal"], len(loci)), file=sys.stderr) print(f"Wrote {output_summary['rows']:,} allele rows to {output}", file=sys.stderr) print(f"Wrote QC/provenance to {qc_path}", file=sys.stderr) return 0 +def primer_removal_notice(removal: Mapping[str, object], marker_count: int) -> str: + """The line ``generate`` prints after it wrote a table without primers. + + It says how many rows still end in their right primer, and why, because + the table itself does not mark them. + """ + length = removal["amplicon_length"] + notice = ( + f"Removed primers: the right primer was located at {removal['markers_by_right_primer'].get('located', 0):,} " + f"of {marker_count:,} markers (" + + (f"amplicon length {length}" if length else "the panel shows no single amplicon length") + + f"); {removal['rows_merged']:,} rows became identical to another and were added to it" + ) + reasons = Counter(row["reason"] for row in removal["rows_right_primer_kept"]) + if reasons: + notice += ( + f"; rows that kept their right primer: {sum(reasons.values()):,} ({reasons['target']:,} to keep the target " + f"base, {reasons['short']:,} too short to cut, {reasons['collision']:,} to stay apart from a row of another " + "allele), listed in the QC file under primer_removal.rows_right_primer_kept" + ) + if removal["markers_right_primer_kept"]: + notice += f"; markers that kept the right primer on every row: {removal['markers_right_primer_kept']:,}" + return notice + + def run_validate(args: argparse.Namespace) -> int: report = validate_madc(Path(args.generated), Path(args.expected)) if args.report: diff --git a/tests/test_remove_primers.py b/tests/test_remove_primers.py index 4479787..99cb70d 100644 --- a/tests/test_remove_primers.py +++ b/tests/test_remove_primers.py @@ -443,6 +443,7 @@ def test_table_without_primers(self): "rows_right_primer_kept_short": 0, "rows_right_primer_kept_collision": 0, "markers_right_primer_kept": 0, + "rows_right_primer_kept": [], }, ) self.assertEqual(summary["rows"], 2 * len(self.loci) + 2) @@ -620,6 +621,7 @@ def test_low_count_unresolved_row_cannot_poison_merged_clean_or_canonical_row(se s_alt = left + snp_body + right[:-1] + "A" s_other = left + snp_body + right[:-1] + "C" tally_col = Counter() + kept_col = {} _, tr_col, counts_col, _ = mp.trim_locus_rows( locus, [(0, "Ref", ref), (1, "Alt", alt), (3, "AltMatch", s_alt), (4, "Other", s_other)], @@ -627,13 +629,37 @@ def test_low_count_unresolved_row_cannot_poison_merged_clean_or_canonical_row(se site, GAP_BAND, tally_col, + kept=kept_col, ) self.assertEqual(tally_col["rows_merged_across_allele_groups"], 0) self.assertEqual(tally_col["rows_right_primer_kept_collision"], 2) + self.assertEqual(kept_col, {s_alt[len(left):]: "collision", s_other[len(left):]: "collision"}) col_by_seq = {seq: (cat, counts_col[seq]) for _, cat, seq in tr_col} self.assertEqual(col_by_seq[s_alt[len(left):]], ("AltMatch", [15])) self.assertEqual(col_by_seq[s_other[len(left):]], ("Other", [80])) + def test_rows_that_keep_their_right_primer_are_listed_in_the_qc_and_counted_in_the_notice(self): + locus = self.loci[0] + parts = self.parts[locus.marker] + kept = tag_of(parts, parts[1][: TARGET - 2]) # a short product: the cut would remove the base its category came from + canonical = {locus.ref_tag: (40, 0), locus.alt_tag: (0, 30)} + with tempfile.TemporaryDirectory() as directory: + summary, table = self.write({locus.marker: {**canonical, kept: (12, 9)}}, True, directory) + clean, _ = self.write({locus.marker: canonical}, True, directory) + removal = summary["primer_removal"] + row = next(row for row in table if row["AlleleSequence"] == kept[LEFT:]) + self.assertEqual( + removal["rows_right_primer_kept"], + [{"marker": locus.marker, "allele_id": row["AlleleID"], "sequence": kept[LEFT:], "reason": "target"}], + ) + self.assertEqual(removal["rows_right_primer_kept_target"], 1) + notice = mp.primer_removal_notice(removal, len(self.loci)) + self.assertIn("rows that kept their right primer: 1 (1 to keep the target base, 0 too short to cut, 0 to stay", notice) + self.assertIn("primer_removal.rows_right_primer_kept", notice) + # A table whose rows all lost their primers says nothing about kept primers. + self.assertEqual(clean["primer_removal"]["rows_right_primer_kept"], []) + self.assertNotIn("kept", mp.primer_removal_notice(clean["primer_removal"], len(self.loci))) + def test_off_is_the_default_and_adds_nothing_to_the_table_or_its_first_line(self): arguments = ["generate", "--fastq-dir", "fastq", "--output", "madc.csv", "--reference-tags", "tags.csv"] args = mp.build_parser().parse_args(arguments)